前言
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