注释未按预期工作

注释未按预期工作

本文介绍了Spring @ConditionalOnProperty 注释未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在属性文件中定义了一个属性:property=true

I have a property defined inside a property file: property=true

然后我有 SomeClass.java 类,它应该创建一个属性配置 bean only 如果属性 property 设置为 true.

Then I have SomeClass.java class , which should create a Property Configuration bean only if the property property is set to true.

这是我的 SomeClass 类:

public class SomeClass {

  //this is the proerty which I set to true or false
  @Value("${property}")
  private String property;

  //this is the bean which needs to be created conditionally based on the property but at the moment it does not get created
  @Bean
  @ConditionalOnProperty(name="${property}", havingValue="true")
  public PropertyConfiguration propertyConfig() {
    // doesnt print anything because the bean does not get created
    System.out.print(property);
  }
}

如果我在 @ConditionalOnProperty 中添加 matchIfMissing = true,只是为了试验并看看 property 的值是什么,然后bean 确实被创建,我看到property的值是true.

If I add the matchIfMissing = true inside the @ConditionalOnProperty, just to experiment and to see what is the value of property, then the bean does get created and I see that the value of property is true.

如果我删除 matchIfMissing = true,将条件保留为 @ConditionalOnProperty(name="${property}", gettingValue="true") 并更改属性 property=truetruefalse 永远不会创建 bean(对于 true错误).

If I remove the matchIfMissing = true, leave the condition as @ConditionalOnProperty(name="${property}", havingValue="true") and change the property property=true from true to false the bean is never created (neither for true nor for false).

我该怎么办?bean 是根据属性有条件地创建的?

What should I do s.t. the bean gets created conditionally, based on the property?

推荐答案

请在您的班级上方添加@Configuration.

Please add @Configuration above your class.

组件扫描不包括您的类,为此需要在您的类之上添加 @Component 或任何其他继承的注释.那么你的 @Bean 应该是从 spring 中创建的.

The component scan does not include your class, to do so it is required to add a @Component or any other inherited annotation on top of your class. Then your @Bean should be created from spring.

希望这会有所帮助.

这篇关于Spring @ConditionalOnProperty 注释未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 13:12