Spring Boot 自动配置
程序员文章站
2022-04-19 19:09:06
...
Spring Boot 启动方法如下
@SpringBootApplication
public class ActuatorApplication {
public static void main(String[] args) {
SpringApplication.run(ActuatorApplication.class, args);
}
}
@SpringBootApplication 其实包含3个注解
○@SpringBootConfiguration:标记当前类为配置类
○@EnableAutoConfiguration:开启自动配置
○@ComponentScan:扫描主类所在的同级包以及下级包里的Bean
关键是@EnableAutoConfiguration
我们来看看@EnableAutoConfiguration的源代码:
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@AutoConfigurationPackage
@Import(AutoConfigurationImportSelector.class)
public @interface EnableAutoConfiguration {
String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";
Class<?>[] exclude() default {};
String[] excludeName() default {};
}
关键是@Import(AutoConfigurationImportSelector.class)导入的配置功能,
AutoConfigurationImportSelector中的方法getCandidateConfigurations,得到待配置的class的类名集合
/**
* Return the auto-configuration class names that should be considered. By default
* this method will load candidates using {@link SpringFactoriesLoader} with
* {@link #getSpringFactoriesLoaderFactoryClass()}.
* @param metadata the source metadata
* @param attributes the {@link #getAttributes(AnnotationMetadata) annotation
* attributes}
* @return a list of candidate configurations
*/
protected List<String> getCandidateConfigurations(AnnotationMetadata metadata,
AnnotationAttributes attributes) {
List<String> configurations = SpringFactoriesLoader.loadFactoryNames(
getSpringFactoriesLoaderFactoryClass(), getBeanClassLoader());
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.");
return configurations;
}
下一步通过SpringFactoriesLoader.loadFactoryNames() 扫描所有 jar 包类路径下的META-INF/spring.factories,将扫描到的文件内容包装成properties对象,从properties中获取到EnableAutoConfiguration.class类名对应的值,然后把他们添加到容器中。
上一篇: 获得当前年 月,星期
推荐阅读
-
java-使用war将spring-boot和angular 7应用程序部署到tomcat 8.5中
-
(转)Spring boot 切换配置文件到yaml
-
将Spring Boot JAR应用程序转换为WAR
-
将Spring Boot应用程序绑定到Cloud Foundry中的服务的方法
-
Spring Boot应用程序创建可部署的war文件到tomcat
-
将Spring Boot应用程序注册成为系统服务
-
将Spring Boot程序打包成docker镜像-超简版
-
spring Boot环境下dubbo+zookeeper的一个基础讲解与示例
-
Spring Boot使用redis做数据缓存
-
Spring Boot 实战 入门