还是拿最熟悉的 web 程序为例,对应的 Spring 容器是 AnnotationConfigServletWebServerApplicationContext.class,上面的 refresh() 方法调用的是它的的父类 AbstractApplicationContext.class中的refresh 方法。
// 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(); } } }
/** * 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 // 验证环境信息里一些必须存在的属性 getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners... if (this.earlyApplicationListeners == null) { this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners); } else { // 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 = new LinkedHashSet<>(); }
protectedvoidprepareBeanFactory(ConfigurableListableBeanFactory beanFactory){ // Tell the internal bean factory to use the context's class loader etc. // 1.设置beanFactory的类加载器(用于加载bean) beanFactory.setBeanClassLoader(getClassLoader()); // 2.设置beanFactory的表达式解析器 beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); // 3.添加属性编辑注册器 beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks. // 4.添加ApplicationContextAwareProcessor这个beanPostProcessor beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); // 5.取消EnvironmentAware、EmbeddedValueResolverAware、ResourceLoaderAware、ApplicationEventPublisherAware、MessageSourceAware、ApplicationContextAware这6个接口的自动注入,因为上面添加的ApplicationContextAwareProcessor.class把这6个接口的实现工作都做了(可以去看类里的invokeAwareInterfaces()方法) beanFactory.ignoreDependencyInterface(EnvironmentAware.class); beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class); beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class); beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class); beanFactory.ignoreDependencyInterface(MessageSourceAware.class); beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// BeanFactory interface not registered as resolvable type in a plain factory. // MessageSource registered (and found for autowiring) as a bean. // 6.注册可以解析的自动装配类,使得我们可以在程序的任何地方使用@Autowired完成自动注入 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. // 7.添加BeanPostProcessor后置处理器,这个处理器用于在bean初始化前后添加和移除ApplicationListener监听器 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found. // 8.添加一个BeanPostProcessor,这个处理器用于添加编译时的AspectJ. if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); // Set a temporary ClassLoader for type matching. beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); }
// Register default environment beans. // 9.给beanFactory注册一些能用的组件,包括环境信息ConfigurableEnvironment、系统属性、系统环境变量 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()); } }
// 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(new LoadTimeWeaverAwareProcessor(beanFactory)); beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(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. // 用于保存本次需要执行的BeanDefinitionRegistryPostProcessor List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear. boolean reiterate = true; while (reiterate) { reiterate = false; // 再次查找,原因同上 postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); // 3.3 最后,执行所有没有实现优先级接口的BeanDefinitionRegistryPostProcessor for (String ppName : postProcessorNames) { // 跳过已执行的 if (!processedBeans.contains(ppName)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); // 如果有BeanDefinitionRegistryPostProcessor被执行了,可能会产生新的BeanDefinitionRegistryPostProcessor,因此将reiterate赋值为true,代表再循环查找一次 reiterate = true; } } sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); }
// Now, invoke the postProcessBeanFactory callback of all processors handled so far. // 4.接着,执行BeanFactoryPostProcessor的postProcessBeanFactory()方法对上面3个步骤获取到的所有BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor类型的bean进行处理 // 4.1 先执行BeanDefinitionRegistryPostProcessor的postProcessBeanFactory()方法 invokeBeanFactoryPostProcessors(registryProcessors, beanFactory); // 4.2 然后执行普通BeanFactoryPostProcessor的postProcessBeanFactory()方法 invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); }
// 如果BeanFactory不是BeanDefinitionRegistry,则表示它不具备注册BeanDefinition的功能,因此直接将传入beanFactoryPostProcessors视为普通BeanFactoryPostProcessor,执行postProcessBeanFactory()方法 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! // 5.接下来从Spring容器中查找BeanFactoryPostProcessor接口的实现类,然后执行,这里的查找规则与上面查找BeanDefinitionRegistryPostProcessor一样,先查实现PriorityOrdered的,在找实现Ordered的,最后是两者都没有实现的 String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered, // Ordered, and the rest. // 存放实现了PriorityOrdered接口的BeanFactoryPostProcessor List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>(); // 存放实现了Ordered接口的BeanFactoryPostProcessor List<String> orderedPostProcessorNames = new ArrayList<>(); // 存放普通的BeanFactoryPostProcessor List<String> nonOrderedPostProcessorNames = new ArrayList<>(); // 遍历从Spring容器中找到的postProcessorNames,将其按照实现了PriorityOrdered、实现了Ordered、普通区分开来 for (String ppName : postProcessorNames) { // 跳过已经执行的 if (processedBeans.contains(ppName)) { // skip - already processed in first phase above } // 添加实现了PriorityOrdered的 elseif (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)); } // 添加实现了Ordered的 elseif (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } // 添加普通的 else { nonOrderedPostProcessorNames.add(ppName); } }
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered. // 首先执行实现了PriorityOrdered接口的BeanFactoryPostProcessor sortPostProcessors(priorityOrderedPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered. // 然后执行实现了Ordered接口的 List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(); for (String postProcessorName : orderedPostProcessorNames) { orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } sortPostProcessors(orderedPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors. // 最后执行普通的 List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(); for (String postProcessorName : nonOrderedPostProcessorNames) { nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
// Clear cached merged bean definitions since the post-processors might have // modified the original metadata, e.g. replacing placeholders in values... beanFactory.clearMetadataCache(); }
@FunctionalInterface publicinterfaceBeanFactoryPostProcessor{ /** * 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 overriding or adding * properties even to eager-initializing beans. * @param beanFactory the bean factory used by the application context * @throws org.springframework.beans.BeansException in case of errors */ voidpostProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)throws BeansException; }
// 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. // BeanPostProcessor的目标计数 int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length; // 2.添加BeanPostProcessorChecker(主要用于记录信息)到beanFactory中 beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// Separate between BeanPostProcessors that implement PriorityOrdered, // Ordered, and the rest. // 3. 定义几个变量,区分实现了PriorityOrdered接口的BeanPostProcessor、实现了Ordered接口的BeanPostProcessor、普通BeanPostProcessor // 3.1 存放实现了PriorityOrdered的BeanPostProcessor List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>(); // 3.2 存放实现了MergedBeanDefinitionPostProcessor的BeanPostProcessor List<BeanPostProcessor> internalPostProcessors = new ArrayList<>(); // 3.3 存放实现了Ordered的BeanPostProcessor的beanName List<String> orderedPostProcessorNames = new ArrayList<>(); // 3.4 存放普通的BeanPostProcessor的beanName List<String> nonOrderedPostProcessorNames = new ArrayList<>(); // 4. 遍历postProcessorNames,将BeanPostProcessors按3.1 - 3.4定义的变量区分开 for (String ppName : postProcessorNames) { if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); priorityOrderedPostProcessors.add(pp); 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. // 5. 先将实现了PriorityOrdered的BeanPostProcessor注册到beanFactory中 sortPostProcessors(priorityOrderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered. // 6.接着是实现了Ordered的BeanPostProcessor List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(); for (String ppName : orderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); orderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } sortPostProcessors(orderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, orderedPostProcessors);
// Now, register all regular BeanPostProcessors. // 7.然后是普通的BeanPostProcessor List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(); for (String ppName : nonOrderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); nonOrderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
// Re-register post-processor for detecting inner beans as ApplicationListeners, // moving it to the end of the processor chain (for picking up proxies etc). // 9.重新注册ApplicationListenerDetector,主要是为了将这个类移动到处理器链的末尾 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext)); }
// Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let post-processors apply to them! // 2. 获取beanFactory中的ApplicationListener.class,将其添加到广播器中 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... // 3. 发布早期应用程序事件到相应的监听器 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. if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) && beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) { 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()) { beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal)); }
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early. String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false); for (String weaverAwareName : weaverAwareNames) { getBean(weaverAwareName); }
// Stop using the temporary ClassLoader for type matching. // 停用临时的ClassLoader beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes. // 冻结所有的bean定义,已经注册的bean不能再被修改定义了,因为马上就要创建Bean的实例对象了 beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons. // 实例化所有剩余的单例对象(懒加载除外) beanFactory.preInstantiateSingletons(); }
/** * 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). clearResourceCaches();
// Initialize lifecycle processor for this context. // 1. 初始化生命周期处理器 initLifecycleProcessor();
// Propagate refresh to lifecycle processor first. // 2.调用生命周期处理器的onRefresh()方法,最终就是调用了SmartLifecycle的start方法 getLifecycleProcessor().onRefresh();
// Publish the final event. // 3.发布上下文刷新完毕事件到相应的监听器 publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active. LiveBeansView.registerApplicationContext(this); }