一.背景

  事件机制作为一种编程机制,在很多开发语言中都提供了支持,同时许多开源框架的设计中都使用了事件机制,比如SpringFramework。

  在 Java 语言中,Java 的事件机制参与者有3种角色:

    1.Event Source:具体的事件源,比如说,你在界面点击一个 button 按钮,那么这个按钮就是事件源,要想使按钮对某些事件进行响应,你就需要注册特定的监听器 listener,事件源将事件对象传递给所有注册的监听器;

    2.Event Object:事件状态对象,用于监听器的相应的方法之中,作为参数;

    3.Event Listener:事件监听器,当它监听到 event object 产生的时候,它就调用相应的方法进行处理;

    上面3个角色就定义了事件机制的基本模型。

    流程是:

      1)首先我们将监听器对象注册给事件源对象,这样当事件触发时系统便可以通过事件源访问相应的监听器;

      2)当事件源触发事件后,系统将事件的相关信息封装成相应类型的事件对象,并将其发送给注册到事件源的相应监听器;

      3)当事件对象发送给监听器后,系统调用监听器相应的事件处理方法对事件进行处理,也就是做出响应;

  PS:监听器与事件源之间是“多对多”的关系。

  下面对几个概念进行详细介绍:

   1)事件源:事件最初由事件源产生,事件源可以是 Java Bean 或由生成事件能力的对象。在 Java 中,每一个组件会产生什么样的事件,已经被定义好了。或者说,对于任何一个事件来说,哪些组件可以产生它,已经是确定的了。

   2)事件对象:在事件对象中最高层是 java.util.EventObject,所有事件状态对象都是继承该类的派生类,比如 Spring-context 的事件机制的根类为 ApplicationEvent,而 Apollo 配置中心的事件处理类 AppCreationEvent 是继承自 Spring 的;

    除了 EventObject是在 util 包中,其它都在 java.awt、java.awt.event 包或 java.swing、java.swing.event 包中,比如有 AWTEvent、ActionEvent、AdjustmentEvent等等;

    • EventObject:该类除了从 Object 类中继承下来的方法外还有一个 getSource 方法,其功能就是返回最初发生 Event 的对象;

      1. public class EventObject implements java.io.Serializable {
      2.  
      3. protected transient Object source;
      4.  
      5. public EventObject(Object source) {
      6. if (source == null)
      7. throw new IllegalArgumentException("null source");
      8.  
      9. this.source = source;
      10. }
      11.  
      12. public Object getSource() {
      13. return source;
      14. }
      15.  
      16. public String toString() {
      17. return getClass().getName() + "[source=" + source + "]";
      18. }
      19. }
    • ApplicationEvent:
      1. public abstract class ApplicationEvent extends EventObject {
      2. private static final long serialVersionUID = 7099057708183571937L;
      3. private final long timestamp = System.currentTimeMillis();
      4.  
      5. public ApplicationEvent(Object source) {
      6. super(source);
      7. }
      8.  
      9. public final long getTimestamp() {
      10. return this.timestamp;
      11. }
      12. }
    • AppCreationEvent:
      1. public class AppCreationEvent extends ApplicationEvent {
      2.  
      3. public AppCreationEvent(Object source) {
      4. super(source);
      5. }
      6.  
      7. public App getApp() {
      8. Preconditions.checkState(source != null);
      9. return (App) this.source;
      10. }
      11. }

   3) 监听器对象:监听器对象就是一个实现了特定监听器接口的类的实例,在监听器接口的最顶层接口是 java.util.EventListener,这个接口是所有事件侦听器接口必须扩展的标记接口。感到诧异的是这个接口完全是空的,里面没有任何的抽象方法的定义;

  1. public interface EventListener {
  2. }

  事件监听器的接口命名方式为:XXListener,而且,在java中,这些接口已经被定义好了。用来被实现,它定义了事件处理器(即事件处理的方法原型,这个方法需要被重新实现)。例如:ActionListener接口、MouseListener接口、WindowListener接口等;

  说了这么多,现在要回到正题来,说到 Spring 的事件机制,就得从 Spring 的容器开始说起,在 IOC 容器的启动过程,当所有的 bean 都已经初始化处理完成之后,Spring IOC 容器会有一个发布事件的动作。

  1. public void refresh() throws BeansException, IllegalStateException {
  2. //来个锁,不然 refresh() 还没结束,你又来个启动或销毁容器的操作,那不就乱套了嘛
  3. synchronized (this.startupShutdownMonitor) {
  4.  
  5. ..............
  6. //初始化容器的信息源
  7. initMessageSource();
  8.  
  9. //初始化事件监听多路广播器
  10. initApplicationEventMulticaster();
  11.  
  12. //是个空壳方法,在AnnotationApplicationContex上下文中没有实现,可能在spring后面的版本会去扩展。
  13. onRefresh();
  14.  
  15. //注册监听器
  16. registerListeners();
  17.  
  18. //对象的创建:初始化剩下所有的(非懒加载的)单实例对象
  19. finishBeanFactoryInitialization(beanFactory);
  20.  
  21. //刷新完成工作,包括初始化LifecycleProcessor,发布刷新完成事件等
  22. finishRefresh();
  23. }
  24. .................
  25. }

  在 AbstractApplicationContext 类的 finishRefresh 方法,里面就会发布(广播)一条代表初始化结束的消息:

  1. protected void finishRefresh() {
  2. // Clear context-level resource caches (such as ASM metadata from scanning).
  3. clearResourceCaches();
  4.  
  5. // Initialize lifecycle processor for this context.
  6. initLifecycleProcessor();
  7.  
  8. // Propagate refresh to lifecycle processor first.
  9. getLifecycleProcessor().onRefresh();
  10.  
  11. //发布(广播)一条消息,类型ContextRefreshedEvent代表Spring容器初始化结束
  12. publishEvent(new ContextRefreshedEvent(this));
  13.  
  14. // Participate in LiveBeansView MBean, if active.
  15. LiveBeansView.registerApplicationContext(this);
  16. }

  这样,当 Spring IOC 容器加载处理完相应的 bean 之后,也给我们提供了一个机会,可以去做一些自己想做的事情。这也是 Spring IOC 容器提供给外部扩展的地方,我们可以使用这个扩展机制,来实现一些特殊的业务需求。

  比如让我们的 bean 实现  ApplicationListener 接口,这样当发布事件时, Spring 的 IOC 容器就会以容器中的实例对象作为事件源类,并从中找到事件的监听者,此时会执行相应的方法比如 onApplicationEvent(E event),我们的业务逻辑代码就会写在这个方法里面。这样我们的目的就可以达到了,但你这是可能会有一个疑问,这样的代码我们可以通过实现 InitializingBean 接口来实现啊,也会被 Spring 容器自动调用。但如果我们这时的需求是我们要做的事情,是必要要等到所有的 bean 都被处理完成之后再进行,此时 InitializingBean 接口就步合适了。(可查看下文案例3)

  Spring 的事件机制是观察者设计模式的实现,通过 ApplicationEvent 和 ApplicationListener 接口,可以实现容器事件处理。

  ApplicationListener 监听 ApplicationEvent 及其子类的事件:

  1. public interface ApplicationListener<E extends ApplicationEvent> extends EventListener {
  2.  
  3. void onApplicationEvent(E event);
  4.  
  5. }

  如果容器中有一个监听器,每当容器发布事件时,监听器将自动被触发,当然这种事件机制必须需要程序显示的触发。

  其中 Spring 有一些内置的事件,当完成某种操作时会发出某些事件动作。比如上文中的监听 ContextRefreshedEvent 事件,当所有的bean都初始化完成并成功装载后会触发该事件,实现 ApplicationListener<ContextRefreshedEvent> 接口可以收到监听动作,如何实现自己的业务逻辑。

  下面是一些 Spring 的内置事件:

    • ContextRefreshedEvent:ApplicationContext 被初始化或刷新时,该事件被发布。这也可以在 ConfigurableApplicationContext 接口中使用 refresh() 方法来发生。此处的初始化是指:所有的Bean 被成功装载,后置处理器 Bean 被检测并激活,所有 Singleton Bean 被预实例化,ApplicationContext 容器已就绪可用;【容器刷新完成所有 bean 都完全创建会发布这个事件】
    • ContextStartedEvent:当使用 ConfigurableApplicationContext (ApplicationContext子接口)接口中的 start() 方法启动 ApplicationContext 时,该事件被发布。你可以调查你的数据库,或者你可以在接受到这个事件后重启任何停止的应用程序;
    • ContextStoppedEvent:当使用 ConfigurableApplicationContext 接口中的 stop() 停止 ApplicationContext 时,发布这个事件。你可以在接受到这个事件后做必要的清理的工作;
    • ContextClosedEvent:当使用 ConfigurableApplicationContext 接口中的 close() 方法关闭 ApplicationContext 时,该事件被发布。一个已关闭的上下文到达生命周期末端,它不能被刷新或重启;【关闭容器会发布这个事件】

    • RequestHandledEvent:这是一个 web-specific 事件,告诉所有 bean HTTP 请求已经被服务。只能应用于使用 DispatcherServlet 的 Web 应用。在使用 Spring 作为前端的MVC控制器时,当Spring处理用户请求结束后,系统会自动触发该事件;

