if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) { RootBeanDefinitiondef=newRootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)); }
// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor. if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) { RootBeanDefinitiondef=newRootBeanDefinition(CommonAnnotationBeanPostProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)); }
// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor. if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) { RootBeanDefinitiondef=newRootBeanDefinition(); try { def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, AnnotationConfigUtils.class.getClassLoader())); } catch (ClassNotFoundException ex) { thrownewIllegalStateException( "Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex); } def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)); }
if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) { RootBeanDefinitiondef=newRootBeanDefinition(EventListenerMethodProcessor.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME)); }
if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) { RootBeanDefinitiondef=newRootBeanDefinition(DefaultEventListenerFactory.class); def.setSource(source); beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME)); }
@Override publicvoidregister(Class<?>... componentClasses) { // 检验传入进来的 comonpentClasses是一定要有值的. Assert.notEmpty(componentClasses, "At least one component class must be specified"); this.reader.register(componentClasses); }
// Destroy already created singletons to avoid dangling resources. destroyBeans();
// Reset 'active' flag. cancelRefresh(ex);
// Propagate exception to caller. throw ex; }
finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } }
prepareRefresh() 方法
从注释来看, 设置startup数据 & 标识active来表示状态,同时也会初始化一些资源.
/** * Prepare this context for refreshing, setting its startup date and * active flag as well as performing any initialization of property sources. */ protectedvoidprepareRefresh() { // Switch to active. this.startupDate = System.currentTimeMillis(); // 对状态标识的设置. this.closed.set(false); this.active.set(true);
if (logger.isDebugEnabled()) { if (logger.isTraceEnabled()) { logger.trace("Refreshing " + this); } else { logger.debug("Refreshing " + getDisplayName()); } }
// Initialize any placeholder property sources in the context environment. // 这里暂时没有实现来做事情. initPropertySources();
// Validate that all properties marked as required are resolvable: // see ConfigurablePropertyResolver#setRequiredProperties // org.springframework.core.env.AbstractEnvironment#validateRequiredProperties // 对 org.springframework.core.env.AbstractPropertyResolver#requiredProperties 进行检验,如果检验到有问题的话,就会抛出异常来. // 这里是对 properties 进行检验. getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners... // earlyApplicationListeners是null的话,利用applicationListeners来初始化. if (this.earlyApplicationListeners == null) { this.earlyApplicationListeners = newLinkedHashSet<>(this.applicationListeners); } else { // 如果已经存在值了,就对 applicationListeners 清空,然后全部添加applicationListeners来. // Reset local application listeners to pre-refresh state. this.applicationListeners.clear(); this.applicationListeners.addAll(this.earlyApplicationListeners); }
// Allow for the collection of early ApplicationEvents, // to be published once the multicaster is available... this.earlyApplicationEvents = newLinkedHashSet<>(); }
/** * Configure the factory's standard context characteristics, * such as the context's ClassLoader and post-processors. * @param beanFactory the BeanFactory to configure */ protectedvoidprepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { // Tell the internal bean factory to use the context's class loader etc. // org.springframework.core.io.DefaultResourceLoader#getClassLoader // 设置 class 加载器&赋值进去. beanFactory.setBeanClassLoader(getClassLoader()); // 将 beanClassLoader放入SpelParserConfiguration中来,SpelExpressionParser中有含有SpelParserConfiguration作为configuration,StandardBeanExpressionResolver属性又含有SpelExpressionParser. 这也就可以理解为beanClassLoader最后是放入到SpelParserConfiguration来. beanFactory.setBeanExpressionResolver(newStandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); // 传入applicationContext和environment到ResourceEditorRegistrar对象来. //然后添加到beanFactory中来. beanFactory.addPropertyEditorRegistrar(newResourceEditorRegistrar(this, getEnvironment()));
// BeanFactory interface not registered as resolvable type in a plain factory. // MessageSource registered (and found for autowiring) as a bean. // private final Map<Class<?>, Object> resolvableDependencies = new ConcurrentHashMap<>(16); // org.springframework.beans.factory.support.DefaultListableBeanFactory#resolvableDependencies,这里将 BeanFactory.class和beanFactory给添加到 resolvableDependencies中来了,这里可以看到resolvableDependencies的key是一个Class类型. beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); beanFactory.registerResolvableDependency(ResourceLoader.class, this); beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Register early post-processor for detecting inner beans as ApplicationListeners. // 这里又添加了一个后置处理器. // 传入一个 ApplicationContext 给后置处理器,然后添加到BeanFactory中来. // org.springframework.beans.factory.support.AbstractBeanFactory#beanPostProcessors,也即是添加到专门存放 后置处理器的集合中来了. beanFactory.addBeanPostProcessor(newApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found. // beanFactory如果有loadTimeWeaver,那么就添加 LoadTimeWeaverAwareProcessor 后置处理器进来 if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(newLoadTimeWeaverAwareProcessor(beanFactory)); // Set a temporary ClassLoader for type matching. beanFactory.setTempClassLoader(newContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); }
// Register default environment beans. // 不包含environment/systemProperties/systemEnvironment,就会添加到org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#singletonObjects中来. if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment()); } if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties()); } if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment()); } }
/** * Modify the application context's internal bean factory after its standard * initialization. All bean definitions will have been loaded, but no beans * will have been instantiated yet. This allows for registering special * BeanPostProcessors etc in certain ApplicationContext implementations. * @param beanFactory the bean factory used by the application context */ protectedvoidpostProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { }
/** * Instantiate and invoke all registered BeanFactoryPostProcessor beans, * respecting explicit order if given. * <p>Must be called before singleton instantiation. */ protectedvoidinvokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) { // getBeanFactoryPostProcessors() 获取出来的是空集合. PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor) if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(newLoadTimeWeaverAwareProcessor(beanFactory)); beanFactory.setTempClassLoader(newContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } }
// Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let the bean factory post-processors apply to them! // Separate between BeanDefinitionRegistryPostProcessors that implement // PriorityOrdered, Ordered, and the rest. List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = newArrayList<>();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered. postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { // 如果processedBeans集合中不包含并且type是Ordered.class才满足进来的条件. if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); } } // 所以这里的currentRegistryProcessors集合是空集合. sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear();
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear. // 这里用 while 循环来最后解析,判断从getBeanNamesForType获取出来的bean是不是被解析过了的. // 也是用 processedBeans 集合来进行控制的. booleanreiterate=true; while (reiterate) { reiterate = false; postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { if (!processedBeans.contains(ppName)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); reiterate = true; } } sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); }
// Now, invoke the postProcessBeanFactory callback of all processors handled so far. // org.springframework.context.annotation.ConfigurationClassPostProcessor#postProcessBeanFactory,这里是走到了postProcessBeanFactory回调方法来了.用org.springframework.context.annotation.ConfigurationClassPostProcessor#factoriesPostProcessed集合来控制是否解析过了.用registriesPostProcessed集合来判断上次是否进入到postProcessBeanDefinitionRegistry方法中来. 如果没有的话,就会再走一边processConfigBeanDefinitions,可以看到 postProcessBeanDefinitionRegistry 方法最后也是走到了processConfigBeanDefinitions中来了. //org.springframework.context.annotation.ConfigurationClassPostProcessor#enhanceConfigurationClasses 该方法判断是不是需要代理来增强,这里是没有的,所以就直接return掉了. // 最后添加一个 ImportAwareBeanPostProcessor 后置处理器进来. invokeBeanFactoryPostProcessors(registryProcessors, beanFactory); // 这里的regularPostProcessors 集合是empty. invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); }
else { // Invoke factory processors registered with the context instance. invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory); }
// Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let the bean factory post-processors apply to them! // org.springframework.context.annotation.internalConfigurationAnnotationProcessor和org.springframework.context.event.internalEventListenerProcessor这里获取出来的是二个. String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered, // Ordered, and the rest. List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = newArrayList<>(); List<String> orderedPostProcessorNames = newArrayList<>(); List<String> nonOrderedPostProcessorNames = newArrayList<>(); for (String ppName : postProcessorNames) { // 这里是对上面已经处理过了的进行过滤处理. if (processedBeans.contains(ppName)) { // skip - already processed in first phase above } // 这里分为 PriorityOrdered&Ordered&非前二者,分这三种情况分别放入到三个不同的集合中. elseif (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)); } elseif (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { nonOrderedPostProcessorNames.add(ppName); } }
// 这里是可以看到先是对PriorityOrdered进行处理,再对Ordered处理,最后对非前二者进行处理. // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered. sortPostProcessors(priorityOrderedPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered. List<BeanFactoryPostProcessor> orderedPostProcessors = newArrayList<>(orderedPostProcessorNames.size()); for (String postProcessorName : orderedPostProcessorNames) { // 注意这里是调用了getBean方法. orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } // 排序 sortPostProcessors(orderedPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Clear cached merged bean definitions since the post-processors might have // modified the original metadata, e.g. replacing placeholders in values... // org.springframework.beans.factory.support.DefaultListableBeanFactory#clearMetadataCache // 对 一些集合等进行清除. beanFactory.clearMetadataCache(); }
// Register BeanPostProcessorChecker that logs an info message when // a bean is created during BeanPostProcessor instantiation, i.e. when // a bean is not eligible for getting processed by all BeanPostProcessors. // 6 intbeanProcessorTargetCount= beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length; // 传入beanFactory和个数,创建出一个检查bean的后置处理器来. // org.springframework.context.support.PostProcessorRegistrationDelegate.BeanPostProcessorChecker // 有兴趣的同学可以看到该后置处理器重写的方法做了什么事情. // 最后添加到 beanFactory 中来. beanFactory.addBeanPostProcessor(newBeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// Separate between BeanPostProcessors that implement PriorityOrdered, // Ordered, and the rest. List<BeanPostProcessor> priorityOrderedPostProcessors = newArrayList<>(); List<BeanPostProcessor> internalPostProcessors = newArrayList<>(); List<String> orderedPostProcessorNames = newArrayList<>(); List<String> nonOrderedPostProcessorNames = newArrayList<>(); // 对后置处理器进行迭代 for (String ppName : postProcessorNames) { if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { // 注意这里调用 getBean 方法是已经实例化这个后置处理起了. // AutowiredAnnotationBeanPostProcessor // CommonAnnotationBeanPostProcessor // 这里实例化的是Spring内置的二个 BeanPostProcessorpp= beanFactory.getBean(ppName, BeanPostProcessor.class); priorityOrderedPostProcessors.add(pp); // 内部的二个后置处理器都是有实现 MergedBeanDefinitionPostProcessor 的. if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } elseif (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { nonOrderedPostProcessorNames.add(ppName); } }
// First, register the BeanPostProcessors that implement PriorityOrdered. // 排序 sortPostProcessors(priorityOrderedPostProcessors, beanFactory); // 添加到 org.springframework.beans.factory.support.AbstractBeanFactory#beanPostProcessors,也就是添加到Spring的BanFactory中来. registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered. // 这里是对实现了 Ordered 类型的处理,很显然我这里是没有的. List<BeanPostProcessor> orderedPostProcessors = newArrayList<>(orderedPostProcessorNames.size()); for (String ppName : orderedPostProcessorNames) { BeanPostProcessorpp= beanFactory.getBean(ppName, BeanPostProcessor.class); orderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } sortPostProcessors(orderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// Re-register post-processor for detecting inner beans as ApplicationListeners, // moving it to the end of the processor chain (for picking up proxies etc). // ApplicationListenerDetector 这里也是对 ApplicationListenerDetector 也是重新注册一遍. beanFactory.addBeanPostProcessor(newApplicationListenerDetector(applicationContext)); }
/** * Template method which can be overridden to add context-specific refresh work. * Called on initialization of special beans, before instantiation of singletons. * <p>This implementation is empty. * @throws BeansException in case of errors * @see #refresh() */ protectedvoidonRefresh()throws BeansException { // For subclasses: do nothing by default. }
/** * Add beans that implement ApplicationListener as listeners. * Doesn't affect other listeners, which can be added without being beans. */ protectedvoidregisterListeners() { // Register statically specified listeners first. // getApplicationListeners() 获取出来的是空集合. 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! // 根据ApplicationListener来获取出监听器,这也也是没有的. 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... // 这里也是获取早初始的 ApplicationEvent. Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents; this.earlyApplicationEvents = null; if (earlyEventsToProcess != null) { for (ApplicationEvent earlyEvent : earlyEventsToProcess) { getApplicationEventMulticaster().multicastEvent(earlyEvent); } } }
/** * Finish the initialization of this context's bean factory, * initializing all remaining singleton beans. */ protectedvoidfinishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { // Initialize conversion service for this context. // 如果beanFactroy包含conversionService并且type是ConversionService.class的话, if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) && beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) { // 就会从beanFactory中获取出对象设置到beanFactory的ConversionService来. beanFactory.setConversionService( beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)); }
// Register a default embedded value resolver if no bean post-processor // (such as a PropertyPlaceholderConfigurer bean) registered any before: // at this point, primarily for resolution in annotation attribute values. if (!beanFactory.hasEmbeddedValueResolver()) { //org.springframework.beans.factory.support.AbstractBeanFactory#addEmbeddedValueResolver //添加到org.springframework.beans.factory.support.AbstractBeanFactory#embeddedValueResolvers中来. beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal)); }
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early. // 根据 LoadTimeWeaverAware.class 来获取信息. // 很明显这里我们是没有配置的,所以也就是没有的. String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false); for (String weaverAwareName : weaverAwareNames) { getBean(weaverAwareName); }
// Stop using the temporary ClassLoader for type matching. beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes. //org.springframework.beans.factory.support.DefaultListableBeanFactory#freezeConfiguration // 设置configurationFrozen是true, // 将beanDefinitionNames集合转哈为String类型的数组. StringUtils.toStringArray(this.beanDefinitionNames);使用这个方法即可. beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons. beanFactory.preInstantiateSingletons(); }
preInstantiateSingletons 方法
这里就是对 单例池 里面的对象进行初始化,可以看到是有 getBean 方法的.
@Override publicvoidpreInstantiateSingletons()throws BeansException { if (logger.isTraceEnabled()) { logger.trace("Pre-instantiating singletons in " + this); }
// Iterate over a copy to allow for init methods which in turn register new bean definitions. // While this may not be part of the regular factory bootstrap, it does otherwise work fine. // 这里获取出来的 beanNames 是有6个的,其中五个是包含了内部的 //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 //yangBeanScannerConfig List<String> beanNames = newArrayList<>(this.beanDefinitionNames);
/** * Finish the refresh of this context, invoking the LifecycleProcessor's * onRefresh() method and publishing the * {@link org.springframework.context.event.ContextRefreshedEvent}. */ protectedvoidfinishRefresh() { // Clear context-level resource caches (such as ASM metadata from scanning). //对org.springframework.core.io.DefaultResourceLoader#resourceCaches进行清除. clearResourceCaches();
// Initialize lifecycle processor for this context. initLifecycleProcessor();
// Propagate refresh to lifecycle processor first. //org.springframework.context.support.DefaultLifecycleProcessor //org.springframework.context.support.DefaultLifecycleProcessor#startBeans getLifecycleProcessor().onRefresh();
// Publish the final event. // 推送Event,这里的Event是 ContextRefreshedEvent. publishEvent(newContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active. //org.springframework.context.support.LiveBeansView#registerApplicationContext //先根据key:spring.liveBeansView.mbeanDomain获取value,这里获取出来的是null, // 所以也就是没有下文了. LiveBeansView.registerApplicationContext(this); }
initLifecycleProcessor 方法 ()
/** * Initialize the LifecycleProcessor. * Uses DefaultLifecycleProcessor if none defined in the context. * @see org.springframework.context.support.DefaultLifecycleProcessor */ protected void initLifecycleProcessor() { // 获取出 beanFactory 来. ConfigurableListableBeanFactory beanFactory = getBeanFactory(); // 判断beanFactory中是否包含lifecycleProcessor if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) { // 包含的话,就会获取出来,指向this.lifecycleProcessor this.lifecycleProcessor = beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class); if (logger.isTraceEnabled()) { logger.trace("Using LifecycleProcessor [" + this.lifecycleProcessor + "]"); } } else { // 如果不包含的话,就自己new一个,然后注册到Spring容器中来. DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor(); defaultProcessor.setBeanFactory(beanFactory); this.lifecycleProcessor = defaultProcessor; beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor); if (logger.isTraceEnabled()) { logger.trace("No '" + LIFECYCLE_PROCESSOR_BEAN_NAME + "' bean, using " + "[" + this.lifecycleProcessor.getClass().getSimpleName() + "]"); } } }
publishEvent 方法
/** * Publish the given event to all listeners. * @param event the event to publish (may be an {@link ApplicationEvent} * or a payload object to be turned into a {@link PayloadApplicationEvent}) * @param eventType the resolved event type, if known * @since 4.2 */ protectedvoidpublishEvent(Object event, @Nullable ResolvableType eventType) { Assert.notNull(event, "Event must not be null");
// Decorate event as an ApplicationEvent if necessary ApplicationEvent applicationEvent; // 对传入进来的 event 进行类型的判断. if (event instanceof ApplicationEvent) { applicationEvent = (ApplicationEvent) event; } else { applicationEvent = newPayloadApplicationEvent<>(this, event); if (eventType == null) { eventType = ((PayloadApplicationEvent<?>) applicationEvent).getResolvableType(); } }
// Multicast right now if possible - or lazily once the multicaster is initialized if (this.earlyApplicationEvents != null) { this.earlyApplicationEvents.add(applicationEvent); } else { //org.springframework.context.event.SimpleApplicationEventMulticaster#multicastEvent(org.springframework.context.ApplicationEvent, org.springframework.core.ResolvableType) //走到了这里来发送event的, getApplicationEventMulticaster().multicastEvent(applicationEvent, eventType); }
// Publish event via parent context as well... // 这里的 parent是null. if (this.parent != null) { if (this.parent instanceof AbstractApplicationContext) { ((AbstractApplicationContext) this.parent).publishEvent(event, eventType); } else { this.parent.publishEvent(event); } } }