自动装配是SpringBoot的核心功能,它将开发人员从Bean的繁复配置中解脱出来。那么SpringBoot具体起什么作用呢?以Spring MVC为例,不采用SpringBoot时,需要配置视图解析器,文件解析器,请求适配器等各种Bean,如果采用SpringBoot,则只需集成spring-boot-starter-web依赖模块即可。同样如果使用数据库,在非SpringBoot工程中,我们需要配置dataSource、sessionFactory、transactionManager等各种Bean。
本文将逐步解析SpringBoot自动装配原理,首先从@SpringBootApplication启动注解入手,然后逐层分析SpringBoot怎么利用注解实现Bean自动装配的。
注解@SpringBootApplication一般作用在启动类上,由三个重要的Annotation组成@SpringBootConfiguration、@EnableAutoConfiguration和@ComponentScan,其中@SpringBootConfiguration实际上就是代表了一个配置类,相当于一个beans.xml文件,@ComponentScan的功能其实就是自动扫描并加载符合条件的组件或bean定义,最终将这些bean 定义加载到Spring IoC容器中,@EnableAutoConfiguration代表开启SpringBoot的自动装配。
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes