事件监听器初体验
1.事件应该继承与ApplicationEvent
public class HelloEvent extends ApplicationEvent {
private String message;
/**
* Create a new ApplicationEvent.
*
* @param source the object on which the event initially occurred (never {@code null})
*/
public HelloEvent(Object source, String message) {
super(source);
this.message = message;
}
public String getName() {
return message;
}
public void setName(String name) {
this.message = message;
}
}
2.发布者应该注入ApplicationEventPublisher或者实现ApplicationEventPublisherAware接口,容器在启动时将自动注入
- 第一种方式
@Component
public class HelloEventPublish {
@Autowired
private ApplicationEventPublisher applicationEventPublisher;
public void publishEvent(final String message) {
//创建自定义事件
HelloEvent helloEvent = new HelloEvent(this, message);
applicationEventPublisher.publishEvent(helloEvent);
}
}
- 第二种方式
@Component
public class HelloEventPublisher2 implements ApplicationEventPublisherAware {
private ApplicationEventPublisher applicationEventPublisher;
@Override
public void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher) {
this.applicationEventPublisher = applicationEventPublisher;
}
public void publishEvent(final String message) {
//创建自定义事件
HelloEvent helloEvent = new HelloEvent(this, message);
applicationEventPublisher.publishEvent(helloEvent);
}
}
3.事件监听器
定义事件监听器有两种方式。第一种方式可以实现ApplicationListener
@Component
public class HelloEventListener implements ApplicationListener<HelloEvent> {
@Override
public void onApplicationEvent(HelloEvent event) {
System.out.println("收到消息:" + event.getName());
}
}
spring4.2版本之后,提供@EventListener注解用于public方式,自定义事件作为形参可以直接注册为监听器
@Component
public class AnnotationDrivenContextStartedListener {
@EventListener
public void messageListener(HelloEvent helloEvent){
System.out.println("AnnotationDrivenContextStartedListener:"+helloEvent.message);
}
}
spring允许创建和发布自定义事件,这些事件默认情况下同步。如果需要将监听器设置为异步处理则只需要添加@Async注解
注意:如果被@EventListener标注的方法返回一个Event,那么spring将继续发布此event
4.测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class EventListenerTest {
@Autowired
private HelloEventPublisher2 helloEventPublisher2;
@Test
public void testPublishEvent(){
helloEventPublisher2.publishEvent("i am a message!");
}
}
泛型支持
spring的事件机制支持泛型。在定义事件时,只需要声明泛型即可,此时事件不需要继承ApplicationEvent 。
public class GenericTypeEvent<T> extends ApplicationEvent {
private T t;
public boolean isDeal = true;
/**
* Create a new ApplicationEvent.
*
* @param source the object on which the event initially occurred (never {@code null})
*/
public GenericTypeEvent(Object source, T t) {
super(source);
this.t = t;
}
getter settter...
}
使用SPEL表达式动态决定事件监听器是否要处理事件
@EventListener(condition = "#genericTypeEvent.isDeal")
public void genericTypeListener(GenericTypeEvent<String> genericTypeEvent){
System.out.println("AnnotationDrivenContextStartedListener:"+genericTypeEvent.getT());
}
支持监听事务
spring4.2版本之后,提供了@EventListener的扩展:@TransactionalEventListener。可以将监听器与事务的下述阶段进行绑定。
AFTER_COMMIT(默认):当事务被成功提交后执行
AFTER_ROLLBACK:当事务回滚时执行
AFTER_COMPLETION:当事务完成时执行,一个事务提交或者回滚都算是完成
BEFORE_COMMIT:在事务被提交之前执行
源码分析
监听器模式
如何初始化
第一步,初始化事件广播器
初始化applicationEventMulticaster,applicationEventMulticaster是真正发布事件的执行者,当发布一个事件时实则调用的是getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
AbstractApplicationContext.java
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
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 {
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
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() + "]");
}
}
}
假如用户注册了beanName为applicationEventMulticaster的广播器,则使用用户自定义广播器,否则默认创建SimpleApplicationEventMulticaster
第二步 注册监听器
AbstractApplicationContext.java
protected void registerListeners() {
// Register statically specified listeners first.
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let post-processors apply to them!
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
}
// Publish early application events now that we finally have a multicaster...
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
注册监听器,说白了就是将复合条件的bean放到一个set集合中。首先注册静态指定的监听器,所谓静态指定的监听器,就是容器在初始化时已经指定的一些监听器,相当于默认的一些监听器。之后从BeanFactory中获取实现了ApplicationListener接口的bean,添加至监听器集合中
如何运行
当调用ApplicationEventPublisher的publishEvent方法,调用事件广播器的multicastEvent
@Override
public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
Executor executor = getTaskExecutor();
for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {
if (executor != null) {
executor.execute(() -> invokeListener(listener, event));
}
else {
invokeListener(listener, event);
}
}
}
根据事件类型获取对应的监听器并且执行。从这里也可以直观看到,如何异步触发
private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
try {
listener.onApplicationEvent(event);
}
catch (ClassCastException ex) {
String msg = ex.getMessage();
if (msg == null || matchesClassCastMessage(msg, event.getClass())) {
// Possibly a lambda-defined listener which we could not resolve the generic event type for
// -> let's suppress the exception and just log a debug message.
Log logger = LogFactory.getLog(getClass());
if (logger.isTraceEnabled()) {
logger.trace("Non-matching event type for listener: " + listener, ex);
}
}
else {
throw ex;
}
}
}
从这部分代码可以看出,开始执行监听器的onApplicationEvent方法中的逻辑。如果是通过@EventListener注解实现的监听器,其对应的监听器类为ApplicationListenerMethodAdapter,查看其onApplicationEvent方法,实际调用processEvent方法
public void processEvent(ApplicationEvent event) {
Object[] args = resolveArguments(event);
if (shouldHandle(event, args)) {
Object result = doInvoke(args);
if (result != null) {
handleResult(result);
}
else {
logger.trace("No result object given - no result to handle");
}
}
}
可以看到首先判断条件是否决定执行,即@EventListner注解中的condition的SPEL表达式,然后在doInvoke中利用反射调用相应的方法执行。执行完之后如果返回值不为null,紧接着对result进行处理。查看handlerResult实现
protected void handleResult(Object result) {
if (result.getClass().isArray()) {
Object[] events = ObjectUtils.toObjectArray(result);
for (Object event : events) {
publishEvent(event);
}
}
else if (result instanceof Collection<?>) {
Collection<?> events = (Collection<?>) result;
for (Object event : events) {
publishEvent(event);
}
}
else {
publishEvent(result);
}
}
从上述代码中也可以看出针对返回的结果,继续发布。如果是一个事件集合,则遍历发布。支持返回数组、集合类型。
到这里你们有木有疑问?ApplicationListenerMethodAdapter是啥时候被放到广播器的监听器集合中的?其实在对bean实例化的过程中,经过EventListenerMethodProcessor处理时,将其封装为ApplicationListenerMethodAdapter放到监听器集合中去的。