spring注解驱动系列-- BeanPostProcessor与BeanFactoryPostProcessor

一、BeanPostProcessor与BeanFactoryPostProcessor的定义

一、BeanPostProcessor

bean后置处理器,bean创建对象初始化前后进行拦截工作的

二、BeanFactoryPostProcessor 

beanFactory的后置处理器,在BeanFactory标准初始化之后调用,来定制和修改BeanFactory的内容,所有的bean定义信息已经保存加载到beanFactory,但是bean的实例还未创建。BeanFactoryPostProcessor是BeanFactory的一个钩子接口

二、原理 

一、测试demo

@Component
public class MyBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        System.out.println("MyBeanFactoryPostProcessor...postProcessBeanFactory...");
        int count = beanFactory.getBeanDefinitionCount();
        String[] names = beanFactory.getBeanDefinitionNames();
        System.out.println("当前BeanFactory中有"+count+" 个Bean");
        System.out.println(Arrays.asList(names));
    }
}



@ComponentScan("com.spring.annotate.beans")
@Configuration
public class BeansFactoryConfig {
    @Bean
    public Blue blue(){
        return new Blue();
    }
}




    @Test
    void contextLoads() {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeansFactoryConfig.class);
        applicationContext.close();
    }

结果:

二、原理

一、通过idea工具可以查看到spring源码接口,发现它还有一个子接口BeanDefinitionRegistryPostProcessor

二、BeanFactoryPostProcessor接口

@FunctionalInterface
public interface BeanFactoryPostProcessor {

    /**
     * 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
     */
    void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;

}

从源码上看,这个接口只有一个方法,也就是说spring是通过这个方法对BeanFactory进行增强的

三、BeanDefinitionRegistryPostProcessor接口

public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {

    /**
     * Modify the application context's internal bean definition registry after its
     * standard initialization. All regular bean definitions will have been loaded,
     * but no beans will have been instantiated yet. This allows for adding further
     * bean definitions before the next post-processing phase kicks in.
     * @param registry the bean definition registry used by the application context
     * @throws org.springframework.beans.BeansException in case of errors
     */
    void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;

}
 

此接口也只有一个方法,是为了Bean的注册而生,BeanDefinitionRegistry 是BeanDefinition的注册器,而注册Bean的过程是将满足Bean条件的类解析为BeanDefinition对象然后注册到BeanDefinition注册器中。

总结:

BeanFactoryPostProcessor和BeanDefinitionRegistryPostProcessor都是扩展Bean的加载方式,当我们需要自定义自己的Bean加载方式时实现BeanDefinitionRegistryPostProcessor接口即可。@Configuration注解的实现就是基于BeanDefinitionRegistryPostProcessor接口完成

四、BeanFactoryPostProcessor 原理

首先我们需要清楚,AbstractApplicationContext类中refresh()是spring加载Bean的核心方法,大部分的处理逻辑都是在这个方法中完成。执行时机是:所有的bean定义已经保存加载到beanFactory,但是bean的实例还未创建

@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

			// Prepare this context for refreshing.
			/**
			 * 准备上下文刷新工作,如设置初始值
			 */
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			/**
			 * 告诉子类刷新内部beanFactory,返回Bean工厂
			 */
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			/**
			 * 准备beanFactory,以便于上下文中使用
			 */
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				/**
				 * 允许在上下文子类中对bean工厂进行后处理。
				 */
				postProcessBeanFactory(beanFactory);

				/**
				 * 开启处理PostProcessors步骤器
				 */
				StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
				// Invoke factory processors registered as beans in the context.
				/**
				 * 调用BeanFactory的后置处理器
				 */
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				/**
				 *
				 * 注册拦截bean创建的bean处理器
				 */
				registerBeanPostProcessors(beanFactory);
				/**
				 * 处理PostProcessors步骤器
				 */
				beanPostProcess.end();

				// Initialize message source for this context.
				/**
				 * 初始化MessageSource
				 */
				initMessageSource();

				// Initialize event multicaster for this context.
				/**
				 * 初始化Application监听器的管理Bean(ApplicationEventMulticaster)
				 */
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				/**
				 * 模板模式,刷新Bean的操作,由子类实现具体逻辑
				 */
				onRefresh();

				// Check for listener beans and register them.
				/**
				 * 检查和注册监听器
				 */
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				/**
				 * 实例化所有(非惰性初始化)单例
				 */
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				/**
				 * 发布相应的事件
				 */
				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();
				contextRefresh.end();
			}
		}
	}

一、 ioc容器创建对象

二、invokeBeanFactoryPostProcessors(beanFactory);

	protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
		/**
		 * 执行BeanFactoryPostProcessor,是该方法的处理核心
		 */
		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 (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
			beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
			beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
		}
	}

  三、PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors())方法