二.案例

  1.简单实现自定义监听器,初步认识监听器:结合上篇文章案例,实现监听器监听 Spring 容器变化

  1. @Configuration
  2. public class MyApplicationListener implements ApplicationListener<ApplicationEvent> {
  3. //当容器发布此事件之后,方法触发
  4. @Override
  5. public void onApplicationEvent(ApplicationEvent event) {
  6. System.out.println("当前收到的事件:"+event);
  7. }
  8. }
  9. =========测试运行结果=========
  10. [MyBeanDefinitionRegistryPostProcessor]postProcessBeanDefinitionRegistry--->bean的数量:11
  11. 十一月 03, 2020 10:17:59 下午 org.springframework.context.annotation.ConfigurationClassPostProcessor enhanceConfigurationClasses
  12. 信息: Cannot enhance @Configuration bean definition 'myBeanDefinitionRegistryPostProcessor' since its singleton instance has been created too early. The typical cause is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'.
  13. [MyBeanDefinitionRegistryPostProcessor]postProcessBeanFactory--->bean的数量:12
  14. [MyBeanFactoryPostProcessor]调用了postProcessBeanFactory
  15. [MyBeanFactoryPostProcessor]当前beanFactory共有12bean
  16. [MyBeanFactoryPostProcessor]当前beanFactory有下面组件[org.springframework.context.annotation.internalConfigurationAnnotationProcessor, org.springframework.context.annotation.internalAutowiredAnnotationProcessor, org.springframework.context.annotation.internalCommonAnnotationProcessor, org.springframework.context.event.internalEventListenerProcessor, org.springframework.context.event.internalEventListenerFactory, extConfig, myApplicationListener, myBeanDefinitionRegistryPostProcessor, myBeanFactoryPostProcessor, myBeanPostProcessor, person, color]
  17. PropertyValues: length=0
  18. [MyBeanFactoryPostProcessor]postProcessBeanFactory方法中修改了name属性初始值了
  19. PropertyValues: length=1; bean property 'name'
  20. [MyBeanPostProcessor]后置处理器处理bean=【extConfig】开始
  21. [MyBeanPostProcessor]后置处理器处理bean=【extConfig】完毕!
  22. [MyBeanPostProcessor]后置处理器处理bean=【myApplicationListener】开始
  23. [MyBeanPostProcessor]后置处理器处理bean=【myApplicationListener】完毕!
  24. Person有参构造器:[name=张三,sex=男]
  25. [Person]调用了BeanNameAwaresetBeanName方法了:person
  26. [Person]调用了BeanFactoryAwaresetBeanFactory方法了:org.springframework.beans.factory.support.DefaultListableBeanFactory@e45f292: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,extConfig,myApplicationListener,myBeanDefinitionRegistryPostProcessor,myBeanFactoryPostProcessor,myBeanPostProcessor,person,color]; root of factory hierarchy
  27. [MyBeanPostProcessor]后置处理器处理bean=【person】开始
  28. [Person]调用了InitailizationafterPropertiesSet方法了
  29. [MyBeanPostProcessor]后置处理器处理bean=【person】完毕!
  30. [MyBeanPostProcessor]后置处理器处理bean=【color】开始
  31. [MyBeanPostProcessor]后置处理器处理bean=【color】完毕!
  32. 当前收到的事件:org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@2e817b38, started on Tue Nov 03 22:17:59 CST 2020]
  33. Person [name=赵四, sex=null]
  34. 当前收到的事件:org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@2e817b38, started on Tue Nov 03 22:17:59 CST 2020]
  35. [Person]调用了DisposableBeandestroy方法了

  2.自定义发布一个事件,步骤如下:

    1)实现一个监听器来监听某个事件(事件是实现了ApplicationEvent 及其子类的事件);

    2)把监听器加入到容器中;

    2)发布事件,只要容器有相关事件的发布,我们就能监听到这个事件;

  1. public static void main(String[] args) {
  2. AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ExtConfig.class);
  3. Person bean = context.getBean(Person.class);
  4. System.out.println(bean.toString());
  5. //发布事件
  6. context.publishEvent(new ApplicationEvent(new String("自定义事件")) {
  7. });
  8. context.close();
  9. }
  10. =========测试运行结果=========
  11. [MyBeanDefinitionRegistryPostProcessor]postProcessBeanDefinitionRegistry--->bean的数量:11
  12. ...............
  13. [MyBeanPostProcessor]后置处理器处理bean=【color】完毕!
  14. 当前收到的事件:org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@2e817b38, started on Tue Nov 03 22:40:39 CST 2020]
  15. Person [name=赵四, sex=null]
  16. 当前收到的事件:com.hrh.ext.ExtTest$1[source=自定义事件]
  17. 当前收到的事件:org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@2e817b38, started on Tue Nov 03 22:40:39 CST 2020]
  18. [Person]调用了DisposableBeandestroy方法了

   从上面的运行结果可以看出,我们在容器中添加了一个事件,当我们发布事件时,监听器会监听到事件并把事件的内容发布出来。

  3.自定义监听器,实现容器的 bean都初始化后执行相应的操作,比如执行特定的方法:

    1)自定义注解:

  1. //该注解作用在类上
  2. @Target(ElementType.TYPE)
  3. @Retention(RetentionPolicy.RUNTIME)
  4. public @interface BaseService {
  5. }

    2)两个测试 Mapper:

  1. @Configuration
  2. @BaseService
  3. public class TaskScheduleJobMapper {
  4. public void initMapper() {
  5. System.out.println(">>>>> 【initMapper】Start job <<<<<");
  6. }
  7. }
  8.  
  9. @Configuration
  10. @BaseService
  11. public class TaskScheduleJobTxlogMapper {
  12. public void initMapper() {
  13. System.out.println(">>>>> 【initMapper】Recording log <<<<<");
  14. }
  15. }

    3)测试系统入口:

  1. public interface BaseInterface {
  2. public void init();
  3. }
  4.  
  5. @Configuration
  6. public class BaseInterfaceImpl implements BaseInterface {
  7. @Override
  8. public void init() {
  9. System.out.println("System start........");
  10. }
  11. }    

    4)自定义监听器:

  1. @Configuration
  2. public class ApplicationContextListener implements ApplicationListener<ContextRefreshedEvent> {
  3.  
  4. @Override
  5. public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
  6. // root application context
  7. if (null == contextRefreshedEvent.getApplicationContext().getParent()) {
  8. System.out.println(">>>>> Spring初始化完毕 <<<<<");
  9. // spring初始化完毕后,通过反射调用所有使用BaseService注解的initMapper方法
  10. Map<String, Object> baseServices =
  11. contextRefreshedEvent.getApplicationContext().getBeansWithAnnotation(BaseService.class);
  12. for (Object service : baseServices.values()) {
  13. System.out.println(">>>>> {" + service.getClass().getName() + "}.initMapper():");
  14. try {
  15. Method initMapper = service.getClass().getMethod("initMapper");
  16. initMapper.invoke(service);
  17. } catch (Exception e) {
  18. System.out.println("初始化BaseService的initMapper方法异常:" + e);
  19. e.printStackTrace();
  20. }
  21. }
  22. // 系统入口初始化
  23. Map<String, BaseInterface> baseInterfaceBeans =
  24. contextRefreshedEvent.getApplicationContext().getBeansOfType(BaseInterface.class);
  25. for (Object service : baseInterfaceBeans.values()) {
  26. System.out.println(">>>>> {" + service.getClass().getName() + "}.init()");
  27. try {
  28. Method init = service.getClass().getMethod("init");
  29. init.invoke(service);
  30. } catch (Exception e) {
  31. System.out.println("初始化BaseInterface的init方法异常:" + e);
  32. e.printStackTrace();
  33. }
  34. }
  35. }
  36. }
  37. }
  38.  
  39. =======测试运行结果=======
  40. [MyBeanDefinitionRegistryPostProcessor]postProcessBeanDefinitionRegistry--->bean的数量:14
  41. ................
  42. [MyBeanPostProcessor]后置处理器处理bean=【color】开始
  43. [MyBeanPostProcessor]后置处理器处理bean=【color】完毕!
  44. >>>>> Spring初始化完毕 <<<<<
  45. >>>>> {com.hrh.ext.TaskScheduleJobMapper$$EnhancerBySpringCGLIB$$6bfe7114}.initMapper():
  46. >>>>> initMapperStart job <<<<<
  47. >>>>> {com.hrh.ext.TaskScheduleJobTxlogMapper$$EnhancerBySpringCGLIB$$7132ffe6}.initMapper():
  48. >>>>> initMapperRecording log <<<<<
  49. >>>>> {com.hrh.ext.BaseInterfaceImpl$$EnhancerBySpringCGLIB$$f49a26ba}.init()
  50. System start........
  51. Person [name=赵四, sex=null]
  52. [Person]调用了DisposableBeandestroy方法了

  4.自定义事件及监听并进行发布

    1)自定义事件:

  1. public class EmailEvent extends ApplicationEvent {
  2. private String address;
  3. private String text;
  4.  
  5. /**
  6. * Create a new {@code ApplicationEvent}.
  7. *
  8. * @param source the object on which the event initially occurred or with
  9. * which the event is associated (never {@code null})
  10. */
  11. public EmailEvent(Object source) {
  12. super(source);
  13. }
  14.  
  15. public EmailEvent(Object source, String address, String text) {
  16. super(source);
  17. this.address = address;
  18. this.text = text;
  19. }
  20.  
  21. public String getAddress() {
  22. return address;
  23. }
  24.  
  25. public void setAddress(String address) {
  26. this.address = address;
  27. }
  28.  
  29. public String getText() {
  30. return text;
  31. }
  32.  
  33. public void setText(String text) {
  34. this.text = text;
  35. }
  36. }

    2)自定义监听器监听自定义事件:

  1. @Component
  2. public class EmailListener implements ApplicationListener {
  3. @Override
  4. public void onApplicationEvent(ApplicationEvent event) {
  5. if (event instanceof EmailEvent) {
  6.  
  7. EmailEvent emailEvent = (EmailEvent) event;
  8. System.out.println("邮件地址:" + emailEvent.getAddress());
  9. System.out.println("邮件内容:" + emailEvent.getText());
  10. } else {
  11. System.out.println("容器本身事件:" + event);
  12. }
  13.  
  14. }
  15. }

    3)测试发布事件:

  1. public static void main(String[] args) {
  2. AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ExtConfig.class);
  3.  
  4. Person bean = context.getBean(Person.class);
  5. System.out.println(bean.toString());
  6. //创建一个ApplicationEvent对象
  7. EmailEvent event = new EmailEvent("hello","249968839@qq.com","This is a event test");
  8. //主动触发该事件
  9. context.publishEvent(event);
  10. context.close();
  11. }
  12. =======测试运行结果=======
  13. [MyBeanDefinitionRegistryPostProcessor]postProcessBeanDefinitionRegistry--->bean的数量:15
  14. .............
  15. >>>>> Spring初始化完毕 <<<<<
  16. >>>>> {com.hrh.ext.TaskScheduleJobMapper$$EnhancerBySpringCGLIB$$45955a2d}.initMapper():
  17. >>>>> initMapperStart job <<<<<
  18. >>>>> {com.hrh.ext.TaskScheduleJobTxlogMapper$$EnhancerBySpringCGLIB$$4ac9e8ff}.initMapper():
  19. >>>>> initMapperRecording log <<<<<
  20. >>>>> {com.hrh.ext.BaseInterfaceImpl$$EnhancerBySpringCGLIB$$e5b13f13}.init()
  21. System start........
  22. 容器本身事件:org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@2e5d6d97, started on Fri Nov 06 22:55:23 CST 2020]
  23. Person [name=赵四, sex=null]
  24. 容器本身事件:com.hrh.ext.ExtTest$1[source=自定义事件]
  25. 邮件地址:249968839@qq.com
  26. 邮件内容:This is a event test
  27. 容器本身事件:org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@2e5d6d97, started on Fri Nov 06 22:55:23 CST 2020]
  28. [Person]调用了DisposableBeandestroy方法了

