java match中的无法加载属性-
试图在spring中实现条件bean加载。这是代码,问题是,我无法在match方法中加载属性java match中的无法加载属性-,java,spring,dependency-injection,conditional,Java,Spring,Dependency Injection,Conditional,试图在spring中实现条件bean加载。这是代码,问题是,我无法在match方法中加载属性 @Configuration public class Class implements Condition { @Value("${test.property}") private boolean testProperty; @Override public boolean matches(ConditionContext conditionContext,
@Configuration
public class Class implements Condition {
@Value("${test.property}")
private boolean testProperty;
@Override
public boolean matches(ConditionContext conditionContext,
AnnotatedTypeMetadata annotatedTypeMetadata) {
sout(testProperty);
return true;
}
}
但是,如果我将属性注入构造函数,我可以打印该属性,
但是这并不能解决我的问题,有什么想法吗?对于基于环境变量的条件实例化,您可以在bean定义的顶部使用
@ConditionalOnProperty
注释
@Configuration
public class Config {
@Bean
@ConditionalOnProperty(name = "your.property", havingValue = "true")
public YourBean instantiateIfTrue() {
// instantiate and return YourBean in case the property is true
}
@Bean
@ConditionalOnProperty(name = "your.property", havingValue = "false")
public YourBean instantiateIfFalse() {
// instantiate and return YourBean in case the property is false
}
}
在您的情况下,您可以在@配置
上添加@条件属性
(并且不再扩展条件
)
仅当@conditionalnproperty
对于您的用例不够灵活时,才依赖于扩展条件
@Configuration
@ConditionalOnProperty(name = "your.property", havingValue = "true")
public class Config {
// ...
}