spring boot实战(第十三篇)自动配置原理分析

前言

Spring Boot中引入了自动配置,让开发者利用起来更加的简便、快捷,本篇讲利用RabbitMQ的自动配置为例讲分析下Spring Boot中的自动配置原理。

在上一篇末尾讲述了Spring Boot 默认情况下会为ConnectionFactory、RabbitTemplate等bean,在前面的文章中也讲到嵌入的Tomcat默认配置为8080端口

这些都属于Spring Boot自动配置的范畴,当然其自动配置相当多。


EnableAutoConfiguration注解

在创建Application时我们使用了SpringBootApplication注解,在 spring boot实战(第九篇)Application创建源码分析中曾有所分析,再来看下其定义:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Configuration
@EnableAutoConfiguration
@ComponentScan
public @interface SpringBootApplication {  
	Class<?>[] exclude() default {};

}

该注解上存在元注解@EnableAutoConfiguration,这就是Spring Boot自动配置实现的核心入口;其定义为:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import({ EnableAutoConfigurationImportSelector.class,
		AutoConfigurationPackages.Registrar.class })
public @interface EnableAutoConfiguration {

	/**
	 * Exclude specific auto-configuration classes such that they will never be applied.
	 * @return the classes to exclude
	 */
	Class<?>[] exclude() default {};

}

很显然能看出有一特殊的注解 @Import,该注解在spring boot实战(第十篇)Spring boot Bean加载源码分析中有讲解到,加载bean时会解析Import注解,因此需要讲目光聚集在这段代码

@Import({ EnableAutoConfigurationImportSelector.class,
		AutoConfigurationPackages.Registrar.class })

EnableAutoConfigurationImportSelector

来看EnableAutoConfigurationImportSelector类

public String[] selectImports(AnnotationMetadata metadata) {
		try {
			AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata
					.getAnnotationAttributes(EnableAutoConfiguration.class.getName(),
							true));

			Assert.notNull(attributes, "No auto-configuration attributes found. Is "
					+ metadata.getClassName()
					+ " annotated with @EnableAutoConfiguration?");

			// Find all possible auto configuration classes
  • 16
    点赞
  • 68
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值