1.什么是SpringBoot的自动配置
SpringBoot的自动配置就是当spring容器启动后,一些配置类,bean对象就自动存入到IOC容器中,无需手动声明,从而简化开发,省去繁琐的配置操作
2.原理解析
*想要了解自动配置的原理以我们初学者的视角关注Application启动类上@SpringBootApplication注解即可 该注解是一个组合注解 其内部还封装了七个注解 分别是四个元注解(@Retention @Target @Documented @Inherited)与本文的重点关联不大就不再展开叙述 重点为接下来的三个注解 分别是 @ComponentScan @SpringBootConfiguration @EnableAutoConfiguration
接下来我将以重要程度来依次介绍这三个注解
1.@ComponentScan(basePackages)该注解用于包扫描 会扫描当前包及其子包的组件(如 @Component、@Service、@Repository、@Controller )上述几个注解都用于将类注册为Spring管理的bean 只有当注册行为被扫描到时才会生效 所以尤其需要注意当你想要添加的bean所在的位置不属于启动类所在的包及其子包时需要显示的进行配置 如图所示 为@ComponentScan的参数basePackages赋值 即bean所在的包的全类名
2.@SpringBootConfiguration 其内部封装了@Configuration @Indexed两个注解 @Configuration声明当前类也是配置类(即启动类也是配置类) 即可以在当前类中直接声明第三方bean对象 @Indexed加速应用启动非本文的重点
3.@EnableAutoConfiguration该注解是实现自动配置的核心注解 其内部封装了@AutoConfigurationPackage @Import({AutoConfigurationImportSelector.class}) @Import便是核心中的核心 该注解的作用是将配置类或配置文件导入到当前配置类中,导入的配置类中的Bean和其他配置信息也会被包含到当前Spring容器中
3.1@Import({AutoConfigurationImportSelector.class}) 详解:在此处@Import导入了AutoConfigurationImportSelector 可以看到该类实现了接口DeferredImportSelector而该接口是ImportSelector的子接口 所以也可以说AutoConfigurationImportSelector是ImportSelector的实现类 那接下来就让我们看看该类究竟实现了ImportSelector接口的哪个方法
3.2可以看到该类实现了ImportSelector接口的selectImports方法 该方法封装了需要导入到Spring IOC容器中类的全类名 接下来接让我们一起来看看这些需要导入的类是如何进行封装的
3.3selectImports()方法详解 作为初学者 我们只需要关注 selectImports()调用的getAutoConfigurationEntry()即可
看起来是不是有点复杂,但不必惊慌我们只需要关注getAutoConfigurationEntry()方法中的这个configurations String类型的集合即可
3.4configurations 这个集合当中封装了 spring.factories与spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports这样的两个配置文件 SpringBoot在启动时会自动加载这两个配置文件的信息
可以看到这两个配置文件配置了一系列类的全类名 最终会被读取出来 通过@Import注解加载到IOC容器进行管理
*总结:
@SpringBootApplication中除四个元注解外 还封装了
@SpringBootConfiguration-> @Configuration 表明启动类也是一个配置类
@ComponentScan用于包扫描
@EnableAutoConfiguration 实现自动装配的核心注解 其内部封装了@Import 导入了AutoConfigurationImportSelector(ImportSelector的实现类) ImportSelector的实现类通过selectImports()方法 将需要的类导入到IOC容器中
selectImports()方法 调用getAutoConfigurationEntry() 读取这个configurations String类型的集合中封装的spring.factories与 spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports两个配置文件 最终加载到IOC容器中进行管理