配置的是一些基本属性

一、代码路径

1、SpringBootApplication注解

  1. public @interface SpringBootApplication {
  2. @AliasFor(
  3. annotation = EnableAutoConfiguration.class
  4. )
  5. }

2、EnableAutoConfiguration注解

  1. @Target({ElementType.TYPE})
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. @Inherited
  5. @AutoConfigurationPackage
  6. @Import({AutoConfigurationImportSelector.class})
  7. public @interface EnableAutoConfiguration {
  8. String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
  9. Class<?>[] exclude() default {};
  10. String[] excludeName() default {};
  11. }

3、AutoConfigurationImportSelector类

getCandidateConfigurations调用 SpringFactoriesLoader类的loadFactoryNames方法。

  1. protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
  2. List<String> configurations = SpringFactoriesLoader.loadFactoryNames(this.getSpringFactoriesLoaderFactoryClass(), this.getBeanClassLoader());
  3. Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you are using a custom packaging, make sure that file is correct.");
  4. return configurations;
  5. }

4、SpringFactoriesLoader类

getResources(“META-INF/spring.factories”)获取配置信息。

  1. private static Map<String, List<String>> loadSpringFactories(@Nullable ClassLoader classLoader) {
  2. MultiValueMap<String, String> result = (MultiValueMap)cache.get(classLoader);
  3. if (result != null) {
  4. return result;
  5. } else {
  6. try {
  7. Enumeration<URL> urls = classLoader != null ? classLoader.getResources("META-INF/spring.factories") : ClassLoader.getSystemResources("META-INF/spring.factories");
  8. LinkedMultiValueMap result = new LinkedMultiValueMap();
  1. ![image.png](https://cdn.nlark.com/yuque/0/2021/png/5365888/1627027494375-2db09b85-0980-48ae-b921-1f3356ed315f.png#clientId=ud79fe82f-80d8-4&from=paste&height=232&id=uc95ee75c&margin=%5Bobject%20Object%5D&name=image.png&originHeight=464&originWidth=1162&originalType=binary&ratio=1&size=75467&status=done&style=none&taskId=ufa129cf9-e3d9-49ad-8735-1f4a6750564&width=581)

二、Spring.factories的几个常用自动配置

  1. org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration

三、总结

spring-boot-autoconfigure包中:
xxxAutoConfiguration类用来自动加载配置、xxxProperties类是定义具体配置属性

在application.properties中设置debug=true,可以打印配置信息。

  1. debug=true
  2. server.port=8000
  3. ## sqlite 数据库
  4. spring.datasource.driver-class-name=org.sqlite.JDBC
  5. #数据库地址
  6. spring.datasource.url=jdbc:sqlite:app.db
  7. #每次启动更改数据表结构
  8. spring.jpa.hibernate.ddl-auto=update
  9. #显示数据库操作记录
  10. spring.jpa.show-sql=true

image.png

四、扩展配置

五、参考

1、SpringBoot自动配置源码分析
2、狂神-MVC自动配置原理
3、官方:https://docs.spring.io/spring-boot/docs/2.2.5.RELEASE/reference/htmlsingle/#boot-features-spring-mvc-auto-configuration