在一个完整的事件系统中,有以下几种角色事件:描述发生了什么,比如请求处理完成,Spring容器的刷新等。事件源:事件的产生者,任何事件都必须有一个事件源。比如请求处理完成的事件源是DispatcherServlet,Spring容器刷新的事件源是ApplicationContext事件广播器:事件和事件监听器之间的桥梁,负责将事件通知给事件监听器。在监听器中对Spring事件做一些处理。我们常见的事件可能是ApplicationContextEvent,它的子类ContextRefreshedEvent就是我们常见的事件类型。它在Spring实例化所有非延迟加载的bean后释放。让我们看一下Spring事件的架构。Spring监听器事件广播器ApplicationContext支持事件。ApplicationEventPublisher这是Spring为用户提供的事件发布者。实际的发布功能委托给上面的ApplicationEventMulticaster来实现。Spring提供了ApplicationEventPublisherAware,用户可以获取这个发布者进行事件发布。如何使用Spring提供了两种使用注解@EventListener注解实现ApplicationListener接口的方法我们直接看到EventListenerMethodProcessor类实现了接口SmartInitializingSingleton接口,在Spring初始化所有非懒加载的bean后会调用该接口。publicinterfaceSmartInitializingSingleton{/***在单例预实例化阶段结束时调用,*保证所有常规单例bean都已经创建*了。{@linkListableBeanFactory#getBeansOfType}调用*此方法不会在引导过程中触发意外副作用。*
注意:这个回调不会被单例bean触发*在{@linkBeanFactory}引导程序后按需延迟初始化,*也不会被任何其他bean作用域触发。小心地将它用于beans*仅具有预期的引导语义。*/voidafterSingletonsInstantiated();}其实现非常简单for(Methodmethod:annotatedMethods.keySet()){for(EventListenerFactoryfactory:factories){if(factory.supportsMethod(method)){MethodmethodToUse=AopUtils.selectInvocableMethod(方法,context.getType(beanName));ApplicationListener>应用程序icationListener=factory.createApplicationListener(beanName,targetType,methodToUse);if(applicationListenerinstanceofApplicationListenerMethodAdapter){((ApplicationListenerMethodAdapter)applicationListener).init(context,this.evaluator);}context.addApplicationListener(applicationre}akener;find};显示所有被注解修改的方法,然后分别创建对应的ApplicationListener,接收到事件后反射调用该方法publicvoidprocessEvent(ApplicationEventevent){Object[]args=resolveArguments(event);if(shouldHandle(event,args)){对象结果=doInvoke(args);如果(结果!=null){handleResult(结果);}else{logger.trace("没有给出结果对象-没有要处理的结果");我们可以在AbstractApplicationEventMulticaster#retrieveApplicationListeners中看到的监听器调用顺序支持我们指定监听器的顺序。Spring涉及到很多订单,可以通过实现Ordered接口来实现。实现PriorityOrdered接口。使用@Ordered接口异步调用监听器。默认情况下,Spring创建的事件广播器会同步调用通知监听器。我们可以通过设置或者替换Spring的默认监听器来达到异步调用的目的,当然也可以进行扩展,根据不同的事件采用同步或者异步的方式,而不是单个或者全部同步或者全部异步的@OverridepublicvoidmulticastEvent(finalApplicationEventevent,@NullableResolvableTypeeventType){ResolvableTypetype=(eventType!=null?eventType:resolveDefaultEventType(event));执行器executor=getTaskExecutor();for(ApplicationListener>listener:getApplicationListeners(event,type)){if(executor!=null){executor.execute(()->invokeListener(listener,event));}else{invokeListener(监听器,事件);}}}Springrefresh之前回初化事件传播器protectedvoidinitApplicationEventMulticaster(){ConfigurableListableBeanFactorybeanFactory=getBeanFactory();如果(beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)){this.applicationEventMulticaster=beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME,ApplicationEventMulticaster.class);if(logger.isTraceEnabled()){logger.trace("使用ApplicationEventMulticaster["+this.applicationEventMulticaster+"]");}}else{this.applicationEventMulticaster=newSimpleApplicationEventMulticaster(beanFactory);beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME,this.applicationEventMulticaster);if(logger.isTraceEnabled()){logger.trace("No'"+APPLICATION_EVENT_MULTICASTER_BEAN_NAME+"'bean,使用"+"["+this.applicationEventMulticaster.getClass().getSimpleName()+"]");}}}替换原来的事件传播器@Component("applicationEventMulticaster")publicclassTestEventMulticasterextendsSimpleApplicationEventMulticaster{}