SpringBoot深入自动配置
引入
在上一篇Spring Boot与微服务基本介绍中,介绍了创建maven项目到运行springboot的基本过程。
其中使用主程序来启动SpringBoot
1 |
|
仅仅是添加了一个@SpringBootApplication注解,这个注解的作用是什么,原理是什么,接下来就通过源码简单看一下。
SpringBootApplication启动注解
1 | //点开@SpringBootApplication源码 |
在上面的@SpringBootApplication源码中,其中使用到了三个比较重要的基本注解@SpringBootConfiguration、@EnableAutoConfiguration和@ComponentScan。下面分别来对这三个注解进行简单分析。
SpringBootConfiguration
1 | /** |
其实这时SpringBoot对Spring的@Configuration的注解的包装
Configuration
1 | (ElementType.TYPE) |
简单理解为,Configuration 注解上标注了@Component原注解,所以它也是一个spring组件,会通过扫描把标志这个注解的类作为spring的配置类加载到容器中。
实际上加载Configuration的方法有三种,自动扫描配置类只是其中的一种,其他两种是
- 通过AnnotationConfigApplicationContext类
1 |
|
- 使用xml配置文件,将标注为@Configuration的类作为一个bean来声明在xml文件中。
1 | <beans> |
标记@Configuration注解的类表示这个类中声明了一个或多个@Bean方法,可以交由spring容器处理。可以在运行时生成bean定义和bean之间的服务请求。
更加详细的参考Spring官网Configuration注解
EnableAutoConfiguration
EnableAutoConfiguration是spring boot中的注解,它的作用就是猜测并自动配置可能需要的bean,也就是自动配置功能。
1 |
|
其中重要的两个注解@AutoConfigurationPackage和@Import中的内容
AutoConfigurationPackage
1 | // 标注@AutoConfigurationPackage的注解可以使用Registrar进行注册 |

将主配置类的所在的包及下面的所有子包扫描到Spring容器中。
1 | // 以编程方式注册自动配置包名称.将给定的包【这里的是com.nanyin 】注册添加到已经注册的包名称中 |
@Import(AutoConfigurationImportSelector.class)
自动导入组件的选择器。将需要导入的组件以全类名的方式返回一个数组。
1 |
|
代码中断点得出的自动导入的包名称:

通过方法getConstructorArgumentValues得到自动配置的包的名称,调用了SpringFactoriesLoader的方法,其中
1 | protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) { |
最后通过文件中spring.factorys文件中的内容来获取最终的自动导入自动配置类包范围。


ComponentScan
组件扫描指令,需要与@Configuration一起使用。与Spring提供的xml配置<context:component-scan>作用相同。
在SpringBootApplication注解中是这样定义ComponentScan的:
1 | (excludeFilters = { |
excludeFilters的作用是指定哪些类型不符合组件扫描的条件,也就是排除掉指定的类。