Spring-Event

1. Demo

1.1 定义事件

定义事件可以是一个简单的POJO对象

1
2
3
4
5
6
@Data
@Builder
public class AacopyTestEvent {
private String name;
private String description;
}

1.2 编写监听事件处理类

监听事件需要

  • 在处理方法上添加@EventListener注解,
  • 在方法入参里加上对应的事件对象
  • 将方法所在类加入到spring容器
1
2
3
4
5
6
7
8
9
@Component
public class AacopyTestEventListener {

@EventListener
public void handleAacopyTestEvent(AacopyTestEvent aacopyTestEvent) {
System.out.println("接收到事件...");
System.out.println(aacopyTestEvent);
}
}

1.3 编写发布事件测试类

发布事件需要用ApplicationEventPublisher对象,或者ApplicationContext,ApplicationContext继承了ApplicationEventPublisher

1
2
3
4
5
6
7
8
9
10
11
12
@SpringBootTest
public class EventPublisherTest {

@Resource
private ApplicationEventPublisher applicationEventPublisher;

@Test
void testPublish() {
System.out.println("发送事件...");
applicationEventPublisher.publishEvent(AacopyTestEvent.builder().name("aacopy").description("aacopy.cn").build());
}
}
  • 执行结果
1
2
3
发送事件...
接收到事件...
AacopyTestEvent(name=aacopy, description=aacopy.cn)

2. 异步执行事件

发布事件和监听事件默认情况下是同步执行的,如果需要异步执行,只需要在监听方法上添加@Async