1、场景
Spring的事件为Bean和Bean之间的消息通信提供了支持。当一个Bean处理完一个任务之后,希望另外一个Bean知道并能做相应的处理,这时我们就需要另外一个Bean监听当前Bean所发送的事件。
2、流程
- 自定义事件,继承ApplicationEvent
- 定义事件监听器,实现ApplicationListener
- 使用容器发布事件
3、示例
自定义事件
public class DemoEvent extends ApplicationEvent {
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public DemoEvent(Object source, String msg) {
super(source);
this.msg = msg;
}
}
事件监听器
@Component
public class DemoListener implements ApplicationListener<DemoEvent> {
@Override
public void onApplicationEvent(DemoEvent demoEvent) {
String msg = demoEvent.getMsg();
System.out.println("DemoListener接收到DemoPublisher发布的消息:" + msg);
}
}
事件发布类
@Component
public class DemoPublisher {
@Autowired
private ApplicationContext applicationContext;
public void publish(String msg) {
applicationContext.publishEvent(new DemoEvent(this, msg));
}
}
配置类
@Configuration
@ComponentScan("com")
public class EventConfig {
}
测试
public class Main {
public static void main(String[] args){
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(EventConfig.class);
DemoPublisher publisher = context.getBean(DemoPublisher.class);
publisher.publish("世界那么大,我想去看看!");
context.close();
}
}
测试结果