Spring initApplicationEventMulticaster

demo

  1. package com.huifer.source.spring.applicationListener;
  2. import org.springframework.context.ApplicationEvent;
  3. import org.springframework.context.ApplicationListener;
  4. public class DemoApplicationListener implements ApplicationListener {
  5. @Override
  6. public void onApplicationEvent(ApplicationEvent event) {
  7. System.out.println("com.huifer.source.spring.applicationListener.DemoApplicationListener.onApplicationEvent");
  8. }
  9. }
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xmlns="http://www.springframework.org/schema/beans"
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
  5. <bean id="demoApplicationListener" class="com.huifer.source.spring.applicationListener.DemoApplicationListener"/>
  6. </beans>
  1. public class ListenerSourceCode {
  2. public static void main(String[] args) {
  3. ApplicationContext context = new ClassPathXmlApplicationContext("Listener-demo.xml");
  4. }
  5. }

初始化入口

  • org.springframework.context.support.AbstractApplicationContext.refresh中的initApplicationEventMulticaster方法
  1. protected void initApplicationEventMulticaster() {
  2. ConfigurableListableBeanFactory beanFactory = getBeanFactory();
  3. // 判断是否存在名字applicationEventMulticaster的bean
  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. // 创建一个
  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. }

注册

  1. protected void registerListeners() {
  2. // Register statically specified listeners first.
  3. // 读取 ApplicationListener
  4. for (ApplicationListener<?> listener : getApplicationListeners()) {
  5. getApplicationEventMulticaster().addApplicationListener(listener);
  6. }
  7. // Do not initialize FactoryBeans here: We need to leave all regular beans
  8. // uninitialized to let post-processors apply to them!
  9. /**
  10. * 寻找类型为{@link ApplicationListener} 的beanName,目标文件为用户配置文件
  11. */
  12. String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
  13. for (String listenerBeanName : listenerBeanNames) {
  14. /**
  15. * 1. 获取 {@link applicationEventMulticaster}
  16. * 2. 添加监听器名称
  17. */
  18. getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
  19. }
  20. // Publish early application events now that we finally have a multicaster...
  21. Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
  22. this.earlyApplicationEvents = null;
  23. if (earlyEventsToProcess != null) {
  24. for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
  25. getApplicationEventMulticaster().multicastEvent(earlyEvent);
  26. }
  27. }
  28. }

image-20200119163638222

finishRefresh 发布

  1. protected void finishRefresh() {
  2. // Clear context-level resource caches (such as ASM metadata from scanning).
  3. clearResourceCaches();
  4. // Initialize lifecycle processor for this context.
  5. initLifecycleProcessor();
  6. // Propagate refresh to lifecycle processor first.
  7. getLifecycleProcessor().onRefresh();
  8. // Publish the final event.
  9. // 发布事件做处理
  10. publishEvent(new ContextRefreshedEvent(this));
  11. // Participate in LiveBeansView MBean, if active.
  12. LiveBeansView.registerApplicationContext(this);
  13. }
  • org.springframework.context.support.AbstractApplicationContext#publishEvent(org.springframework.context.ApplicationEvent)
    • org.springframework.context.support.AbstractApplicationContext#publishEvent(java.lang.Object, org.springframework.core.ResolvableType)
  1. protected void publishEvent(Object event, @Nullable ResolvableType eventType) {
  2. Assert.notNull(event, "Event must not be null");
  3. // Decorate event as an ApplicationEvent if necessary
  4. ApplicationEvent applicationEvent;
  5. if (event instanceof ApplicationEvent) {
  6. applicationEvent = (ApplicationEvent) event;
  7. }
  8. else {
  9. applicationEvent = new PayloadApplicationEvent<>(this, event);
  10. if (eventType == null) {
  11. eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType();
  12. }
  13. }
  14. // Multicast right now if possible - or lazily once the multicaster is initialized
  15. if (this.earlyApplicationEvents != null) {
  16. this.earlyApplicationEvents.add(applicationEvent);
  17. }
  18. else {
  19. /**
  20. * 执行监听事件
  21. * {@link ApplicationEventMulticaster} ->{@link SimpleApplicationEventMulticaster}
  22. */
  23. getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType);
  24. }
  25. // Publish event via parent context as well...
  26. if (this.parent != null) {
  27. if (this.parent instanceof AbstractApplicationContext) {
  28. ((AbstractApplicationContext) this.parent).publishEvent(event, eventType);
  29. }
  30. else {
  31. this.parent.publishEvent(event);
  32. }
  33. }
  34. }
  • 执行监听方法

image-20200119164149650

  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. }
  1. @SuppressWarnings({"rawtypes", "unchecked"})
  2. private void doInvokeListener(ApplicationListener listener, ApplicationEvent event) {
  3. try {
  4. // 最后调用方法
  5. listener.onApplicationEvent(event);
  6. }
  7. catch (ClassCastException ex) {
  8. String msg = ex.getMessage();
  9. if (msg == null || matchesClassCastMessage(msg, event.getClass())) {
  10. // Possibly a lambda-defined listener which we could not resolve the generic event type for
  11. // -> let's suppress the exception and just log a debug message.
  12. Log logger = LogFactory.getLog(getClass());
  13. if (logger.isTraceEnabled()) {
  14. logger.trace("Non-matching event type for listener: " + listener, ex);
  15. }
  16. }
  17. else {
  18. throw ex;
  19. }
  20. }
  21. }

image-20200119164402137

image-20200119164410301