事件发布
Spring提供了两个接口实现发布事件,分别是:ApplicationEventPublisher和ApplicationEventMulticaster。
- ApplicationEventPublisher源码:
package org.springframework.context;
@FunctionalInterface
public interface ApplicationEventPublisher {
default void publishEvent(ApplicationEvent event) {
this.publishEvent((Object)event);
}
// spring 4.2后支持发布任何对象作为事件
void publishEvent(Object var1);
}
使用ApplicationEventPublisher发布事件的实例代码
@RestController
@RequestMapping("test/")
public class Test implements ApplicationContextAware {
//ApplicationContext 实现了ApplicationEventPublisher接口,为了省事直接拿来用
ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@RequestMapping(value = "publishEvent",method = {RequestMethod.POST})
public Demo publishEvent(@RequestBody Demo myEvent){
applicationContext.publishEvent(myEvent);
return myEvent;
}
}
关于Aware接口:Spring提供了各种aware接口用户获取不同的实例。
- ApplicationEventMulticaster源码
package org.springframework.context.event;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.core.ResolvableType;
import org.springframework.lang.Nullable;
public interface ApplicationEventMulticaster {
// 添加监听器
void addApplicationListener(ApplicationListener<?> var1);
// 以bean的方式添加监听器
void addApplicationListenerBean(String var1);
// 移除监听器
void removeApplicationListener(ApplicationListener<?> var1);
// 同上
void removeApplicationListenerBean(String var1);
void removeAllListeners();
//发布事件
void multicastEvent(ApplicationEvent var1);
// ResolvableType是泛型信息
void multicastEvent(ApplicationEvent var1, @Nullable ResolvableType var2);
}
ApplicationEventMulticaster发布事件demo
@RestController
@RequestMapping("test/")
public class Test {
@Autowired
MyEventListener2 myEventListener2;
SimpleApplicationEventMulticaster simpleApplicationEventMulticaster;
@RequestMapping(value = "multicastEvent",method = {RequestMethod.POST})
public String multicastEvent(@RequestBody Demo demo){
MyEvent myEvent = new MyEvent(demo);
simpleApplicationEventMulticaster = new SimpleApplicationEventMulticaster();
simpleApplicationEventMulticaster.addApplicationListener(myEventListener2);
simpleApplicationEventMulticaster.multicastEvent(myEvent);
return "multicastEvent succeed";
}
}
事件监听
- 注解方式实现事件监听
@Component
public class MyEventListener {
@Async
@EventListener
public String onMyMessage(Demo myEvent){
System.out.println("eventListener on message:"+JSON.toJSONString(myEvent));
return "myNewEvent";
}
}
若返回值不为空则会被作为新的事件再次发布。
- 实现ApplicationListener接口监听事件
@Component
public class MyEventListener2 implements ApplicationListener<MyEvent> {
@Override
public void onApplicationEvent(MyEvent applicationEvent) {
System.out.println("实现ApplicationListener方法监听事件:"+applicationEvent.data);
}
}
public class MyEvent extends ApplicationEvent {
Object data;
public MyEvent(Object source) {
super(source);
this.data = source;
}
}