springboot自动配置
一、原理
1、 基于添加的 JAR 依赖⾃动对 Spring Boot 应⽤程序进⾏配置
spring-boot-autoconfifiguration
2、开启自动配置
@EnableAutoConfiguration
exclude = Class<?>[]
@SpringBootApplication(包含有EnableAutoConfiguration)
AutoConfigurationImportSelector
getAutoConfigurationEntry自动配置元数据
getCandidateConfigurations根据条件进行判断
自动配置项
二、条件注解
@Conditional
1、当满足某个条件时配置生效
条件注解
@Conditional
类条件
@ConditionalOnClass
@ConditionalOnMissingClass
属性条件
@ConditionalOnProperty
Bean 条件
@ConditionalOnBean
@ConditionalOnMissingBean
@ConditionalOnSingleCandidate
资源条件
@ConditionalOnResource
Web 应⽤条件
@ConditionalOnWebApplication
@ConditionalOnNotWebApplication
其他条件
@ConditionalOnExpression
@ConditionalOnJava
@ConditionalOnJndi
三、实现自己的自动配置
定义日志输出类,当自动配置生效时打印日志
@Slf4j
public class GreetingApplicationRunner implements ApplicationRunner {
public GreetingApplicationRunner() {
log.info("Initializing GreetingApplicationRunner.");
}
public GreetingApplicationRunner(String name) {
log.info("Initializing GreetingApplicationRunner."+name);
}
public void run(ApplicationArguments args) throws Exception {
log.info("Hello everyone! We all like Spring! ");
}
}
定位⾃动配置,resources目录新建META-INF新增spring.factories文件,内容:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
geektime.spring.hello.greeting.GreetingAutoConfiguration
定义自动配置类
@Configuration
@ConditionalOnClass(GreetingApplicationRunner.class)
public class GreetingAutoConfiguration {
@Bean
@ConditionalOnMissingBean(GreetingApplicationRunner.class)
@ConditionalOnProperty(name = "greeting.enabled", havingValue = "true", matchIfMissing = true)
public GreetingApplicationRunner greetingApplicationRunner() {
return new GreetingApplicationRunner("test");
}
}
当满足以下几个条件时配置生效:
1、存在GreetingApplicationRunner类时生效
2、GreetingApplicationRunner对象不存在生效
3、属性greeting.enabled为true生效,默认为true
测试结果: