【问题标题】:Cant load property in java match-无法在 java 匹配中加载属性-
【发布时间】:2019-03-13 14:27:44
【问题描述】:

尝试在 spring 中实现条件 bean 加载。这是代码,问题是,我无法在 match 方法中加载属性,

@Configuration
public class Class implements Condition {

    @Value("${test.property}")
    private boolean testProperty;

    @Override
    public boolean matches(ConditionContext conditionContext, 
                           AnnotatedTypeMetadata annotatedTypeMetadata) {
        sout(testProperty);
        return true;
    }

}

但是,如果我将属性注入构造函数,我可以打印它, 但这并不能解决我的问题,有什么想法吗?

【问题讨论】:

    标签: java spring dependency-injection conditional


    【解决方案1】:

    对于基于环境变量的条件实例化,您可以在 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
        }
    
    }
    

    在您的情况下,您可以将 @ConditionalOnProperty 添加到您的 @Configuration 之上(并且不再扩展 Condition)。

    @Configuration
    @ConditionalOnProperty(name = "your.property", havingValue = "true")
    public class Config {
    
        // ...
    
    }
    

    仅当 @ConditionalOnProperty 对您的用例不够灵活时,才依赖扩展 Condition

    【讨论】:

      猜你喜欢
      • 2011-11-27
      • 1970-01-01
      • 1970-01-01
      • 2016-05-18
      • 1970-01-01
      • 2012-04-19
      • 1970-01-01
      • 1970-01-01
      • 2019-04-26
      相关资源
      最近更新 更多