SpringBoot 启动的时候,会有大量的自动配置的类加载到容器中。正是因为 SpringBoot 的这些自动配置,使得我们在编程的时候,不像 Spring MVC 那样还需要关注各种配置,开发者只需要专心的关注业务代码。
SpringBoot 中的@EnableAutoConfiguration 注解,表示实现自动配置。通常不直接使用该注解,而是通过注解@SpringBootApplication 使用它,@SpringBootApplication 注解包含了@EnableAutoConfiguration 注解。
@EnableAutoConfiguration 注解定义源码如下:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
/**
* Exclude specific auto-configuration classes such that they will never be applied.
* @return the classes to exclude
*/
Class<?>[] exclude() default {};
/**
* Exclude specific auto-configuration class names such that they will never be
* applied.
* @return the class names to exclude
* @since 1.3.0
*/
String[] excludeName() default {};
}
定义中出现了@AutoConfigurationPackage 注解,该注解的作用就是将主配置类(即@SpringBootApplication 标注的类)所在的包及其子包里的所有类都纳入 Spring 容器。从源码中可以看到它标注了一个@Import 注解,该注解是 Spring 的底层注解。它给容器中导入一个组件 (AutoConfigurationImportSelector.class)。
AutoConfigurationImportSelector 确定了导入哪些组件到选择器。该类中有个方法 selectImports,返回了一个 String 数组,其中内容就是需要导入的组件的全类名,这些组件会被自动添加到 Spring 容器。
我们可以在 spring-boot-autoconfigure.jar 中查看具体导入了哪些组件,spring-boot-autoconfigure.jar 有一个 META-INF/spring.factories,这个文件中定义了需要导入的配置类。
spring.factories 中的内容如下:
继续展开,看到这里包含了大量的自动配置类,有了这些自动配置类就能帮我们自动配置好相关内容,简化开发,提高效率。
SpringBoot 的自动配置原理并不复杂,它大量的使用了条件注解@Conditional,该注解可以根据不同的条件状态来判断是否需要自动配置。想深入了解的话,可以百度一些文章,分析的比较详细。