主要就是三个部分: 事件、事件发布者、事件监听器。
@Component
// Aware 注入 applicationEventPublisher
public class MyPublisher implements ApplicationEventPublisherAware {
private ApplicationEventPublisher applicationEventPublisher;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
public void doPublisher(String msg){
applicationEventPublisher.publishEvent(new MyApplicationEvent(msg));
}
}
public class MyApplicationEvent extends ApplicationEvent {
public MyApplicationEvent(Object source) {
super(source);
}
}
public class MyListener implements ApplicationListener<MyApplicationEvent> {
// 监听MyApplicationEvent事件
@Override
public void onApplicationEvent(MyApplicationEvent event) {
String source = (String)event.getSource();
System.out.printf("监听者收到了消息" + source);
}
}
这样用 Publisher 发布消息 , 监听者就可以接收到消息了
MyPublisher myPublisher = (MyPublisher)applicationContext.getBean("myPublisher");
myPublisher.doPublisher("今天晚上吃啥");
initApplicationEventMulticaster 这个方法用于初始化事件广播器 代码 和 initMessageSource 大致相同,都是 先查找是否有用户自定义的 Multicaster 若没有初始化一个默认的。 至于是如何发布消息的 等我看完之后的代码再来补上吧
protected void initApplicationEventMulticaster() {
// 获取工厂
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
//首先判断是否已有xml文件定义了id为aplicationEventMulticaster的bean对象
//自定义的事件监听多路广播器需要实现AplicationEventMulticaster接口
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
// 保存多播事件
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isTraceEnabled()) {
logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
// 不存在 创建SimpleApplicationEventMulticaster
//因为SimpleApplicationEventMulticaster继承了AbstractApplicationEventMulticaster抽象类,而这个抽象类实现了aplicationEventMulticaster接口
//因此SimpleApplicationEventMulticaster是aplicationEventMulticaster接口的一个实现
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
// 注册 bean
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isTraceEnabled()) {
logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
}
}
}