Spring引导中的@Value不会从application.properties中注入值

时间:2017-08-20 22:37:09

标签: java spring-boot

我在我的代码中使用EasyRules API。以下是一个规则类,它访问application.propertiessrc/main/resources文件中的@Rule(name = "Over-weight rule") // to indicate that this class is a rule @PropertySource("/application.properties") public class OverweightRule { /** * The user input which represents the data * that the rule will operate on. */ private Metric metric; @Autowired @Qualifier("alertServiceDao") private AlertService alertService; @Value("${base.weight}") private double baseWeight; public OverweightRule(Metric metric) { this.metric = metric; } @Condition public boolean isOverweight() { // The rule should be applied only if the // weight in metric object shoots 10% over the base weight. if(metric.getWeight() > (baseWeight + (0.1 * baseWeight))) return true; return false; } @Action public void createAndStoreOverweightAlert() { // When rule conditions are satisfied, // an alert is created. Alert alert = new Alert(); alert.setAlertType(Alert.AlertType.OVER_WEIGHT); alert.setWeight(metric.getWeight()); alert.setTimeStamp(metric.getTimeStamp()); alertService.createAlert(alert); } } 文件的双精度值:

application.properties

baseWeight中的值始终为0.0,而我在属性文件中将其设置为150.0。我读到Spring启动会自动从src/main/resources中的@PropertySource("/path to properties file")文件中读取值,因此无需使用@PropertySource。我仍然添加了@Configuration注释,但结果是一样的。这段代码有什么问题?我不想将{{1}}添加到此类中,因为我希望将此类保留为easy规则框架定义的Rule类。

1 个答案:

答案 0 :(得分:1)

另一种方法是声明为@Component并移除@PropertySource并保留@Value("${base.weight}")

@Rule(name = "Over-weight rule") // to indicate that this class is a rule
@Component("myOverWeightRule")
public class OverweightRule {

创建rulesEngineFactoryBean后,您可以自动加载myOverWeightRule

@Bean
@Autowired
RulesEngineFactoryBean rulesEngineFactoryBean(OverweightRule myOverweightRule){
    RulesEngineFactoryBean rules = new RulesEngineFactoryBean();
    rules.setRules(Arrays.asList(myOverweightRule));
    return rules;
}

最后调用fireRules获取rulesEngineFactoryBean

        RulesEngine rulesEngine
                = (RulesEngine) ctx.getBean("rulesEngineFactoryBean");
        rulesEngine.fireRules();