三.原理

  上面说了几个案例,现在你应该知道怎么使用了吧,接下来通过 debug 代码来分析它的执行流程。

  1.先来看看 ContextRefreshedEvent事件是怎么发布的,还是从熟悉的配方 refresh() 讲起,当容器刷新后,可以看到它调用了 finishRefresh() 来刷新执行事件:

  1. public void refresh() throws BeansException, IllegalStateException {
  2. //来个锁,不然 refresh() 还没结束,你又来个启动或销毁容器的操作,那不就乱套了嘛
  3. synchronized (this.startupShutdownMonitor) {
  4.  
  5. ..............
  6. //初始化容器的信息源
  7. initMessageSource();
  8.  
  9. //初始化事件监听多路广播器
  10. initApplicationEventMulticaster();
  11.  
  12. //是个空壳方法,在AnnotationApplicationContex上下文中没有实现,可能在spring后面的版本会去扩展。
  13. onRefresh();
  14.  
  15. //注册监听器
  16. registerListeners();
  17.  
  18. //对象的创建:初始化剩下所有的(非懒加载的)单实例对象
  19. finishBeanFactoryInitialization(beanFactory);
  20.  
  21. //刷新完成工作,包括初始化LifecycleProcessor,发布刷新完成事件等
  22. finishRefresh();
  23. }
  24. .................
  25. }

  2.在 AbstractApplicationContext.finishRefresh 方法中就会发布(广播)一条代表初始化结束的消息:publishEvent(new ContextRefreshedEvent(this))

  1. protected void finishRefresh() {
  2. // Clear context-level resource caches (such as ASM metadata from scanning).
  3. clearResourceCaches();
  4.  
  5. // Initialize lifecycle processor for this context.
  6. initLifecycleProcessor();
  7.  
  8. // Propagate refresh to lifecycle processor first.
  9. getLifecycleProcessor().onRefresh();
  10.  
  11. //发布(广播)一条消息,类型ContextRefreshedEvent代表Spring容器初始化结束
  12. publishEvent(new ContextRefreshedEvent(this));
  13.  
  14. // Participate in LiveBeansView MBean, if active.
  15. LiveBeansView.registerApplicationContext(this);
  16. }

  3.继续 publishEvent 方法会发现执行了getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType) 来广播消息:

  1. public void publishEvent(ApplicationEvent event) {
  2. publishEvent(event, null);
  3. }
  4.  
  5. protected void publishEvent(Object event, @Nullable ResolvableType eventType) {
  6. Assert.notNull(event, "Event must not be null");
  7.  
  8. // Decorate event as an ApplicationEvent if necessary
  9. ApplicationEvent applicationEvent;
  10. if (event instanceof ApplicationEvent) {
  11. applicationEvent = (ApplicationEvent) event;//类型转换
  12. }
  13. else {
  14. applicationEvent = new PayloadApplicationEvent<>(this, event);
  15. if (eventType == null) {
  16. eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType();
  17. }
  18. }
  19.  
  20. // Multicast right now if possible - or lazily once the multicaster is initialized
  21. //初始化过程中的registerListeners方法会把earlyApplicationEvents设置为空,(早期事件,容器初始化时使用,可以忽略)
  22. if (this.earlyApplicationEvents != null) {
  23. this.earlyApplicationEvents.add(applicationEvent);
  24. }
  25. else {
  26. //执行广播消息
  27. getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
  28. }
  29.  
  30. // Publish event via parent context as well... 方便使用父类进行发布事件
  31. if (this.parent != null) {
  32. if (this.parent instanceof AbstractApplicationContext) {
  33. ((AbstractApplicationContext) this.parent).publishEvent(event, eventType);
  34. }
  35. else {
  36. this.parent.publishEvent(event);
  37. }
  38. }
  39. }

    PS:publishEvent 方法是发布(广播)服务的核心能力,而它定义在 ApplicationEventPublisher 接口中,ApplicationContext接口继承了 ApplicationEventPublisher,所以 AbstractApplicationContext抽象类(ApplicationContext接口的实现类)就实现了该方法,也具有了发送广播的能力。

    上面的 getApplicationEventMulticaster() 是什么东西呢?需要深入了解下,它的作用是获取事件的多播器(派发器),即将事件发送给多个监听器,让监听器执行相应的逻辑。

  1. private ApplicationEventMulticaster applicationEventMulticaster;
  2. ApplicationEventMulticaster getApplicationEventMulticaster() throws IllegalStateException {
  3. if (this.applicationEventMulticaster == null) {
  4. throw new IllegalStateException("ApplicationEventMulticaster not initialized - " +
  5. "call 'refresh' before multicasting events via the context: " + this);
  6. }
  7. return this.applicationEventMulticaster;
  8. }

    从上面的代码可以看出,applicationEventMulticaster是 AbstractApplicationContext 的私有成员变量,那么这个多播器(派发器)是怎么获取到的呢?在前面的 refresh 方法中有一个initApplicationEventMulticaster()方法,就是调用 AbstractApplicationContext.initApplicationEventMulticaster() 来初始化这个多播器(派发器)的:

  1. protected void initApplicationEventMulticaster() {
  2. ConfigurableListableBeanFactory beanFactory = getBeanFactory();
  3. //从bean工厂查找有没有一个bean为applicationEventMulticaster,如果有,从容器中拿出来
  4. if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
  5. this.applicationEventMulticaster =
  6. beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
  7. if (logger.isTraceEnabled()) {
  8. logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
  9. }
  10. }
  11. else {
  12. //如果没有,则往容器中注册一个SimpleApplicationEventMulticaster,名字为applicationEventMulticaster,如果派发事件需要就可以使用了
  13. this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
  14. beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
  15. if (logger.isTraceEnabled()) {
  16. logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
  17. "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
  18. }
  19. }
  20. }   

  4.说完了  getApplicationEventMulticaster(),再来说说 multicastEvent(),它的作用是派发事件,它是 ApplicationEventMulticaster接口的一个方法,所以它会调用实现类 SimpleApplicationEventMul

