Spring源码 - 容器刷新#postProcessBeanFactory()

本文解析了Spring框架中容器刷新过程中的postProcessBeanFactory方法。该方法允许注册特定的BeanPostProcessor等操作,SpringBoot实现了此方法以支持WebApplication的配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring源码 - 容器刷新#postProcessBeanFactory()

Spring版本:Spring 5.3.13-release


# 1、postProcessBeanFactory()

AbstractApplicationContext#postProcessBeanFactory()代码:

	/**
	 * 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 registering special
	 * BeanPostProcessors etc in certain ApplicationContext implementations.
	 * @param beanFactory the bean factory used by the application context
	 */
	protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	}

可以看到,在AbstractApplicationContext#postProcessBeanFactory()中是没有做任何事情的,这是Spring预留给子类进行扩展使用的。模板方法设计模式。

而在SpringBoot中的AnnotationConfigServletWebServerApplicationContext#postProcessBeanFactory()是对这个方法进行了覆盖的:

	/**
	 * override AbstractApplicationContext's postProcessBeanFactory()
	 * template method in Spring IOC refresh()
	 *
	 * @param beanFactory ConfigurableListableBeanFactory
	 */
	@Override
	protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		// 首先注册为 Web Application
		super.postProcessBeanFactory(beanFactory);
		// 扫描指定包下的 Bean 并将其进行注册
		if (this.basePackages != null && this.basePackages.length > 0) {
			this.scanner.scan(this.basePackages);
		}
		// 扫描指定注解的类下的 Bean 并将其注册
		if (!this.annotatedClasses.isEmpty()) {
			this.reader.register(ClassUtils.toClassArray(this.annotatedClasses));
		}
	}

我这里的Spring Boot源码版本为:2.6.2-release

GitHub源码地址https://github.com/kapbc/kapcb-spring-source/tree/master/Spring-Framework-v5.3.13

备注:此文为笔者学习Spring源码的笔记,鉴于本人技术有限,文中难免出现一些错误,感谢大家批评指正。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值