什么是 @ConditionalOnProperty
?
@ConditionalOnProperty
是 Spring Boot 提供的一个条件注解,它表示:
如果配置文件中某个属性满足指定的值条件,则当前注解标注的组件/Bean 才会被创建或生效。
它广泛应用于 Spring Boot 的自动配置类中,确保只有在特定配置项被启用的情况下才会加载某些功能。
步骤一:定义一个条件 Bean
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeatureConfig {
@Bean
@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
public MyFeatureService myFeatureService() {
return new MyFeatureService();
}
}
📌 说明:
- 该 Bean 只有在
feature.enabled=true
时才会被创建 - 否则不创建,避免启动失败或资源浪费
步骤二:在 application.yml
中定义配置项
feature:
enabled: true
📌 结果:
MyFeatureService
会被创建- 如果配置为
false
或未配置,则不会创建该 Bean
步骤三:在 @Component
上使用
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
@Component
@ConditionalOnProperty(name = "feature.debug", havingValue = "true", matchIfMissing = true)
public class DebugService {
public void logDebugInfo() {
System.out.println("这是调试服务");
}
}
📌 说明:
matchIfMissing = true
表示如果配置不存在,默认也认为条件成立- 更加灵活,适用于 Starter 开发
步骤四:实战:开发一个可插拔的 Starter
1. 创建 feature-spring-boot-starter
模块
定义一个自动配置类:
@Configuration
@ConditionalOnProperty(name = "feature.enabled", havingValue = "true")
public class FeatureAutoConfiguration {
@Bean
public MyFeatureService myFeatureService() {
return new MyFeatureService();
}
}
2. 在 spring.factories
中注册自动配置类:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.feature.autoconfigure.FeatureAutoConfiguration
3. 用户引入 Starter 后:
- 如果配置了
feature.enabled=true
,功能启用 - 否则不启用,不加载相关 Bean
📌 这是构建可插拔模块、Starter 的最佳实践!