ticaster(上面注册的多播器)的multicastEvent 方法:

  1. public interface ApplicationEventMulticaster {
  2.  
  3. void multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType);
  4.  
  5. }
  6. //public abstract class AbstractApplicationEventMulticaster implements ApplicationEventMulticaster
  7. public class SimpleApplicationEventMulticaster extends AbstractApplicationEventMulticaster {
  8. @Override
  9. public void multicastEvent(final ApplicationEvent event, @Nullable ResolvableType eventType) {
  10. ResolvableType type = (eventType != null ? eventType : resolveDefaultEventType(event));
  11. Executor executor = getTaskExecutor();
  12. //根据消息类型取出对应的所有监听器
  13. for (ApplicationListener<?> listener : getApplicationListeners(event, type)) {
  14. //如果可以使用多线程执行,就使用多线程来异步派发事件,执行监听器的方法
  15. if (executor != null) {
  16. executor.execute(() -> invokeListener(listener, event));
  17. }
  18. else {
  19. invokeListener(listener, event);
  20. }
  21. }
  22. }
  23. }

  5.最后来看看 invokeListener 方法,它会拿到监听器来回调 MyApplicationListener. onApplicationEvent方法,然后控制台就输出了信息 :

  1. protected void invokeListener(ApplicationListener<?> listener, ApplicationEvent event) {
  2. ErrorHandler errorHandler = getErrorHandler();
  3. if (errorHandler != null) {
  4. try {
  5. doInvokeListener(listener, event);
  6. }
  7. catch (Throwable err) {
  8. errorHandler.handleError(err);
  9. }
  10. }
  11. else {
  12. doInvokeListener(listener, event);//执行
  13. }
  14. }
  15. private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
  16. try {
  17. //回调onApplicationEvent
  18. listener.onApplicationEvent(event);
  19. }
  20. catch (ClassCastException ex) {
  21. String msg = ex.getMessage();
  22. if (msg == null || matchesClassCastMessage(msg, event.getClass())) {
  23. // Possibly a lambda-defined listener which we could not resolve the generic event type for
  24. // -> let's suppress the exception and just log a debug message.
  25. Log logger = LogFactory.getLog(getClass());
  26. if (logger.isTraceEnabled()) {
  27. logger.trace("Non-matching event type for listener: " + listener, ex);
  28. }
  29. }
  30. else {
  31. throw ex;
  32. }
  33. }
  34. }

  6.当再执行案例2的事件时,从AbstractApplicationContext. publishEvent()(上面第3步)开始执行,步骤还是multicastEvent派发事件 --> invokeListener回调执行 onApplicationEvent;

  7.当容器关闭时,会调用doClose(),里面有个ContextClosedEvent事件,监听器监听到事件控制台就输出了信息:

  1. context.close();
  2. @Override
  3. public void close() {
  4. synchronized (this.startupShutdownMonitor) {
  5. doClose();
  6. // If we registered a JVM shutdown hook, we don't need it anymore now:
  7. // We've already explicitly closed the context.
  8. if (this.shutdownHook != null) {
  9. try {
  10. Runtime.getRuntime().removeShutdownHook(this.shutdownHook);
  11. }
  12. catch (IllegalStateException ex) {
  13. // ignore - VM is already shutting down
  14. }
  15. }
  16. }
  17. }
  18. protected void doClose() {
  19. // Check whether an actual close attempt is necessary...
  20. if (this.active.get() && this.closed.compareAndSet(false, true)) {
  21. if (logger.isDebugEnabled()) {
  22. logger.debug("Closing " + this);
  23. }
  24.  
  25. LiveBeansView.unregisterApplicationContext(this);
  26.  
  27. try {
  28. // Publish shutdown event.
  29. publishEvent(new ContextClosedEvent(this));
  30. }
  31. catch (Throwable ex) {
  32. logger.warn("Exception thrown from ApplicationListener handling ContextClosedEvent", ex);
  33. }
  34.  
  35. // Stop all Lifecycle beans, to avoid delays during individual destruction.
  36. if (this.lifecycleProcessor != null) {
  37. try {
  38. this.lifecycleProcessor.onClose();
  39. }
  40. catch (Throwable ex) {
  41. logger.warn("Exception thrown from LifecycleProcessor on context close", ex);
  42. }
  43. }
  44.  
  45. // Destroy all cached singletons in the context's BeanFactory.
  46. destroyBeans();
  47.  
  48. // Close the state of this context itself.
  49. closeBeanFactory();
  50.  
  51. // Let subclasses do some final clean-up if they wish...
  52. onClose();
  53.  
  54. // Reset local application listeners to pre-refresh state.
  55. if (this.earlyApplicationListeners != null) {
  56. this.applicationListeners.clear();
  57. this.applicationListeners.addAll(this.earlyApplicationListeners);
  58. }
  59.  
  60. // Switch to inactive.
  61. this.active.set(false);
  62. }
  63. }

  8.上面在第4步中派发事件操作 getApplicationListeners 拿到了所有的监听器,那么容器中有哪些监听器呢?从第1步的 registerListeners() 可以看到,容器是先注册了多播器和监听器后才进行事件的发布,下面是监听器的注册:

  1. protected void registerListeners() {
  2. // Register statically specified listeners first.
  3. //从容器中拿到所有的监听器添加到多路派发器中,(最开始是没有的,跳过循环执行下面的步骤)
  4. for (ApplicationListener<?> listener : getApplicationListeners()) {
  5. getApplicationEventMulticaster().addApplicationListener(listener);
  6. }
  7.  
  8. // Do not initialize FactoryBeans here: We need to leave all regular beans
  9. // uninitialized to let post-processors apply to them!
  10. //若容器中没有,即上面的遍历没有执行,则根据类型获取组件名称,然后根据组件名称获取对应的组件加入到多路派发器中
  11. String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
  12. for (String listenerBeanName : listenerBeanNames) {
  13. getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
  14. }
  15.  
  16. // Publish early application events now that we finally have a multicaster...
  17. Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
  18. this.earlyApplicationEvents = null;
  19. if (earlyEventsToProcess != null) {
  20. for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
  21. getApplicationEventMulticaster().multicastEvent(earlyEvent);
  22. }
  23. }
  24. }

    下面再来看看 getApplicationListeners 方法,发现它是 AbstractApplicationEventMulticaster 类的一个方法,所以在开始详解 getApplicationListeners 方法前,先来看看 AbstractApplicationEventMulticaster 类是一个起什么作用的类。

    从上面类图可以看到 AbstractApplicationEventMulticaster 它实现了几个接口,它是一个事件派发器,上文第3点里面讲到的初始化派发器获取的 SimpleApplicationEventMulticaster 其实是继承自AbstractApplicationEventMulticaster 的。

    在看下面的获取监听器源码前,我们先思考一个问题:监听器如何做到只监听指定类型的消息?如何要实现,有什么方式?

    我们可以先猜测下:

      1) 注册监听器的时候,将监听器和消息类型绑定;(该论证可查看下文 addApplicationListener 实现方法的解析)

      2) 广播的时候,按照这条消息的类型去找指定了该类型的监听器,但不可能每条广播都去所有监听器里面找一遍,应该是说广播的时候会触发一次监听器和消息的类型绑定;

    好了,接下来我们带着这些问题和猜测详细看看 getApplicationListeners 的源码:

  1. public abstract class AbstractApplicationEventMulticaster
  2. implements ApplicationEventMulticaster, BeanClassLoaderAware, BeanFactoryAware {
  3. //创建监听器助手类,用于存放监听器集合,参数是否是预过滤监听器
  4. private final ListenerRetriever defaultRetriever = new ListenerRetriever(false);
  5. //ListenerCacheKey是基于事件类型和源类型的类作为key用来存储监听器助手
  6. final Map<ListenerCacheKey, ListenerRetriever> retrieverCache = new ConcurrentHashMap<>(64);
  7.  
  8. @Nullable
  9. private ClassLoader beanClassLoader;//类加载器
  10. //互斥的监听器助手类
  11. private Object retrievalMutex = this.defaultRetriever;
  12. //监听器助手类(封装一组特定目标监听器的帮助类,允许有效地检索预过滤的监听器,此助手的实例按照时间类型和源类型缓存)
  13. private class ListenerRetriever {
  14. //存放事件监听器,有序、不可重复
  15. public final Set<ApplicationListener<?>> applicationListeners = new LinkedHashSet<>();
  16. //存放事件监听器bean名称,有序,不可重复
  17. public final Set<String> applicationListenerBeans = new LinkedHashSet<>();
  18. //是否预过滤监听器
  19. private final boolean preFiltered;
  20.  
  21. public ListenerRetriever(boolean preFiltered) {
  22. this.preFiltered = preFiltered;
  23. }
  24. //获取事件监听器
  25. public Collection<ApplicationListener<?>> getApplicationListeners() {
  26. //创建一个指定大小的ApplicationListener监听器List集合
  27. List<ApplicationListener<?>> allListeners = new ArrayList<>(
  28. this.applicationListeners.size() + this.applicationListenerBeans.size());
  29. allListeners.addAll(this.applicationListeners);
  30. //如果存放监听器bean name的集合不为空
  31. if (!this.applicationListenerBeans.isEmpty()) {
  32. //获取IOC容器工厂类
  33. BeanFactory beanFactory = getBeanFactory();
  34. for (String listenerBeanName : this.applicationListenerBeans) {
  35. try {
  36. //获取指定bean name的监听器实例
  37. ApplicationListener<?> listener = beanFactory.getBean(listenerBeanName, ApplicationListener.class);
  38. //判定如果是预过滤的监听器或者集合中不包含监听器实例则添加到集合中
  39. if (this.preFiltered || !allListeners.contains(listener)) {
  40. allListeners.add(listener);
  41. }
  42. }
  43. catch (NoSuchBeanDefinitionException ex) {
  44. // Singleton listener instance (without backing bean definition) disappeared -
  45. // probably in the middle of the destruction phase
  46. }
  47. }
  48. }
  49. if (!this.preFiltered || !this.applicationListenerBeans.isEmpty()) {
  50. AnnotationAwareOrderComparator.sort(allListeners);
  51. }
  52. return allListeners;
  53. }
  54. }
  55. //流程1:当所发布的事件类型和事件源类型与Map(retrieverCache)中的key匹配时,
  56. //将直接返回value中的监听器列表作为匹配结果,通常这发生在事件不是第一次发布时,能避免遍历所有监听器并进行过滤,
  57. //如果事件时第一次发布,则会执行流程2。
  58. protected Collection<ApplicationListener<?>> getApplicationListeners(
  59. ApplicationEvent event, ResolvableType eventType) {
  60. //事件源,事件最初发生在其上的对象
  61. Object source = event.getSource();
  62. //事件源class对象
  63. Class<?> sourceType = (source != null ? source.getClass() : null);
  64. //缓存的key有两个维度:消息来源+消息类型(关于消息来源可见ApplicationEvent构造方法的入参)
  65. //创建基于事件源和源类型的监听器助手cacheKey
  66. ListenerCacheKey cacheKey = new ListenerCacheKey(eventType, sourceType);
  67.  
  68. // Quick check for existing entry on ConcurrentHashMap...
  69. // retrieverCache是ConcurrentHashMap对象(并发容器,使用锁分段来确保多线程下数据安全),所以是线程安全的,
  70. // ListenerRetriever中有个监听器的集合,并有些简单的逻辑封装,调用它的getApplicationListeners方法返回的监听类集合是排好序的(order注解排序)
  71. ListenerRetriever retriever = this.retrieverCache.get(cacheKey);
  72. //如果retrieverCache中找到对应的监听器集合,就立即返回了
  73. if (retriever != null) {
  74. return retriever.getApplicationListeners();
  75. }
  76. //如果类加载器为null,或者事件源在给定的类加载器上下文是安全的并且源类型为null或者源类型在指定上下文是安全的
  77. if (this.beanClassLoader == null ||
  78. (ClassUtils.isCacheSafe(event.getClass(), this.beanClassLoader) &&
  79. (sourceType == null || ClassUtils.isCacheSafe(sourceType, this.beanClassLoader)))) {
  80. // Fully synchronized building and caching of a ListenerRetriever
  81. //锁定监听器助手对象,同步从ListenerRetriever监听器助手中获取指定的监听器
  82. synchronized (this.retrievalMutex) {
  83. //抢到锁之后再做一次判断,因为有可能在前面BLOCK的时候,另一个抢到锁的线程已经设置好了缓存,
  84. //即避免自己在BLOCK的时候其他线程已经将数据放入缓存了
  85. retriever = this.retrieverCache.get(cacheKey);
  86. if (retriever != null) {
  87. //返回监听器助手中存储的监听器对象
  88. return retriever.getApplicationListeners();
  89. }
  90. retriever = new ListenerRetriever(true);
  91. //retrieveApplicationListeners方法实际检索给定事件和源类型的监听器
  92. Collection<ApplicationListener<?>> listeners =
  93. retrieveApplicationListeners(eventType, sourceType, retriever);//流程2
  94. //retriever放到缓存器中(更新缓存)
  95. this.retrieverCache.put(cacheKey, retriever);
  96. return listeners;
  97. }
  98. }
  99. else {
  100. // No ListenerRetriever caching -> no synchronization necessary
  101. // 无ListenerRetriever监听器助手 -> 无需同步缓存
  102. return retrieveApplicationListeners(eventType, sourceType, null);
  103. }
  104. }
  105. }

    从上面的源码可以看出:

      1)在获取 ApplicationListener 的时候用到了缓存,同时有缓存更新和用锁来确保线程同步(双重判断也做了),这样如果在自定义广播时,如果多线程同时发广播,就不会有线程同步的问题了。  

      2)发送消息的时候根据类型去找所有对应的监听器,这样就可以实现自定义监听器只接收指定类型的消息。

        3)在广播消息的时刻,如果某个类型的消息在缓存中找不到对应的监听器集合,就调用 retrieveApplicationListeners 方法去找出符合条件的所有监听器,然后放入这个集合中。

    下面再详细看看 retrieveApplicationListeners:

  1. private Collection<ApplicationListener<?>> retrieveApplicationListeners(
  2. ResolvableType eventType, @Nullable Class<?> sourceType, @Nullable ListenerRetriever retriever) {
  3. //存放匹配的监听器的列表
  4. List<ApplicationListener<?>> allListeners = new ArrayList<>();
  5. Set<ApplicationListener<?>> listeners;
  6. Set<String> listenerBeans;
  7. //锁定监听器助手对象
  8. synchronized (this.retrievalMutex) {
  9. //获取监听器助手中存储的监听器对象,去重
  10. listeners = new LinkedHashSet<>(this.defaultRetriever.applicationListeners);
  11. //获取监听器助手中存储的监听器bean名称集合,去重
  12. listenerBeans = new LinkedHashSet<>(this.defaultRetriever.applicationListenerBeans);
  13. }
  14.  
  15. // Add programmatically registered listeners, including ones coming
  16. // from ApplicationListenerDetector (singleton beans and inner beans).
  17. ////遍历所有的监听器
  18. for (ApplicationListener<?> listener : listeners) {
  19. //判断监听器是否匹配的逻辑在supportsEvent(listener, eventType, sourceType)中
  20. if (supportsEvent(listener, eventType, sourceType)) {
  21. //监听器助手类不为空,加入监听器助手类中的监听器集合中
  22. if (retriever != null) {
  23. retriever.applicationListeners.add(listener);
  24. }
  25. //放入匹配的监听器列表中
  26. allListeners.add(listener);
  27. }
  28. }
  29.  
  30. // Add listeners by bean name, potentially overlapping with programmatically
  31. // registered listeners above - but here potentially with additional metadata.
  32. //监听器助手中存储的监听器bean名称集合有值
  33. if (!listenerBeans.isEmpty()) {
  34. //获取IOC容器
  35. ConfigurableBeanFactory beanFactory = getBeanFactory();
  36. //遍历
  37. for (String listenerBeanName : listenerBeans) {
  38. try {
  39. //判断监听器是否匹配的逻辑在supportsEvent(listener, eventType, sourceType)中
  40. if (supportsEvent(beanFactory, listenerBeanName, eventType)) {
  41. //获取指定bean name的监听器实例
  42. ApplicationListener<?> listener =
  43. beanFactory.getBean(listenerBeanName, ApplicationListener.class);
  44. //如果匹配的监听器列表不包含上面获取的实例和符合supportsEvent的逻辑
  45. if (!allListeners.contains(listener) && supportsEvent(listener, eventType, sourceType)) {
  46. //监听器助手类不为空
  47. if (retriever != null) {
  48. //bean名称是单例,在容器中没有重复监听器
  49. if (beanFactory.isSingleton(listenerBeanName)) {
  50. //加入监听器助手类中的监听器集合中
  51. retriever.applicationListeners.add(listener);
  52. }
  53. else {
  54. //去重,applicationListenerBeans是LinkedHashSet
  55. retriever.applicationListenerBeans.add(listenerBeanName);
  56. }
  57. }
  58. //放入匹配的监听器列表中
  59. allListeners.add(listener);
  60. }
  61. }
  62. //监听器是否匹配的逻辑不在supportsEvent(listener, eventType, sourceType)中,从监听器助手类和匹配的监听器列表中移除
  63. else {
  64. // Remove non-matching listeners that originally came from
  65. // ApplicationListenerDetector, possibly ruled out by additional
  66. // BeanDefinition metadata (e.g. factory method generics) above.
  67. Object listener = beanFactory.getSingleton(listenerBeanName);
  68. if (retriever != null) {
  69. retriever.applicationListeners.remove(listener);
  70. }
  71. allListeners.remove(listener);
  72. }
  73. }
  74. catch (NoSuchBeanDefinitionException ex) {
  75. // Singleton listener instance (without backing bean definition) disappeared -
  76. // probably in the middle of the destruction phase
  77. }
  78. }
  79. }
  80. //监听器进行排序
  81. AnnotationAwareOrderComparator.sort(allListeners);
  82. if (retriever != null && retriever.applicationListenerBeans.isEmpty()) {
  83. retriever.applicationListeners.clear();
  84. retriever.applicationListeners.addAll(allListeners);
  85. }
  86. return allListeners;
  87. }

    下面是 supportsEvent 的源码探究:

  1. //首先对原始的ApplicationListener进行一层适配器包装成GenericApplicationListener,
  2. //便于后面使用该接口中定义的方法判断监听器是否支持传入的事件类型或事件源类型
  3. protected boolean supportsEvent(
  4. ApplicationListener<?> listener, ResolvableType eventType, @Nullable Class<?> sourceType) {
  5.  
  6. GenericApplicationListener smartListener = (listener instanceof GenericApplicationListener ?
  7. (GenericApplicationListener) listener : new GenericApplicationListenerAdapter(listener));
  8. return (smartListener.supportsEventType(eventType) && smartListener.supportsSourceType(sourceType));
  9. }
  10.  
  11. public interface GenericApplicationListener extends ApplicationListener<ApplicationEvent>, Ordered {
  12. //判断是否支持该事件类型
  13. boolean supportsEventType(ResolvableType eventType);
  14.  
  15. //判断是否支持该事件源类型,默认是true,也就是说事件源的类型通常对于判断匹配的监听器没有意义
  16. default boolean supportsSourceType(@Nullable Class<?> sourceType) {
  17. return true;
  18. }
  19. }
  20. public class GenericApplicationListenerAdapter implements GenericApplicationListener, SmartApplicationListener {
  21.  
  22. ......
  23. //监听器泛型的实际类型
  24. @Nullable
  25. private final ResolvableType declaredEventType;
  26.  
  27. //判断监听器是否支持该事件类型,因为我们的监听器实例通常都不是SmartApplicationListener类型
  28. //eventType是发布的事件的类型
  29. @Override
  30. @SuppressWarnings("unchecked")
  31. public boolean supportsEventType(ResolvableType eventType) {
  32. if (this.delegate instanceof SmartApplicationListener) {
  33. Class<? extends ApplicationEvent> eventClass = (Class<? extends ApplicationEvent>) eventType.resolve();
  34. return (eventClass != null && ((SmartApplicationListener) this.delegate).supportsEventType(eventClass));
  35. }
  36. else {
  37. //this.declaredEventType.isAssignableFrom(eventType)当以下两种情况返回true
  38. // 1.declaredEventType和eventType类型相同
  39. // 2.declaredEventType是eventType的父类型
  40. //只要监听器泛型的实际类型和发布的事件类型一样或是它的父类型,则该监听器将被成功匹配。
  41. return (this.declaredEventType == null || this.declaredEventType.isAssignableFrom(eventType));
  42. }
  43. }
  44. }

   9.下面是流程总结图:

