• Spring IOC源码:invokeBeanFactoryPostProcessors 后置处理器详解


    Spring源码系列:

    Spring IOC源码:简单易懂的Spring IOC 思路介绍
    Spring IOC源码:核心流程介绍
    Spring IOC源码:ApplicationContext刷新前准备工作
    Spring IOC源码:obtainFreshBeanFactory 详解(上)
    Spring IOC源码:obtainFreshBeanFactory 详解(中)
    Spring IOC源码:obtainFreshBeanFactory 详解(下)
    Spring IOC源码:<context:component-scan>源码详解
    Spring IOC源码:invokeBeanFactoryPostProcessors 后置处理器详解
    Spring IOC源码:registerBeanPostProcessors 详解
    Spring IOC源码:实例化前的准备工作
    Spring IOC源码:finishBeanFactoryInitialization详解
    Spring IoC源码:getBean 详解
    Spring IoC源码:createBean( 上)
    Spring IoC源码:createBean( 中)
    Spring IoC源码:createBean( 下)
    Spring IoC源码:finishRefresh 完成刷新详解

    前言

    前面篇幅介绍了Bean配置的解析过程,包括注解、xml配置文件的解析。下面进入refresh方法中另一个重要的节点,即BeanFactoryPostProcessor的注册及其执行过程。

    正文

    进入refresh,前面篇幅已经介绍了obtainFreshBeanFactory(),接下来进入prepareBeanFactory(beanFactory);

    public void refresh() throws BeansException, IllegalStateException {
    		synchronized (this.startupShutdownMonitor) {
    			// 容器刷新前准备工作
    			prepareRefresh();
    
    			// Tell the subclass to refresh the internal bean factory.
    			//创建Bean工厂,解析配置
    			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
    
    			// bean工厂准备工作
    			prepareBeanFactory(beanFactory);
    
    			try {
    				//拓展接口,留给子类进行实现拓展
    				postProcessBeanFactory(beanFactory);
    
    				// 注册执行,BeanFactoryPostProcessor
    				invokeBeanFactoryPostProcessors(beanFactory);
    
    				// 注册创建BeanPostProcessor
    				registerBeanPostProcessors(beanFactory);
    
    				// 这个方法主要作用就是使用国际化,定制不同的消息文本,比如定义了一个Person的Bean,它有name属性,我们需要在不同的国家展示对应国家所在语言名称,这时候就可以使用国际化了。
    				initMessageSource();
    
    				// Initialize event multicaster for this context.
    				//初始化应用事件广播器
    				initApplicationEventMulticaster();
    
    				// Initialize other special beans in specific context subclasses.
    				//拓展接口,留给子类进行实现拓展,springboot就对该方法进行了处理
    				onRefresh();
    
    				// Check for listener beans and register them.
    				//将内部的、以及我们自定义的监听器添加到缓存中,为后续逻辑处理做准备。还有添加事件源到缓存中。
    				registerListeners();
    
    				// Instantiate all remaining (non-lazy-init) singletons.
    				//实例化剩下非懒加载的Bean
    				finishBeanFactoryInitialization(beanFactory);
    
    				// Last step: publish corresponding event.
    				//使用应用事件广播器推送上下文刷新完毕事件(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();
    			}
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71

    prepareBeanFactory(beanFactory),见方法1详解

    postProcessBeanFactory(beanFactory),见方法2详解

    invokeBeanFactoryPostProcessors(beanFactory),见方法3详解

    方法1:prepareBeanFactory

    	protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    		// 为当前Bean工厂设置类加载器
    		beanFactory.setBeanClassLoader(getClassLoader());
    		beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
    		beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
    
    		//添加BeanPostProcessor后置处理器
    		beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
    		//跳过以下6个属性的自动注入
    		//因为在ApplicationContextAwareProcessor后置处理器中通过setter注入
    		beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
    		beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
    		beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
    		beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
    		beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
    		beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
    
    	  /**
    		 * 在Spring自动装配的时候如果一个接口有多个实现类,并且都已经放到IOC中去了,
    		 * 那么自动装配的时候就会出异常,因为spring不知道把哪个实现类注入进去,
    		 * 但是如果我们自定义一个类,然后实现BeanFactoryPostProcessor接口
    		 * 在该阶段调用这个方法,如果哪个地方要自动注入这个类型的对象的话,那么就注入进去我们指定的对象
    	  */
    
    		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));
    
    		//如果当前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()));
    		}
    
    		// 将以下Bean添加到一级缓存中
    		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());
    		}
    	}
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53

    方法2:postProcessBeanFactory

    	protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    	}
    
    • 1
    • 2

    这个方法没有实现内容,为拓展接口,留给子类实现。我们可以看到这个方法的参数为bean工厂对象,意味着我们可以往该工厂中添加后置处理器或者添加忽略类,在后续注入中跳过。也可以往三级缓存中添加信息。

    例如:

    	protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    		if (this.servletContext != null) {
    			beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext));
    			beanFactory.ignoreDependencyInterface(ServletContextAware.class);
    		}
    		WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext);
    		WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext);
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    方法3:invokeBeanFactoryPostProcessors

    	protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    		//执行BeanFactoryPostProcessors
    		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()));
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    getBeanFactoryPostProcessors(),见方法4详解
    invokeBeanFactoryPostProcessors(),见方法5详解

    方法4:getBeanFactoryPostProcessors()

    	public List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors() {
    		return this.beanFactoryPostProcessors;
    	}
    
    • 1
    • 2
    • 3

    我们看到这里是直接返回当前上下文的beanFactoryPostProcessors集合,默认情况下这里是空的,那我们如何自定义一个后置处理器并且往该集合存放呢?我们可以自定义ClassPathXmlApplicationContext子类,重写上述介绍的方法2postProcessBeanFactory方法,并往beanFactoryPostProcessors添加自定义后置处理器;

    创建工厂后置处理器

    package controller.main;
    
    import org.springframework.beans.BeansException;
    import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
    import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
    
    public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    	@Override
    	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    		Object teacher = beanFactory.getBean("teacher");
    		System.out.println(teacher);
    	}
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    自定义ClassPathXmlApplicationContext子类,并添加后置处理器

    package controller.main;
    
    import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
    import org.springframework.beans.factory.support.DefaultListableBeanFactory;
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class MyClassPathApplicationContext extends ClassPathXmlApplicationContext {
    
    	public MyClassPathApplicationContext(String path){
    		super(path);
    	}
    
    	@Override
    	protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    		this.addBeanFactoryPostProcessor(new MyBeanFactoryPostProcessor());
    	}
    }
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    启动测试

    public class PersonTest {
    	public static void main(String[] args) {
    		MyClassPathApplicationContext applicationContext=new MyClassPathApplicationContext("application-scan.xml");
    		StudentDao zdcDomain = (StudentDao) applicationContext.getBean("studentDao");
    		System.out.println(zdcDomain);
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    在这里插入图片描述

    方法5:invokeBeanFactoryPostProcessors

    public static void invokeBeanFactoryPostProcessors(
    			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
    
    		// 存放BeanDefinitionRegistryPostProcessor类型已经执行过其postProcessBeanDefinitionRegistry方法的beanName
    		Set<String> processedBeans = new HashSet<>();
    
    		if (beanFactory instanceof BeanDefinitionRegistry) {
    			
    			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
    			//存放普通的PostProcessors,就是非BeanDefinitionRegistryPostProcessor类型的
    			List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
    			//存放BeanDefinitionRegistryPostProcessor类型的处理器
    			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
    			//遍历上下文中的beanFactoryPostProcessors集合,也就是我们在方法4中设置进去的后置处理器集合
    			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
    				
    				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
    					BeanDefinitionRegistryPostProcessor registryProcessor =
    							(BeanDefinitionRegistryPostProcessor) postProcessor;
    					//执行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.
    			//存放当前节点的集合
    			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
    
    			// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
    			//获取我们bean工厂中类型为BeanDefinitionRegistryPostProcessor的beanName
    			String[] postProcessorNames =
    					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
    			for (String ppName : postProcessorNames) {
    				//判断是否实现了PriorityOrdered接口
    				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
    					//添加到当前节点中
    					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
    					//添加名称到集合中
    					processedBeans.add(ppName);
    				}
    			}
    			//排序
    			sortPostProcessors(currentRegistryProcessors, beanFactory);
    			//将当前节点的后置处理器添加到registryProcessors集合中
    			registryProcessors.addAll(currentRegistryProcessors);
    			//执行postProcessBeanDefinitionRegistry方法
    			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
    			//清空当前节点集合
    			currentRegistryProcessors.clear();
    
    			// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
    			//重新获取类型为BeanDefinitionRegistryPostProcessor的beanName,为什么这里要重新获取一次,
    			//我理解就是上面执行了post ProcessBeanDefinitionRegistry方法,可能存在往bean工厂中添加类型为
    			//BeanDefinitionRegistryPostProcessor的BeanDefinition封装对象,所以这里算是更新数据吧
    			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
    			for (String ppName : postProcessorNames) {
    				//判断执行过的processedBeans集合中不存在,并且实现了Ordered接口
    				if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
    					//添加到当前节点中
    					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
    					//添加名称到已执行集合中
    					processedBeans.add(ppName);
    				}
    			}
    			//排序
    			sortPostProcessors(currentRegistryProcessors, beanFactory);
    			//将当前节点的后置处理器添加到registryProcessors集合中
    			registryProcessors.addAll(currentRegistryProcessors);
    			//执行postProcessBeanDefinitionRegistry方法
    			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);		
    			//清空当前节点集合
    			currentRegistryProcessors.clear();
    
    			// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
    			boolean reiterate = true;
    			while (reiterate) {
    				reiterate = false;
    				//获取类型BeanDefinitionRegistryPostProcessor的beanName
    				postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
    				//这里主要获取没有实现PriorityOrdered和Order类的后置处理器
    				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();
    			}
    
    			// 执行postProcessBeanFactory(beanFactory)方法
    			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
    			invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
    		}
    
    		else {
    			// Invoke factory processors registered with the context instance.
    			//没有实现BeanDefinitionRegistry接口的,直接执行postProcessBeanFactory(beanFactory)方法
    			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!
    		String[] postProcessorNames =
    				beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
    
    		// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
    		// Ordered, and the rest.
    		//存放实现了PriorityOrdered接口的后置处理器
    		List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
    		//存放实现了Ordered接口的BeanName
    		List<String> orderedPostProcessorNames = new ArrayList<>();
    		//存放没有实现了PriorityOrdered和Ordered接口的BeanName
    		List<String> nonOrderedPostProcessorNames = new ArrayList<>();
    		for (String ppName : postProcessorNames) {
    			//跳过之前已经执行过的,也就是BeanDefinitionRegistryPostProcessor类型的后置处理器
    			if (processedBeans.contains(ppName)) {
    				// skip - already processed in first phase above
    			}
    			//实现PriorityOrdered,添加至集合中
    			else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
    				//getBean方法会从三级缓存获取,取不到会提交调用实例化初始化步骤
    				priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
    			}
    			//实现Ordered,添加至集合中
    			else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
    				orderedPostProcessorNames.add(ppName);
    			}
    			//添加至集合中
    			else {
    				nonOrderedPostProcessorNames.add(ppName);
    			}
    		}
    
    		// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
    		//排序并调用postProcessBeanFactory(beanFactory)方法
    		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    		invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
    
    		// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
    		//遍历从bean工厂中获取实例对象,取不到进行实例化操作
    		List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
    		for (String postProcessorName : orderedPostProcessorNames) {
    			orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    		}
    		//排序并调用postProcessBeanFactory(beanFactory)方法
    		sortPostProcessors(orderedPostProcessors, beanFactory);
    		invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
    
    		// Finally, invoke all other BeanFactoryPostProcessors.
    		遍历从bean工厂中获取实例对象,取不到进行实例化操作
    		List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
    		for (String postProcessorName : nonOrderedPostProcessorNames) {
    			nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    		}
    		//排序并调用postProcessBeanFactory(beanFactory)方法
    		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();
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171
    • 172
    • 173
    • 174

    sortPostProcessors(),见方法6详解

    方法6:sortPostProcessors

    	private static void sortPostProcessors(List<?> postProcessors, ConfigurableListableBeanFactory beanFactory) {
    		Comparator<Object> comparatorToUse = null;
    		if (beanFactory instanceof DefaultListableBeanFactory) {
    			comparatorToUse = ((DefaultListableBeanFactory) beanFactory).getDependencyComparator();
    		}
    		if (comparatorToUse == null) {
    			comparatorToUse = OrderComparator.INSTANCE;
    		}
    		postProcessors.sort(comparatorToUse);
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    这里我们的比较器为AnnotationAwareOrderComparator,在前面文章中《<context:component-scan>源码详解》中的方法19有设置该比较器。
    在这里插入图片描述
    比较器部分代码如下:

    	private int doCompare(Object o1, Object o2, OrderSourceProvider sourceProvider) {
    		// 判断o1是否实现了PriorityOrdered接口
    		boolean p1 = (o1 instanceof PriorityOrdered);
    		// 判断o2是否实现了PriorityOrdered接口
    		boolean p2 = (o2 instanceof PriorityOrdered);
    		// 1.如果o1实现了PriorityOrdered接口, 而o2没有, 则o1排前面
    		if (p1 && !p2) {
    			return -1;
    		}
    		// 2.如果o2实现了PriorityOrdered接口, 而o1没有, 则o2排前面
    		else if (p2 && !p1) {
    			return 1;
    		}
    
    		// 3.如果o1和o2都实现(都没实现)PriorityOrdered接口
    		// Direct evaluation instead of Integer.compareTo to avoid unnecessary object creation.
    		// 拿到o1的order值, 如果没实现Ordered接口, 值为Ordered.LOWEST_PRECEDENCE
    		int i1 = getOrder(o1, sourceProvider);
    		// 拿到o2的order值, 如果没实现Ordered接口, 值为Ordered.LOWEST_PRECEDENCE
    		int i2 = getOrder(o2, sourceProvider);
    		// 4.通过order值(order值越小, 优先级越高)排序
    		return (i1 < i2) ? -1 : (i1 > i2) ? 1 : 0;
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    比较器的逻辑很简单,实现 PriorityOrdered 接口的优先级最高,如果两个对象都实现(都没实现)PriorityOrdered 接口,则根据 order 值(实现 Ordered 接口时,需要实现 getOrder() 方法,返回 order 值)来进行比较,order 值越小,优先级越高。

    总结

    本篇文章讲解了refresh方法中的prepareBeanFactory、postProcessBeanFactory、invokeBeanFactoryPostProcessors这三个方法。prepareBeanFactory其实就是BeanFactory工厂做一些准备工作,忽略某些值不被其它类所注入,以及添加一些后置处理器等。postProcessBeanFactory方法为拓展接口,提供子类进行拓展实现,我们也讲解了案例,通过编写实现ClassPathXmlApplicationContext子类重写该方法,并往该方法中添加后置处理器。invokeBeanFactoryPostProcessors方法主要是执行后置处理,主要分为两种类型的BeanFactoryPostProcessor,实现接口BeanDefinitionRegistryPostProcessor的和直接实现BeanFactoryPostProcessor接口的,BeanDefinitionRegistryPostProcessor是BeanFactoryPostProcessor的接口实现类。

    梳理一下invokeBeanFactoryPostProcessors方法:
    1.整个 invokeBeanFactoryPostProcessors 方法围绕两个接口,BeanDefinitionRegistryPostProcessor 和 BeanFactoryPostProcessor,其中 BeanDefinitionRegistryPostProcessor 继承了 BeanFactoryPostProcessor 。BeanDefinitionRegistryPostProcessor 主要用来在常规 BeanFactoryPostProcessor 检测开始之前注册其他 Bean 定义,说的简单点,就是 BeanDefinitionRegistryPostProcessor 具有更高的优先级,执行顺序在 BeanFactoryPostProcessor 之前。

    2.整个 invokeBeanFactoryPostProcessors 方法操作了 3 种 bean 对象:
    入参beanFactoryPostProcessors集合:
    这个我们在方法4中有讲解过,主要取的是当前上下文对象,我们可以通过自定义上下文,并往该集合中添加后置处理器。

    BeanDefinitionRegistryPostProcessor 接口实现类:
    实现了 BeanDefinitionRegistryPostProcessor 接口,并且注册到 Spring IoC容器中。

    常规 BeanFactoryPostProcessor 接口实现类:
    实现了 BeanFactoryPostProcessor 接口,并且注册到 Spring IoC容器中。

    3.该方法中的排序还引用了两个重要的接口PriorityOrdered 和 Ordered,其中 PriorityOrdered 继承了 Ordered,并且 PriorityOrdered 的优先级要高于 Ordered。实现 Ordered 接口需要重写 getOrder 方法,返回一个用于排序的 order 值,order 值的范围为 Integer.MIN_VALUE ~ Integer.MAX_VALUE,order 值越小优先级越高,Integer.MIN_VALUE 拥有最高优先级,而 Integer.MAX_VALUE 则对应的拥有最低优先级。

    4.BeanFactoryPostProcessor中的优先级执行顺序如下:

    第一优先级:上下文beanFactoryPostProcessors集合中的 BeanDefinitionRegistryPostProcessor,会先调用其 postProcessBeanDefinitionRegistry 方法。
    第二优先级:beanFactory工厂中的bean,也就是我们配置文件或者注解所配置的Bean,实现了BeanDefinitionRegistryPostProcessor 、 PriorityOrdered 接口,会调用 postProcessBeanDefinitionRegistry 方法。
    第三优先级:beanFactory工厂中的bean,实现BeanDefinitionRegistryPostProcessor 、Ordered 接口,会调用 postProcessBeanDefinitionRegistry 方法。
    第四优先级:没有实现PriorityOrdered 或Ordered 接口的 BeanDefinitionRegistryPostProcessor 接口实现类,调用 postProcessBeanDefinitionRegistry 方法。
    第五优先级:所有 BeanDefinitionRegistryPostProcessor 接口实现类,调用 postProcessBeanFactory 方法。
    第六优先级:入参 beanFactoryPostProcessors 集合中的常规 BeanFactoryPostProcessor,调用 postProcessBeanFactory 方法。
    第七优先级:beanFactory工厂中的bean,常规 BeanFactoryPostProcessor 接口实现类,并且实现了 PriorityOrdered 接口,调用 postProcessBeanFactory 方法。
    第八优先级:beanFactory工厂中的bean,常规 BeanFactoryPostProcessor 接口实现类,并且实现了 Ordered 接口,调用 postProcessBeanFactory 方法。
    第九优先级:没有实现PriorityOrdered 或Ordered 接口的 BeanFactoryPostProcessor 接口实现类,调用 postProcessBeanFactory 方法。

  • 相关阅读:
    从零开始的C++(四)
    day17-高速缓冲区的管理机制
    Web APIs Web APIs第六天
    SpringCloud系列(7)--Eureka服务端的安装与配置
    21、前端开发:CSS知识总结——transform变形属性
    网络基础(1)
    ModStart - 模块化开发框架的引领者
    4-11 Isomorphic
    万门大学倒闭了,童哲连夜跑路了
    21天经典算法之折半插入排序
  • 原文地址:https://blog.csdn.net/weixin_45031612/article/details/127892495