Spring IOC 注解BeanDefinition加载详解

本文详细探讨了Spring框架中,如何通过注解加载BeanDefinition。从示例代码开始,介绍了创建注解配置ApplicationContext的过程,接着分析了触发解析的时机,包括流程图和源码解析,特别关注了ConfigurationClassPostProcessor在解析注解配置中的关键作用。通过对核心源码的跟踪,揭示了@ComponentScan注解的处理逻辑,解析属性并调用doScan方法进行扫描。阅读源码需要耐心和毅力,希望对你理解Spring注解加载有所帮助。

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

一、示例代码


@ComponentScan("org.springframework.examples")
public class AnnotationConfigApplicationContextTest {
   
   

	public static void main(String[] args) {
   
   
		AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(AnnotationConfigApplicationContextTest.class);
	}
}

此处创建了注解配置的ApplicationContext,执行main函数,我们进入到其构造器去看:

/**
	 * Create a new AnnotationConfigApplicationContext, deriving bean definitions
	 * from the given component classes and automatically refreshing the context.
	 * @param componentClasses one or more component classes — for example,
	 * {@link Configuration @Configuration} classes
	 */
	public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
   
   
	   // 调用无参、构造器
		this();
		// 注册我们传进来的配置类
		register(componentClasses);
		// 容器刷新启动
		refresh();
	}
	/**
	 * 无参构造器
	 * Create a new AnnotationConfigApplicationContext that needs to be populated
	 * through {@link #register} calls and then manually {@linkplain #refresh refreshed}.
	 */
	public AnnotationConfigApplicationContext() {
   
   
		// 注注册 BeanDefinition 读取器  主要是Spring内置的一些BeanFactoryPostProcessor
		this.reader = new AnnotatedBeanDefinitionReader(this);
		// 这里的scanner 主要是用作程序员手动调用 scanner放发
		this.scanner = new ClassPathBeanDefinitionScanner(this);
	}

二、前情提要

AnnotationConfigApplicationContext无参构造器中实例化了AnnotatedBeanDefinitionReader

	public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
   
   
		Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
		
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值