四.扩展

  1.从上面的案例中可以看到,只要 bean 继承 ApplicationEvent,然后使用容器的 publishEvent 就可以发布事件了(类似上文案例4),那么还有其他的方式使 bean 具有跟容器一样具有发布事件的能力吗?

    答案当然是有的,比如 ApplicationEventPublisherAware 这个接口就可以使 bean 具有发布事件的能力。下面是该接口的源码:

  1. public interface ApplicationEventPublisherAware extends Aware {
  2.  
  3. void setApplicationEventPublisher(ApplicationEventPublisher applicationEventPublisher);
  4.  
  5. }

    我们可以创建一个bean,实现了 ApplicationEventPublisherAware 接口,那么该 bean 的 setApplicationEventPublisher 方法就会被调用,通过该方法可以接收到 ApplicationEventPublisher 类型的入参,借助这个 ApplicationEventPublisher 就可以发消息了;

    比如下面的案例:

    1)接口:

  1. public interface UserEventRegisterService {
  2. /**
  3. * 发布事件,注册用户
  4. */
  5. void register();
  6. }

    2)接口实现:

  1. @Service
  2. public class UserEventRegisterServiceImpl implements UserEventRegisterService {
  3. @Resource
  4. private ApplicationEventPublisher applicationEventPublisher;
  5.  
  6. @Override
  7. public void register() {
  8. User user = new User();
  9. user.setId(1);
  10. user.setName("张三");
  11. user.setSex("男");
  12. applicationEventPublisher.publishEvent(user);
  13. System.out.println("结束。");
  14. }
  15. }

    3)自定义监听器:可以使用 @EventListener 注解来实现自定义监听器(该注解下文详细介绍)

  1. @Component
  2. public class UserEventListener {
  3. @EventListener(condition = "#user.id != null")//监听当用户id不为空的事件
  4. public void handleEvent(User user){
  5. try {
  6. Thread.sleep(5000);
  7. } catch (InterruptedException e) {
  8. e.printStackTrace();
  9. }
  10. System.out.println("监听器监听到的信息:"+user);
  11. }
  12. }

    4)配置类:

  1. @ComponentScan("com.hrh.ext")
  2. @Configuration
  3. public class ExtConfig {
  4.  
  5. }

    5)测试:

  1. public static void main(String[] args) {
  2. AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ExtConfig.class);
  3. UserEventRegisterService service = context.getBean(UserEventRegisterService.class);
  4. service.register();
  5. context.close();
  6. }
  7. ======运行结果======
  8. 监听器监听到的信息:User [id=1, name=张三, sex=男]
  9. 结束。

  2.监听器是如何加入到容器中的呢?我们从容器 refresh 刷新开始看起,发现在 refresh 里面有 prepareBeanFactory(beanFactory) 方法,为所有bean准备了一个后置处理器 ApplicationListenerDetector:

  1. public void refresh() throws BeansException, IllegalStateException {
  2. synchronized (this.startupShutdownMonitor) {
  3. // Prepare this context for refreshing.
  4. prepareRefresh();
  5.  
  6. // Tell the subclass to refresh the internal bean factory.
  7. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
  8.  
  9. // Prepare the bean factory for use in this context.
  10. prepareBeanFactory(beanFactory);
  11.  
  12. .........
  13. }
  14. }
  15. protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
  16. ..........
  17.  
  18. // Register early post-processor for detecting inner beans as ApplicationListeners.
  19. beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
  20.  
  21. ..........
  22. }

    接下来再看看 ApplicationListenerDetector类的源码,由于它是一个后置处理器(不清楚后置处理器的可查看上篇文章,开头有简单介绍),所以它有 postProcessBeforeInitialization 和 postProcessAfterInitialization 两个方法,这两个方法在对所有的 bean 进行实例化后进行拦截操作:

  1. private final transient AbstractApplicationContext applicationContext;
  2.  
  3. private final transient Map<String, Boolean> singletonNames = new ConcurrentHashMap<>(256);
  4. @Override
  5. public Object postProcessBeforeInitialization(Object bean, String beanName) {
  6. return bean;
  7. }
  8.  
  9. @Override
  10. public Object postProcessAfterInitialization(Object bean, String beanName) {
  11. //如果bean是ApplicationListener类型
  12. if (bean instanceof ApplicationListener) {
  13. // potentially not detected as a listener by getBeanNamesForType retrieval
  14. //判断bean在不在并发容器中
  15. Boolean flag = this.singletonNames.get(beanName);
  16. if (Boolean.TRUE.equals(flag)) {
  17. // singleton bean (top-level or inner): register on the fly
  18. //注册监听器,其实就是保存在成员变量applicationEventMulticaster的成员变量defaultRetriever的集合applicationListeners中
  19. this.applicationContext.addApplicationListener((ApplicationListener<?>) bean);
  20. }
  21. else if (Boolean.FALSE.equals(flag)) {
  22. if (logger.isWarnEnabled() && !this.applicationContext.containsBean(beanName)) {
  23. // inner bean with other scope - can't reliably process events
  24. logger.warn("Inner bean '" + beanName + "' implements ApplicationListener interface " +
  25. "but is not reachable for event multicasting by its containing ApplicationContext " +
  26. "because it does not have singleton scope. Only top-level listener beans are allowed " +
  27. "to be of non-singleton scope.");
  28. }
  29. this.singletonNames.remove(beanName);
  30. }
  31. }
  32. return bean;
  33. }
  34. public void addApplicationListener(ApplicationListener<?> listener) {
  35. Assert.notNull(listener, "ApplicationListener must not be null");
  36. if (this.applicationEventMulticaster != null) {
  37. this.applicationEventMulticaster.addApplicationListener(listener);
  38. }
  39. this.applicationListeners.add(listener);
  40. }

    如上所示,如果当前 bean 实现了 ApplicationListener 接口,就会调用 this.applicationContext.addApplicationListener 方法将当前 bean 注册到 applicationContext 的监听器集合中,后面有广播就直接找到这些监听器,调用每个监听器的 onApplicationEvent 方法;  

    接下来详细看看 addApplicationListener 方法,它的实现方法在 AbstractApplicationEventMulticaster 类中:

  1. @Override
  2. public void addApplicationListener(ApplicationListener<?> listener) {
  3. //锁定监听器助手对象
  4. synchronized (this.retrievalMutex) {
  5. // Explicitly remove target for a proxy, if registered already,
  6. // in order to avoid double invocations of the same listener.
  7. // 如果已经注册,则显式删除已经注册的监听器对象
  8. // 为了避免调用重复的监听器对象
  9. Object singletonTarget = AopProxyUtils.getSingletonTarget(listener);
  10. if (singletonTarget instanceof ApplicationListener) {
  11. //如果因为AOP导致创建了监听类的代理,那么就要在注册列表中清除代理类
  12. this.defaultRetriever.applicationListeners.remove(singletonTarget);
  13. }
  14. //把监听器加入集合defaultRetriever.applicationListeners中,这是个LinkedHashSet实例
  15. this.defaultRetriever.applicationListeners.add(listener);
  16. //清空监听器助手缓存Map
  17. this.retrieverCache.clear();
  18. }
  19. }

    在上面可以看到,如果对象是由 AOP生成的代理类,需要清除,是因为 AOP 是通过代理技术实现的,此时可能通过 CGLIB 生成了监听类的代理类,此类的实例如果被注册到监听器集合中,那么广播时按照消息类型就会取出两个监听器实例来,到时就是一个消息被两个实例消费了,因此需要先清理掉代理类。

    同时也论证了一个观点:所谓的注册监听器,其实就是把 ApplicationListener 的实现类放入一个LinkedHashSet的集合,此处没有任何与消息类型相关的操作,因此,监听器注册的时候并没有将消息类型和监听器绑定;

  3.异步监听事件案例:正常的事件通知是 ContextRefreshedEvent --> EmailEvent --> ContextClosedEvent

  1. //开启异步支持
  2. @EnableAsync
  3. @Component
  4. public class EmailListener implements ApplicationListener {
  5. @Async//异步执行
  6. @Override
  7. public void onApplicationEvent(ApplicationEvent event) {
  8. if (event instanceof EmailEvent) {
  9.  
  10. EmailEvent emailEvent = (EmailEvent) event;
  11. System.out.println("邮件地址:" + emailEvent.getAddress());
  12. System.out.println("邮件内容:" + emailEvent.getText());
  13. } else {
  14. System.out.println("容器本身事件:" + event);
  15. }
  16. //通过线程名称区别
  17. System.out.println(event+ ":" + Thread.currentThread().getName());
  18. }
  19. }
  20. =======测试运行结果:从下面的运行结果可以看出是异步执行了=======
  21. 邮件地址:249968839@qq.com
  22. 邮件内容:This is a event test
  23. com.hrh.ext.EmailEvent[source=hello]:SimpleAsyncTaskExecutor-2
  24. 容器本身事件:org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@2e5d6d97, started on Mon Nov 09 22:29:09 CST 2020]
  25. 容器本身事件:org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@2e5d6d97, started on Mon Nov 09 22:29:09 CST 2020]
  26. org.springframework.context.event.ContextRefreshedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@2e5d6d97, started on Mon Nov 09 22:29:09 CST 2020]:SimpleAsyncTaskExecutor-1
  27. org.springframework.context.event.ContextClosedEvent[source=org.springframework.context.annotation.AnnotationConfigApplicationContext@2e5d6d97, started on Mon Nov 09 22:29:09 CST 2020]:SimpleAsyncTaskExecutor-3

  5.Spring事务监听机制---使用 @TransactionalEventListener 处理数据库事务提交成功后再执行操作

    在项目中,往往需要执行数据库操作后,发送消息或事件来异步调用其他组件执行相应的操作,例如:用户注册后发送激活码、配置修改后发送更新事件等。

    但是,数据库的操作如果还未完成,此时异步调用的方法查询数据库发现没有数据,这就会出现问题。

    如下面伪代码案例: 

  1. void saveUser(User u) {
  2. //保存用户信息
  3. userDao.save(u);
  4. //触发保存用户事件
  5. applicationContext.publishEvent(new SaveUserEvent(u.getId()));
  6. }
  7.  
  8. @EventListener
  9. void onSaveUserEvent(SaveUserEvent event) {
  10. //获取事件中的信息(用户id)
  11. Integer id = event.getEventData();
  12. //查询数据库,获取用户(此时如果用户还未插入数据库,则返回空)
  13. User u = userDao.getUserById(id);
  14. //这里可能报空指针异常!
  15. String phone = u.getPhoneNumber();
  16. MessageUtils.sendMessage(phone);
  17. }

         为了解决上述问题,Spring为我们提供了两种方式: @TransactionalEventListener 注解 和 事务同步管理器 TransactionSynchronizationManager,以便我们可以在事务提交后再触发某一事件。

    @TransactionalEventListener 注解的使用案例:只有当前事务提交之后,才会执行事件监听器的方法

  1. //phase默认为AFTER_COMMIT,共有四个枚举:BEFORE_COMMIT,AFTER_COMMIT,AFTER_ROLLBACK,AFTER_COMPLETION
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
  2. void onSaveUserEvent(SaveUserEvent event) {
  3. Integer id = event.getEventData();
  4. User u = userDao.getUserById(id);
  5. String phone = u.getPhoneNumber();
  6. MessageUtils.sendMessage(phone);
  7. }

    TransactionSynchronizationManager 的使用案例:@TransactionalEventListener底层下面这样来实现的

  1. @EventListener
  2. void onSaveUserEvent(SaveUserEvent event) {
  3. TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
  4. @Override
  5. public void afterCommit() {
  6. Integer id = event.getEventData();
  7. User u = userDao.getUserById(id);
  8. String phone = u.getPhoneNumber();
  9. MessageUtils.sendMessage(phone);
  10. }
  11. });
  12. }