public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
		Set<String> processedBeans = new HashSet<>();

		/**
		 * 首先调用BeanDefinitionRegistryPostProcessors(如果有)。
		 */
		if (beanFactory instanceof BeanDefinitionRegistry) {
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
			/**
			 * 用于存放BeanFactoryPostProcessor的对象
			 */
			List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
			/**
			 * 用户存放BeanDefinitionRegistryPostProcessor对象
			 */
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();


			/********************************* 下面处理BeanDefinitionRegistryPostProcessor逻辑 *************************************/


			/**
			 * 遍历最原始的BeanFactoryPostProcessor列表,找出BeanDefinitionRegistryPostProcessor和 BeanFactoryPostProcessor
			 * BeanDefinitionRegistryPostProcessor是BeanFactoryPostProcessor的子接口
			 */
			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					BeanDefinitionRegistryPostProcessor registryProcessor =
							(BeanDefinitionRegistryPostProcessor) postProcessor;
					/**
					 * 执行BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry
					 */
					registryProcessor.postProcessBeanDefinitionRegistry(registry);
					registryProcessors.add(registryProcessor);
				}
				else {
					regularPostProcessors.add(postProcessor);
				}
			}

			/**
			 * 定义当前找到的BeanDefinitionRegistryPostProcessor临时存储
			 */
			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

			// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
			// 首先,调用实现PriorityOrdered的BeanDefinitionRegistryPostProcessor。
			String[] postProcessorNames =
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			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, beanFactory.getApplicationStartup());
			currentRegistryProcessors.clear();

			// 接下来,调用实现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, beanFactory.getApplicationStartup());
			currentRegistryProcessors.clear();

			// 最后,调用所有其他BeanDefinitionRegistryPostProcessor,直到不再出现其他BeanDefinitionRegistryPostProcessor。
			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, beanFactory.getApplicationStartup());
				currentRegistryProcessors.clear();
			}

			/**
			 * 批量执行BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry
			 */
			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
			/**
			 * 批量执行BeanFactoryPostProcessor(最开始的BeanFactoryPostProcessor)
			 */
			invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
		}

		else {
			// Invoke factory processors registered with the context instance.
			invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
		}

		/********************************* 下面处理BeanFactoryPostProcessor逻辑(可能执行上面步骤产生新的BeanFactoryPostProcessor),执行逻辑和BeanDefinitionRegistryPostProcessor一致 *************************************/

		// 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.
		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);
			}
		}

		// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

		// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
		List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
		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<>(nonOrderedPostProcessorNames.size());
		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();
	}


	/**
	 * 排序BeanFactoryPostProcessor
	 * @param postProcessors
	 * @param beanFactory
	 */
	private static void sortPostProcessors(List<?> postProcessors, ConfigurableListableBeanFactory beanFactory) {
		// Nothing to sort?
		if (postProcessors.size() <= 1) {
			return;
		}
		Comparator<Object> comparatorToUse = null;
		if (beanFactory instanceof DefaultListableBeanFactory) {
			comparatorToUse = ((DefaultListableBeanFactory) beanFactory).getDependencyComparator();
		}
		if (comparatorToUse == null) {
			comparatorToUse = OrderComparator.INSTANCE;
		}
		postProcessors.sort(comparatorToUse);
	}


	/**
	 * 执行  BeanDefinitionRegistryPostProcessor
	 * @param postProcessors
	 * @param registry
	 * @param applicationStartup
	 */
	private static void invokeBeanDefinitionRegistryPostProcessors(
			Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry, ApplicationStartup applicationStartup) {

		for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
			StartupStep postProcessBeanDefRegistry = applicationStartup.start("spring.context.beandef-registry.post-process")
					.tag("postProcessor", postProcessor::toString);
			postProcessor.postProcessBeanDefinitionRegistry(registry);
			postProcessBeanDefRegistry.end();
		}
	}


	/**
	 * 执行invokeBeanFactoryPostProcessors
	 * @param postProcessors
	 * @param beanFactory
	 */
	private static void invokeBeanFactoryPostProcessors(
			Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) {

		for (BeanFactoryPostProcessor postProcessor : postProcessors) {
			StartupStep postProcessBeanFactory = beanFactory.getApplicationStartup().start("spring.context.bean-factory.post-process")
					.tag("postProcessor", postProcessor::toString);
			postProcessor.postProcessBeanFactory(beanFactory);
			postProcessBeanFactory.end();
		}
	}

	

一、遍历最原始的BeanFactoryPostProcessor,找到BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor,且执行BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry(registry)方法加载Bean。

二、从BeanFactory中寻找BeanDefinitionRegistryPostProcessorPriorityOrdered(最高优先级的排序)类型Bean,排序后执行postProcessBeanDefinitionRegistry(registry)方法加载Bean。

三、从BeanFactory中寻找BeanDefinitionRegistryPostProcessor未被加载的Ordered(排序)类型Bean,排序后执行postProcessBeanDefinitionRegistry(registry)方法加载Bean。

