首先点开@SpringBootApplication可以看到如下注解
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
其中和自动配置相关的就是@EnableAutoConfiguration,开启自动配置。
再次点进去,可以看到:
@Target({ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited @AutoConfigurationPackage @Import({AutoConfigurationImportSelector.class})
其中的关键功能由@Import提供,其导入的AutoConfigurationImportSelector的selectImports()方法通过SpringFactoriesLoader.loadFactoryNames()扫描所有具有META-INF/spring.factories的jar包。spring-boot-autoconfigure-x.x.x.x.jar里就有一个这样的spring.factories文件。
把扫描到的这些内容包装成properties对象,从这个对象里面获取到EnableAutoConfiguration.class类(类名)对应的值,然后把他们添加到容器当中。
每一个这样的xxxAutoConfiguration类都是容器中的组件,都加到容器当中,用他们来做自动配置。
它实际上就是一个Spring容器配置类,它能通过以Properties结尾命名的类中取得在全局配置文件中配置的属性如:server.port,而XxxxProperties类是通过@ConfigurationProperties注解与全局配置文件中对应的属性进行绑定的。
原文:https://www.cnblogs.com/jumphua/p/13551220.html