Spring笔记(7) - Spring的事件和监听机制的更多相关文章

  1. 深入理解Spring的容器内事件发布监听机制

    目录 1. 什么是事件监听机制 2. JDK中对事件监听机制的支持 2.1 基于JDK实现对任务执行结果的监听 3.Spring容器对事件监听机制的支持 3.1 基于Spring实现对任务执行结果的监 ...

  2. 【spring源码学习】spring的事件发布监听机制源码解析

    [一]相关源代码类 (1)spring的事件发布监听机制的核心管理类:org.springframework.context.event.SimpleApplicationEventMulticast ...

  3. 【cocos2d-js官方文档】事件分发监听机制(摘录)

    简介 游戏开发中一个很重要的功能就是交互,如果没有与用户的交互,那么游戏将变成动画,而处理用户交互就需要使用事件监听器了. 总概: 事件监听器(cc.EventListener) 封装用户的事件处理逻 ...

  4. Spring ApplicationContext(八)事件监听机制

    Spring ApplicationContext(八)事件监听机制 本节则重点关注的是 Spring 的事件监听机制,主要是第 8 步:多播器注册:第 10 步:事件注册. public void ...

  5. Spring Boot(六)自定义事件及监听

    事件及监听并不是SpringBoot的新功能,Spring框架早已提供了完善的事件监听机制,在Spring框架中实现事件监听的流程如下: 自定义事件,继承org.springframework.con ...

  6. Spring 事件监听机制及原理分析

    简介 在JAVA体系中,有支持实现事件监听机制,在Spring 中也专门提供了一套事件机制的接口,方便我们实现.比如我们可以实现当用户注册后,给他发送一封邮件告诉他注册成功的一些信息,比如用户订阅的主 ...

  7. Spring事件发布与监听机制

    我是陈皮,一个在互联网 Coding 的 ITer,微信搜索「陈皮的JavaLib」第一时间阅读最新文章,回复[资料],即可获得我精心整理的技术资料,电子书籍,一线大厂面试资料和优秀简历模板. 目录 ...

  8. Spring事件监听机制源码解析

    Spring事件监听器使用 1.Spring事件监听体系包括三个组件:事件.事件监听器,事件广播器. 事件:定义事件类型和事件源,需要继承ApplicationEvent. package com.y ...

  9. Spring Boot 事件和监听

    Application Events and Listeners 1.自定义事件和监听 1.1.定义事件 package com.cjs.boot.event; import lombok.Data; ...

