springboot中 Condition 注解 使用SpEL 判断某个配置属性的值为指定值
可以使用 @Condition 注解结合 SpEL 表达式来判断某个配置属性的值是否为指定值。具体操作步骤如下:
- 在应用的配置文件中添加需要判断的配置属性,例如:
myconfig:
enabled: true
- 在需要进行条件判断的地方使用 @Condition 注解,例如:
@Configuration
@Conditional(MyCondition.class)
public class MyConfiguration {
// 配置类中的其他配置项
}
- 编写 MyCondition 类,实现 Condition 接口,并在 matches 方法中编写 SpEL 表达式进行条件判断,例如:
public class MyCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
return environment.getProperty("myconfig.enabled", Boolean.class, false);
}
}
这里的 SpEL 表达式为 environment.getProperty("myconfig.enabled", Boolean.class, false),意思是获取名为 myconfig.enabled 的配置属性的值,并将其转换为 Boolean 类型,如果获取失败则返回 false。
- 运行应用,当配置属性
myconfig.enabled的值为 true 时,MyConfiguration 类中的配置项将被加载,否则不会被加载
原文地址: https://www.cveoy.top/t/topic/fsQA 著作权归作者所有。请勿转载和采集!