springBoot自动装配原理

 

@SpringBootApplication里面三个核心注解

 

@SpringBootConfiguration表明该类为配置类

@EnableAutoConfiguration //开启springBoot自动配置 里面有两个关键注解

@ComponentScan //扫描该类所在包下spring的注解

进入@EnableAutoConfiguration 发现 

@AutoConfigurationPackage   //该注解表明 此类所在包为自动配置包进行管理
@Import(AutoConfigurationImportSelector.class)

//该注解表明 此类所在包为自动配置包进行管理
@AutoConfigurationPackage


@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {

@SpringBootApplication注解点进去,集成了@EnableAutoConfiguration注解,而这个注解中使用了@Import(AutoConfigurationImportSelector.class)。点进AutoConfigurationImportSelector,然后在getCandidateConfigurations方法中去获取配置信息,继续往里追

getAutoConfigurationEntry()

protected AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
		if (!isEnabled(annotationMetadata)) {
			return EMPTY_ENTRY;
		}
		AnnotationAttributes attributes = getAttributes(annotationMetadata);

    //继续追该方法
		List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);

进入getCandidateConfigurations找到loadSpringFactories()方法

private static Map<String, List<String>> loadSpringFactories(ClassLoader classLoader) {
		Map<String, List<String>> result = cache.get(classLoader);
		if (result != null) {
			return result;
		}

		result = new HashMap<>();
		try {
        //关键一句
			Enumeration<URL> urls = classLoader.getResources(FACTORIES_RESOURCE_LOCATION);

此时FACTORIES_RESOURCE_LOCATION = "META-INF/spring.factories";

就是获取所有start依赖包下的spring.factories  然后其中内容就是自动配置包的全限定名称,拿到这些全限定名称之后通过反射调用,完成自动装配。

此时会扫描所有的自动配置类,但是不一定会初始化成功,原因为自动配置类中@Conditional 注解,效果为满足条件配置才会生效。

随便进入一个自动配置类看看

@Configuration(proxyBeanMethods = false)
@AutoConfigureAfter(JacksonAutoConfiguration.class)
//假设没有注册Cluster 则此次注册就不会生效
@ConditionalOnClass(Cluster.class)
@ConditionalOnProperty("spring.couchbase.connection-string")
@EnableConfigurationProperties(CouchbaseProperties.class)
public class CouchbaseAutoConfiguration {

最后完成springBoot自动装配。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值