Spring @ConditionalOnProperty注释无法按预期工作
我在属性文件中定义了一个属性: property=true
然后,我有了SomeClass.javaclass, 仅 当属性设置为true时, 才应 创建一个Property
Configuration bean 。 __property
这是我的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);
  }
}
如果我在matchIfMissing =
true里面添加@ConditionalOnProperty,只是为了进行实验并查看的值是多少property,那么 确实 创建了bean
, 并且我看到的值property是true。
如果我删除了matchIfMissing =
true,留下的条件作为@ConditionalOnProperty(name="${property}",
havingValue="true")和属性更改property=true来自true于false豆,从未创建(既不true也不对false)。
我应该怎么做才能基于该属性有条件地创建bean?
回答:
请@Configuration在您的课程上方添加。
组件扫描不包括您的类,为此,需要@Component在类顶部添加或任何其他继承的注释。然后,您@Bean应该从spring创建。
希望这可以帮助。
以上是 Spring @ConditionalOnProperty注释无法按预期工作 的全部内容, 来源链接: utcz.com/qa/436045.html





