Spring Boot自动装配主要源码解析

本文详细介绍了Spring Boot的AutoConfigurationImportSelector类的工作原理,解释了它如何从META-INF/spring.factories加载自动配置类。同时澄清了@AutoConfigurationPackage注解的真实作用,它并不负责扫描并注册Bean,而是用于向容器添加特定包路径的引用,辅助自动配置。理解这些核心概念有助于更好地掌握Spring Boot的自动配置机制。

参考https://zhuanlan.zhihu.com/p/136469945
主要调用关系

  1. AutoConfigurationImportSelector类的selectImports方法返回一个String[],数组内存放需要自动装配的类全名,数组是从SpringFactoriesLoader中加载来的,SpringFactoriesLoader读取的是META-INF/spring.factories
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
	List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
			getBeanClassLoader());
	Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
			+ "are using a custom packaging, make sure that file is correct.");
	return configurations;
}

因为AutoConfigurationImportSelector实现了DeferredImportSelector,所以AutoConfigurationImportSelector类会根据selectImports方法的返回的数组值将类路径下 META-INF/spring.factories 里面配置的所有 EnableAutoConfiguration 的值加入到 Spring 容器中。

  1. 关于@AutoConfigurationPackage注解的作用,很多人误解它的作用是扫描启动类包及以下的所有bean并注册到spring容器中,其实不是,这是@ComponentScan注解在做的事。@AutoConfigurationPackage真正的作用一言蔽之就是:该注解的作用是向容器内注入一个组件 组件的作用是保存一些包路径
    参考SpringBoot源码之-关于注解@AutoConfigurationPackage作用
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值