spring IOC - AnnotationConfigApplicationContext#refresh1
接上一篇, 看 refresh() 方法.
refresh
org.springframework.context.support.AbstractApplicationContext#refresh 方法, 是一个非常强大的方法@Override
public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. //准备工作包括设置启动时间,是否激活标识位, 初始化属性源(property source)配置 //不重要 prepareRefresh(); // Tell the subclass to refresh the internal bean factory.//返回一个factory - 为什么需要返回一个工厂 //因为要对工厂进行初始化 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context. //为beanFactory设置一些属性如ClassLoader,BeanExpressionResolver,PropertyEditorRegistrar,BeanPostProcessor等 //准备工厂 prepareBeanFactory(beanFactory); try { // Allows post-processing of the bean factory in context subclasses.//这个方法在当前版本的spring是没用任何代码的 //可能spring期待在后面的版本中去扩展吧 postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context. //为beanFactory注册BeanFactoryPostProcessor //在spring的环境中去执行已经被注册的 factory processors //设置执行自定义的ProcessBeanFactory 和spring内部自己定义的 invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation. //注册当Bean创建时候的BeanPostProcessor registerBeanPostProcessors(beanFactory); // Initialize message source for this context. //初始化上下文的消息源:DelegatingMessageSource initMessageSource(); // Initialize event multicaster for this context. //初始化了一个事件广播器:SimpleApplicationEventMulticaster initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses. onRefresh(); // Check for listener beans and register them. //获取ApplicationListener,并在事件传播器中注册他们 registerListeners(); // Instantiate all remaining (non-lazy-init) singletons. //获取LoadTimeWeaverAware并初始化他们,初始化单例并且非懒加载的Bean finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event. //完成refresh Context操作,初始化LifecycleProcessor并start,发布ContextRefreshedEvent事件 finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // 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(); } } }
prepareBeanFactory
/** * Configure the factory's standard context characteristics, * such as the context's ClassLoader and post-processors. * @param beanFactory the BeanFactory to configure */ protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { // Tell the internal bean factory to use the context's class loader etc. //设置类加载器:存在则直接设置/不存在则新建一个默认类加载器 beanFactory.setBeanClassLoader(getClassLoader()); //设置EL表达式解析器(Bean初始化完成后填充属性时会用到) //默认可以使用#{bean.xxx}的形式来调用相关属性值 beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); //设置属性注册解析器PropertyEditor beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment())); // Configure the bean factory with context callbacks. // 添加一个后置处理器 // 主要是用来处理下面几个 *Aware 的情况 beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); //设置忽略自动装配的接口 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. //注册可以解析的自动装配 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. beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); // Detect a LoadTimeWeaver and prepare for weaving, if found. // 如果当前BeanFactory包含loadTimeWeaver Bean,说明存在类加载期织入AspectJ, // 则把当前BeanFactory交给类加载期BeanPostProcessor实现类LoadTimeWeaverAwareProcessor来处理,从而实现类加载期织入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. //注册当前容器环境environment组件Bean if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment()); } //注册系统配置systemProperties组件Bean if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties()); } //注册系统环境信息systemEnvironment组件Bean if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment()); } }
这个方法, 可以不用细看, 主要就对工厂的一些属性进行默认设置.
invokeBeanFactoryPostProcessors
/** * Instantiate and invoke all registered BeanFactoryPostProcessor beans, * respecting explicit order if given. * <p>Must be called before singleton instantiation. */ protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) { //这个地方需要注意getBeanFactoryPostProcessors()是获取手动设置给spring的BeanFactoryPostProcessor,
//即你手动调用 AnnotationConfigApplicationContext.addBeanFactoryPostProcesor() 方法注册进 spring 的 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(new LoadTimeWeaverAwareProcessor(beanFactory)); beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } }
这里主要看 invokeBeanFactoryPostProcessors 方法.
里面的注释不用看, 方法主要是顺序处理 BeanDefinitionRegistryPostProcessor 和 BeanFactoryPostProcessor 的.
具体过程如下:
1. 处理 BeanDefinitionRegistryPostProcessor
1.1 处理程序员手动注册的 BeanDefinitionRegistryPostProcessor
1.2 处理实现了 PriorityOrdered 接口的 BeanDefinitionRegistryPostProcessor
1.3 处理实现了 Ordered 接口的 BeanDefinitionRegistryPostProcessor
1.4 处理其他的 BeanDefinitionRegistryPostProcessor
2. 处理 BeanFactoryPostProcessor
2.1 处理程序员手动注册的 BeanFactoryPostProcessor
2.2 处理实现了 PriorityOrdered 接口的 BeanFactoryPostProcessor
2.3 处理实现了 Ordered 接口的 BeanFactoryPostProcessor
2.4 处理其他的 BeanFactoryPostProcessor
public static void invokeBeanFactoryPostProcessors( ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) { // Invoke BeanDefinitionRegistryPostProcessors first, if any. Set<String> processedBeans = new HashSet<>(); // 1.判断beanFactory是否为BeanDefinitionRegistry,beanFactory为DefaultListableBeanFactory, // 而 DefaultListableBeanFactory实现了BeanDefinitionRegistry接口,因此这边为true if (beanFactory instanceof BeanDefinitionRegistry) { BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; // 用于存放普通的 BeanFactoryPostProcessor List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>(); // 用于存放 BeanDefinitionRegistryPostProcessor List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>(); // 2.首先处理手动加入spirng的 beanFactoryPostProcessors // 遍历所有的beanFactoryPostProcessors, 将 BeanDefinitionRegistryPostProcessor 和普通BeanFactoryPostProcessor区分开 for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) { if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) { BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor; // 2.1.1 直接执行BeanDefinitionRegistryPostProcessor接口的postProcessBeanDefinitionRegistry方法 registryProcessor.postProcessBeanDefinitionRegistry(registry); registryProcessors.add(registryProcessor); } else { regularPostProcessors.add(postProcessor); } } // 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. // 这个currentRegistryProcessors 放的是spring内部自己实现了BeanDefinitionRegistryPostProcessor接口的对象 // 用于保存本次要执行的BeanDefinitionRegistryPostProcessor List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>(); // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered. // 3.调用所有实现PriorityOrdered接口的BeanDefinitionRegistryPostProcessor实现类 // 3.1 找出所有实现BeanDefinitionRegistryPostProcessor接口的Bean的beanName //BeanDefinitionRegistryPostProcessor 等于 BeanFactoryPostProcessor //getBeanNamesForType 根据bean的类型获取bean的名字ConfigurationClassPostProcessor String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); // 3.2 遍历postProcessorNames //这个地方可以得到一个BeanFactoryPostProcessor,因为是spring默认在最开始自己注册的 //为什么要在最开始注册这个呢? //因为spring的工厂需要许解析去扫描等等功能 //而这些功能都是需要在spring工厂初始化完成之前执行 //要么在工厂最开始的时候、要么在工厂初始化之中,反正不能在之后 //因为如果在之后就没有意义,那个时候已经需要使用工厂了 //所以这里spring在一开始就注册了一个BeanFactoryPostProcessor,用来插手springfactory的实例化过程 //在这个地方断点可以知道这个类叫做 ConfigurationClassPostProcessor for (String ppName : postProcessorNames) { // 3.3 校验是否实现了PriorityOrdered接口 if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { // 3.4 获取ppName对应的bean实例, 添加到currentRegistryProcessors中, // beanFactory.getBean: 这边getBean方法会触发创建ppName对应的bean对象, 目前暂不深入解析 currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); // 3.5 将要被执行的加入processedBeans,避免后续重复执行 processedBeans.add(ppName); } } // 3.6 进行排序(根据是否实现PriorityOrdered、Ordered接口和order值来排序) //排序不重要,况且currentRegistryProcessors这里也只有一个数据 sortPostProcessors(currentRegistryProcessors, beanFactory); // 3.7 添加到registryProcessors(用于最后执行postProcessBeanFactory方法) //合并list,不重要(为什么要合并,因为还有自己的) registryProcessors.addAll(currentRegistryProcessors); // 3.8 遍历currentRegistryProcessors, 执行postProcessBeanDefinitionRegistry方法 // 最重要。注意这里是方法调用 执行所有BeanDefinitionRegistryPostProcessor // @ComponentScan 就是在执行 ConfigurationClassPostProcessor 时, 进行检测和执行的 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); // 3.9 执行完毕后, 清空currentRegistryProcessors //执行完成了所有BeanDefinitionRegistryPostProcessor //这个list只是一个临时变量,故而要清除 currentRegistryProcessors.clear(); // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered. // 4.调用所有实现了Ordered接口的BeanDefinitionRegistryPostProcessor实现类(过程跟上面的步骤3基本一样) // 4.1 找出所有实现BeanDefinitionRegistryPostProcessor接口的类, 这边重复查找是因为执行完上面的BeanDefinitionRegistryPostProcessor, // 可能会新增了其他的BeanDefinitionRegistryPostProcessor, 因此需要重新查找 postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { // 校验是否实现了Ordered接口,并且还未执行过 if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); } } sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); // 4.2 遍历currentRegistryProcessors, 执行postProcessBeanDefinitionRegistry方法 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear. // 5.最后, 调用所有剩下的BeanDefinitionRegistryPostProcessors boolean reiterate = true; while (reiterate) { reiterate = false; // 5.1 找出所有实现BeanDefinitionRegistryPostProcessor接口的类 postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { // 5.2 跳过已经执行过的 if (!processedBeans.contains(ppName)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); // 5.3 如果有BeanDefinitionRegistryPostProcessor被执行, 则有可能会产生新的BeanDefinitionRegistryPostProcessor, // 因此这边将reiterate赋值为true, 代表需要再循环查找一次 reiterate = true; } } sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); // 5.4 遍历currentRegistryProcessors, 执行postProcessBeanDefinitionRegistry方法 invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); } // Now, invoke the postProcessBeanFactory callback of all processors handled so far. // 6.调用所有BeanDefinitionRegistryPostProcessor的postProcessBeanFactory方法(BeanDefinitionRegistryPostProcessor继承自BeanFactoryPostProcessor) //执行BeanFactoryPostProcessor的回调,前面不是吗? //前面执行的BeanFactoryPostProcessor的子类BeanDefinitionRegistryPostProcessor的回调 //这是执行的是BeanFactoryPostProcessor postProcessBeanFactory //ConfuguratuonClassPpostProcssor invokeBeanFactoryPostProcessors(registryProcessors, beanFactory); // 7.最后, 调用入参beanFactoryPostProcessors中的普通BeanFactoryPostProcessor的postProcessBeanFactory方法 //自定义BeanFactoryPostProcessor invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); } else { // Invoke factory processors registered with the context instance. invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory); } // 到这里 , 入参beanFactoryPostProcessors和容器中的所有BeanDefinitionRegistryPostProcessor已经全部处理完毕, // 下面开始处理容器中的所有BeanFactoryPostProcessor // Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let the bean factory post-processors apply to them! // 8.找出所有实现BeanFactoryPostProcessor接口的类 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的beanName List<String> orderedPostProcessorNames = new ArrayList<>(); // 用于存放普通BeanFactoryPostProcessor的beanName List<String> nonOrderedPostProcessorNames = new ArrayList<>(); // 8.1 遍历postProcessorNames, 将BeanFactoryPostProcessor按实现PriorityOrdered、实现Ordered接口、普通三种区分开 for (String ppName : postProcessorNames) { // 8.2 跳过已经执行过的 if (processedBeans.contains(ppName)) { // skip - already processed in first phase above } else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { // 8.3 添加实现了PriorityOrdered接口的BeanFactoryPostProcessor priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)); } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { // 8.4 添加实现了Ordered接口的BeanFactoryPostProcessor的beanName orderedPostProcessorNames.add(ppName); } else { // 8.5 添加剩下的普通BeanFactoryPostProcessor的beanName nonOrderedPostProcessorNames.add(ppName); } } // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered. // 9.调用所有实现PriorityOrdered接口的BeanFactoryPostProcessor // 9.1 对priorityOrderedPostProcessors排序 sortPostProcessors(priorityOrderedPostProcessors, beanFactory); // 9.2 遍历priorityOrderedPostProcessors, 执行postProcessBeanFactory方法 invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory); // Next, invoke the BeanFactoryPostProcessors that implement Ordered. // 10.调用所有实现Ordered接口的BeanFactoryPostProcessor List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(); for (String postProcessorName : orderedPostProcessorNames) { // 10.1 获取postProcessorName对应的bean实例, 添加到orderedPostProcessors, 准备执行 orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } // 10.2 对orderedPostProcessors排序 sortPostProcessors(orderedPostProcessors, beanFactory); // 10.3 遍历orderedPostProcessors, 执行postProcessBeanFactory方法 invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory); // Finally, invoke all other BeanFactoryPostProcessors. // 11.调用所有剩下的BeanFactoryPostProcessor List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(); for (String postProcessorName : nonOrderedPostProcessorNames) { // 11.1 获取postProcessorName对应的bean实例, 添加到nonOrderedPostProcessors, 准备执行 nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } // 11.2 遍历nonOrderedPostProcessors, 执行postProcessBeanFactory方法 invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory); // Clear cached merged bean definitions since the post-processors might have // modified the original metadata, e.g. replacing placeholders in values... // 12.清除元数据缓存(mergedBeanDefinitions、allBeanNamesByType、singletonBeanNamesByType), // 因为后处理器可能已经修改了原始元数据,例如, 替换值中的占位符... beanFactory.clearMetadataCache(); }
这个方法是个非常神奇的方法, 功能异常强大, 也异常的复杂.
这里处理了两个 BeanFactory 的后置处理器, 都是前面注册的
1. 这里处理了, 前面注册的一个非常重要的后置处理器: ConfigurationClassPostProcessor (通过调试可以很直观的看到)
org.springframework.context.annotation.internalConfigurationAnnotationProcessor --> ConfigurationClassPostProcessor
2. EventListenerMethodProcessor, 他提供了 @EventListener 的支持
org.springframework.context.event.internalEventListenerProcessor --> EventListenerMethodProcessor
只有通过阅读 ConfigurationClassPostProcessor的源码之后, 才知道这里是多么的复杂和强大.