事件发布功能,由事件源ApplicationEvent、事件发布者ApplicationEventPublisher、事件监听者ApplicationListener三部分组成
事件发布者发布指定的事件源,时间监听者监听指定的事件源
事件源
public class MyEvent extends ApplicationEvent {
private String msg;
public MyEvent(Object source,String msg) {
super(source);
this.msg = msg;
}
}
事件发布者
public class MyEventPublisher {
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
public void publish(String msg) {
applicationEventPublisher.publishEvent(new MyEvent(this, msg));
}
}
事件监听者
监听方式一
@Component
public class MyListener2 implements ApplicationListener<MyEvent> {
@Override
public void onApplicationEvent(MyEvent event) {
Object source = event.getSource();
System.out.println("source = " + source);
}
}
监听方式二
@Component
public class MyListener3 {
@EventListener
public void xxx(MyEvent event) {
Object source = event.getSource();
System.out.println("source = " + source);
}
}
Spring事件默认是同步的,通过在启动类Application上加上@EnableAsync开启异步。使用方法注解@Async可以作用在监听器的执行方法上,异步执行。@Async不带参数默认使用SpringBoot默认的线程池。推荐使用自定义的线程池: