SpringEvent事件机制

前言

Spring Event 机制使用起来比较简单。

  • 需要一个事件类
  • 需要监听当前事件类
  • 需要发布当前事件类的事件

简单了解一下

ApplicationEventPublisher用来发布事件,默认实现类 AbstractApplicationContext.

其中 ApplicationEventPublisher有两个 publishEvent 方法,在Spring Context 4.2之后就没有区别了。

demo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
@SpringBootApplication
public class StartSpringBootEventDemoApplication {

public static void main(String[] args) {
SpringApplication application = new SpringApplication(StartSpringBootEventDemoApplication.class);
application.run(args);
}

@Bean
public CommandLineRunner test(ApplicationEventPublisher applicationEventPublisher) {
return args -> {
/*发布事件*/
applicationEventPublisher.publishEvent(new CustomEvent(11111));
applicationEventPublisher.publishEvent(new CustomEvent2(22222));
};
}

/**
* 测试自定义事件类
*/
public static class CustomEvent {
/**
* 标识
*/
private final int id;

public CustomEvent(int id) {
this.id = id;
}

@Override
public String toString() {
return "CustomEvent{" + "id=" + id + '}';
}
}

/**
* 测试自定义事件类
*/
public static class CustomEvent2 {
/**
* 标识
*/
private final int id;

public CustomEvent2(int id) {
this.id = id;
}

@Override
public String toString() {
return "CustomEvent2{" + "id=" + id + '}';
}
}

/**
* 监听事件
*/
@EventListener(value = CustomEvent.class)
public void listener(CustomEvent customEvent) {
System.out.println("listener=>" + customEvent);
}

@EventListener
public void listener2(CustomEvent customEvent) {
System.out.println("listener2=>" + customEvent);
}

@EventListener(value = CustomEvent2.class)
public void listener3(CustomEvent2 customEvent) {
System.out.println("listener3=>" + customEvent);
}

@EventListener
public void listener4(CustomEvent2 customEvent) {
System.out.println("listener4=>" + customEvent);
}

@EventListener(value = {CustomEvent.class, CustomEvent2.class})
public void listener5(Object customEvent) {
System.out.println("listener5=>" + customEvent);
}

}

上面会输出

1
2
3
4
5
6
listener=>CustomEvent{id=11111}
listener5=>CustomEvent{id=11111}
listener2=>CustomEvent{id=11111}
listener3=>CustomEvent2{id=22222}
listener5=>CustomEvent2{id=22222}
listener4=>CustomEvent2{id=22222}

引入依赖

1
2
3
4
5
6
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>

本文地址: https://github.com/maxzhao-it/blog/post/ff3733f2/