4. postProcessBeanFactory(beanFactory)
- 本方法是用来给子类实现拓展的
5. invokeBeanFactoryPostProcessors(beanFactory) 执行 BeanFactory 后置处理器
1. 获取所有的 BeanDefinitionRegistryPostProcessor 2. 先执行实现了 PriorityOrdered 优先级接口BeanDefinitionRegistryPostProcessor 3. 再执行实现了 Ordered 顺序接口的 BeanDefinitionRegistryPostProcessor 4. 最后一步执行没有实现优先级接口或者顺序的接口的 BeanDefinitionRegistryPostProcessors 5. 获取所有的 BeanFactoryPostProcessor 6. 执行实现了 PriorityOrdered 优先级接口的 BeanFactoryPostProcessor 7. 执行实现了 Ordered 顺序接口的 BeanFactoryPostProcessor 8. 执行没有实现优先级接口或者顺序的接口的 BeanFactoryPostProcessor
/** * 执行 BeanFactoryPostProcessors 的方法 * @param beanFactory * @param beanFactoryPostProcessors */ public static void invokeBeanFactoryPostProcessors( ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) { // Invoke BeanDefinitionRegistryPostProcessors first, if any. Set<String> processedBeans = new HashSet<>(); if (beanFactory instanceof BeanDefinitionRegistry) { BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory; List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>(); List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>(); for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) { if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) { BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor; 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. List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>(); // 1. 获取所有的 BeanDefinitionRegistryPostProcessor String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); // 2. 先执行实现了 PriorityOrdered 优先级接口的 BeanDefinitionRegistryPostProcessor、 // postProcessor.postProcessBeanDefinitionRegistry(registry); for (String ppName : postProcessorNames) { if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); } } sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); // 3. 再执行实现了 Ordered 顺序接口的 BeanDefinitionRegistryPostProcessor postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { 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); invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); // 4. 最后一步执行没有实现优先级接口或者顺序的接口的 BeanDefinitionRegistryPostProcessors boolean reiterate = 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. invokeBeanFactoryPostProcessors(registryProcessors, beanFactory); invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); } else { // Invoke factory processors registered with the context instance. invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory); } // 再来执行 BeanFactoryPostProcess 的方法 String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false); // Separate between BeanFactoryPostProcessors that implement PriorityOrdered, // Ordered, and the rest. List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>(); List<String> orderedPostProcessorNames = new ArrayList<>(); List<String> nonOrderedPostProcessorNames = new ArrayList<>(); for (String ppName : postProcessorNames) { if (processedBeans.contains(ppName)) { // skip - already processed in first phase above } else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)); } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { nonOrderedPostProcessorNames.add(ppName); } } // 2. 先执行实现了 PriorityOrdered 优先级接口的 BeanFactoryPostProcessor、 // postProcessor.postProcessBeanFactory(beanFactory); sortPostProcessors(priorityOrderedPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory); // 3. 再执行实现了 Ordered 顺序接口的 BeanFactoryPostProcessor List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(); for (String postProcessorName : orderedPostProcessorNames) { orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } sortPostProcessors(orderedPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory); // 4. 最后一步执行没有实现优先级接口或者顺序的接口的 BeanFactoryPostProcessor 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(); }
6. registerBeanPostProcessors(beanFactory) 注册 Bean 后置处理器
- BeanPostProcessor 进行排序,排序分为三类:PriorityOrdered, Ordered,non 默认,MergedBeanDefinitionPostProcessor
- 排序后以此存入到 priorityOrderedPostProcessors, orderedPostProcessors, nonOrderedPostProcessors,internalPostProcessors 集合中
- 这里的优先级是:
PriorityOrdered -> Ordered -> 无 -> MergedBeanDefinitionPostProcessor
注意:如果是实现了多个接口那么则按照最低优先级作为排序的顺序
- 按照顺序注册后置处理器
- 最后注册一个 ApplicationListenerDetector 到容器中
public static void registerBeanPostProcessors( ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) { // 1. 获取所有的 BeanPostProcessor; 后置处理器都可以通过 PriorityOrdered、Ordered 接口来指定优先级 String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false); // 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. int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length; beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount)); // Separate between BeanPostProcessors that implement PriorityOrdered, // Ordered, and the rest. List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>(); List<BeanPostProcessor> internalPostProcessors = new ArrayList<>(); List<String> orderedPostProcessorNames = new ArrayList<>(); List<String> nonOrderedPostProcessorNames = new ArrayList<>(); for (String ppName : postProcessorNames) { if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {// PriorityOrdered @Order @Priority BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); priorityOrderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { nonOrderedPostProcessorNames.add(ppName); } } // 2. 先注册 PriorityOrdered 优先级接口的 BeanPostProcessors sortPostProcessors(priorityOrderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); // 3. 再注册 Order 优先级接口的 BeanPostProcessors 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); // 4. 最后注册没有任何优先级接口的 BeanPostProcessors 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); // 5. 最终注册 MergedBeanDefinitionPostProcessor sortPostProcessors(internalPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, internalPostProcessors); // Re-register post-processor for detecting inner beans as ApplicationListeners, // moving it to the end of the processor chain (for picking up proxies etc). // 6. 注册一个 ApplicationListenerDetector,来在 Bean 创建完成后检查是否是 ApplicationListener 如果是 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext)); }
7. initMessageSource() 初始化 MessageSource 组件
8. initApplicationEventMulticaster() 初始化事件派发器
protected void initApplicationEventMulticaster() { // 1. 获取 BeanFactory ConfigurableListableBeanFactory beanFactory = getBeanFactory(); // 2. 从 BeanFactory 中获取 applicationEventMulticaster 的 applicationEventMulticaster if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) { this.applicationEventMulticaster = beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class); if (logger.isTraceEnabled()) { logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]"); } } else { // 3. 如果上一步没有配置:创建一个 SimpleApplicationEventMulticaster this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); // 4. 将创建的 ApplicationEventMulticaster 添加到 BeanFactory 中,以后其他组件直接自动注入即可 beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster); if (logger.isTraceEnabled()) { logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " + "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]"); } } }
9. onRefresh() 预留方法,用于自定义实现重写实现特殊 Bean 的处理
10. registerListeners() 注册监听器
protected void registerListeners() { // Register statically specified listeners first. // 1. 从容器中拿到所有的 ApplicationListener 组件 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! // 2. 每个监听器添加到事件派发器中 // getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); // 到这一步因为 FactoryBean 还没有调用 getObject() 方法生成 Bean 对象, 所以这里要根据类型查找一下 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... // 3. 派发之前步骤产生的事件 Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents; this.earlyApplicationEvents = null; if (earlyEventsToProcess != null) { for (ApplicationEvent earlyEvent : earlyEventsToProcess) { getApplicationEventMulticaster().multicastEvent(earlyEvent); } } }
11. finishBeanFactoryInitialization(beanFactory) 刷新前的预处理工作
1. 初始化单实例 Bean 2. 对属性进行赋值 和部分将在 Bean 的初始化,依赖注入,循环依赖中拓展
12. finishRefresh() 执行 Bean 的生命周期启动和时间发布
protected void finishRefresh() { // Clear context-level resource caches (such as ASM metadata from scanning). clearResourceCaches(); // Initialize lifecycle processor for this context. // 2. initLifecycleProcessor(); 初始化和生命周期有关的后置处理器 // 默认从容器中找是否有 lifecycleProcessor 的组件 【LifecycleProcessor】,如果没有就使用默认的生命周期组件 // new DefaultLifecycleProcessor(); // 加入容器中方便使用 // LifecycleProcessor 写一个实现类 LifecycleProcessor 的实现类,可以在BeanFactory 的方法进行调用 // void onRefresh(); // void onClose(); initLifecycleProcessor(); // Propagate refresh to lifecycle processor first. // 3. 拿到生命周期处理器(BeanFactory)回调 onRefresh()), getLifecycleProcessor().onRefresh(); // Publish the final event. // 4. publishEvent(new ContextRefreshedEvent(this)); 发布容器刷新完成事件 publishEvent(new ContextRefreshedEvent(this)); // Participate in LiveBeansView MBean, if active. // 5. LiveBeansView.registerApplicationContext(this); LiveBeansView.registerApplicationContext(this); }