四、从BeanFactory中寻找出未被加载的BeanDefinitionRegistryPostProcessor类型Bean,然后执行postProcessBeanDefinitionRegistry(registry)方法加载Bean,这一步目的就是处理加载新的BeanDefinitionRegistryPostProcessor的Bean。

五、从BeanFactory中寻找BeanFactoryPostProcessorPriorityOrdered(最高优先级的排序)类型Bean,排序后执行postProcessBeanFactory(beanFactory)方法加载Bean。

六、从BeanFactory中寻找BeanFactoryPostProcessor未被加载的Ordered(排序)的类型Bean,排序后执行postProcessBeanFactory(beanFactory)方法加载Bean。

七、从BeanFactory中寻找出未排序BeanFactoryPostProcessor类型Bean,然后执行postProcessBeanFactory(beanFactory)方法加载Bean。

  • priorityOrderedPostProcessors:放置有优先级排序的接口
  • orderedPostProcessorNames:放置有排序的PostProcessorNames
  • nonOrderedPostProcessorNames:放置普通的PostProcessorNames

五、BeanDefinitionRegistryPostProcessor原理

执行时机:在所有bean定义信息将要被加载,bean实例还未创建的,这个是将要被加载,BeanFactoryPostProcessor 这个是已经被加载,所以BeanDefinitionRegistryPostProcessor是在更前执行

1、BeanDefinition:容器中的每一个bean都会有一个对应的BeanDefinition实例,该实例负责保存bean对象的所有必要信息,包括bean对象的class类型、是否是抽象类、构造方法和参数、其它属性等等。

2、BeanDefinitionRegistry:

BeanDefinition是定义bean的,BeanDefinitionRegistry则是bean定义信息的保存中心,也叫注册中心,保存了bean的所有定义,以后BeanFactory就是按照BeanDefinitionRegistry里面保存的每一个bean定义信息创建bean实例。bean是单例还是多例,bean的类型,bean的ID等信息,都是存在BeanDefinitionRegistry里面。

3、BeanDefinitionRegistryPostProcessor:它是Spring框架的一个扩展点,用于对Bean定义的注册过程进行干预和定制。继承BeanFactoryPostProcessor接口,并在其基础上扩展了一个新的方法,即:postProcessBeanDefinitionRegistry()方法。

        用途:在Spring容器初始化时,首先会读取应用程序中的配置文件,并解析出所有的Bean定义,然后将这些Bean定义注册到容器中。在这个过程中,BeanDefinitionRegistryProcessor提供了一种机制,允许开发人员在Bean定义注册之前和之后对Bean定义进行自定义处理,例如添加,修改或删除Bean定义等。
        方法详解:

postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry):该方法在所有Bean定义加载完成之后,Bean实例化之前被调用,允许开发人员对Bean定义进行自定义修改,例如添加,修改或删除Bean定义等。
postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory): 该方法是继承自BeanFactoryPostProcessor接口的方法,用于在BeanFactory完成实例化之后对BeanFactory进行后置处理。

一、ioc容器创建

二、调用refresh()方法,执行到里面的invokeBeanFactoryPostProcessors(beanFactory);方法

进入PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

 三、从容器中获取到所有的BeanDefinitionRegistryPostProcessor组件

	private static void invokeBeanDefinitionRegistryPostProcessors(
			Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry) {

		for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
			postProcessor.postProcessBeanDefinitionRegistry(registry);
		}
	}

1、依次触发所有的postProcessBeanDefinitionRegistry()方法

2、再来触发postProcessBeanFactory()方法,是BeanFactoryPostProcessor里面的方法。 

四、最后到BeanFactoryPostProcessor组件时还会依次触发postProcessBeanFactory()方法 

相关推荐

  1. 深入了解 Spring BeanPostProcessor 的应用

    2024-04-22 00:38:02       51 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-22 00:38:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-22 00:38:02       101 阅读
  3. 在Django里面运行非项目文件

    2024-04-22 00:38:02       82 阅读
  4. Python语言-面向对象

    2024-04-22 00:38:02       91 阅读

热门阅读

  1. 【需求】人像数据集采集

    2024-04-22 00:38:02       31 阅读
  2. Ubuntu 22.04.4 LTS 初始配置(root、ssh)

    2024-04-22 00:38:02       29 阅读
  3. iOS RACScheduler 使用详解

    2024-04-22 00:38:02       36 阅读
  4. 深入浅出理解CSS中的3D变换:踏上立体视觉之旅

    2024-04-22 00:38:02       36 阅读
  5. k8s中修复mongodb启动失败

    2024-04-22 00:38:02       23 阅读
  6. Neural Radiance Fields (NeRF) 和 3D Gaussian Splatting区别

    2024-04-22 00:38:02       33 阅读
  7. 展开说说:Android Fragment完全解析-卷二

    2024-04-22 00:38:02       39 阅读
  8. vue大屏

    2024-04-22 00:38:02       32 阅读
  9. jQuery 选择器有几种,分别是什么

    2024-04-22 00:38:02       33 阅读