1. @SpringBootApplication
  2. public class MainApplication {
  3. public static void main(String[] args) {
  4. SpringApplication.run(MainApplication.class, args);
  5. }
  6. }

搭建一个 Springboot 项目无需各种配置文件,一个 @SpringBootApplication 就可以使 main 方法 run 起来

  1. @Target({ElementType.TYPE})
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Inherited
  5. @SpringBootConfiguration
  6. @EnableAutoConfiguration
  7. @ComponentScan(
  8. excludeFilters = {@Filter(
  9. type = FilterType.CUSTOM,
  10. classes = {TypeExcludeFilter.class}
  11. ), @Filter(
  12. type = FilterType.CUSTOM,
  13. classes = {AutoConfigurationExcludeFilter.class}
  14. )}
  15. )
  16. public @interface SpringBootApplication {
  17. ...

@SpringBootApplication 是一个组合注解,核心是这三个:

  • @SpringBootConfiguration:表示这是一个配置类
  • @EnableAutoConfiguration:开启自动配置
  • @ComponentScan:开启组件扫描

自动配置重点就在 @EnableAutoConfiguration

@EnableAutoConfiguration

  1. @Target({ElementType.TYPE})
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Inherited
  5. @AutoConfigurationPackage
  6. @Import({AutoConfigurationImportSelector.class})
  7. public @interface EnableAutoConfiguration {
  8. ...

@AutoConfigurationPackage

  • 将主配置类(@SpringBootConfiguration标注的类)的所在包及下面所有子包里面的所有组件扫描到Spring容器中。

@Import({AutoConfigurationImportSelector.class})

  • 给当前配置类导入另外的 N 个自动配置类。

String[] selectImports -> getAutoConfigurationEntry(获取所有符合规则的配置类)

  1. 1、利用getAutoConfigurationEntry(annotationMetadata);给容器中批量导入一些组件
  2. 2、调用List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes)获取到所有需要导入到容器中的配置类
  3. 3、利用工厂加载 Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader);得到所有的组件
  4. 4、从META-INF/spring.factories位置来加载一个文件。
  5. 默认扫描我们当前系统里面所有META-INF/spring.factories位置的文件
  6. spring-boot-autoconfigure-2.3.4.RELEASE.jar包里面也有META-INF/spring.factories

文件里面写死了spring-boot一启动就要给容器中加载的所有配置类

使用 @ConditionalOnClass 等按条件注入注解,按需控制配置生效

SpringBoot 默认配置好所有组件,但是用户如果配置了,用户的配置优先

修改配置

查文档

https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#common-application-properties

查代码

image.png

image.png

当 debug=true 时会打印出所有配置项的生效情况,Positive(生效)/Negative(不生效)