随机推荐

  1. ansible-playbook调试

    1. ansible-playbook  1)ansible-playbook的语法检测 1 [root@test-1 bin]# ansible-playbook --syntax-check ng ...

  2. 实验一 HTML基本标签及文本处理

    实验一 HTML基本标签及文本处理 [实验目的] 1.掌握利用因特网进行信息游览.搜索,下载网页.图片.文字和文件: 2.对给定的网站,能指出网站的链接结构.目录结构.页面布局方式: 3.掌握HTML ...

  3. ssh登录二次验证,让服务器更安全。

    码云地址 sshdTwoVerification 介绍 ssh登录二次验证 问题:现在很多人的Linux服务器可能会被攻击,只校验一次后台用户名密码登录变得不再保险. 当然大家首先要做的是修改ssh服 ...

  4. elasticsearch-安装-centos7- es7.5 搭建

        centos6 搭建 参考 https://www.cnblogs.com/php-linux/p/8758788.html   搭建linux虚拟机  https://www.cnblogs ...

  5. python操作excel xlwt (转)

    Python中xlrd和xlwt模块使用方法   阅读目录 安装 xlrd模块使用 xlwt模块 xlrd模块实现对excel文件内容读取,xlwt模块实现对excel文件的写入. 回到顶部 安装 ? ...

  6. 安装Linux注意事项

    网络配置NAT Worstation 生成虚拟网卡,编辑虚拟网络中子网IP地址为10网段内部地址,避免冲突.  Linux命令 查看主机IP地址 [root@C8 ~]# hostname -I 19 ...

  7. 不可不知的资源管理调度器Hadoop Yarn

    Yarn(Yet Another Resource Negotiator)是一个资源调度平台,负责为运算程序如Spark.MapReduce分配资源和调度,不参与用户程序内部工作.同样是Master/ ...

  8. Vue留言 checked框案列

    在命令行窗口输入vue create "工程名"命令 来创建vue脚手架

  9. 实战四:Gateway网关作全局路由转发

    Gateway网关的作用主要是两个:路由转发,请求过滤.此篇讲的是路由转发,下篇介绍请求过滤. 一,创建网关module,添加依赖 1,new -> module -> maven 或直接 ...

  10. 树和堆(julyedu网课整理)

    date: 2018-12-05 16:59:15 updated: 2018-12-05 16:59:15 树和堆(julyedu网课整理) 1 定义 1.1 树的定义 它是由n(n>=1)个 ...