Spring @ConditionalOnProperty批注无法按预期工作 [英] Spring @ConditionalOnProperty annotation not working as expected

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

问题描述

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

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

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

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);
  }
}

如果我将matchIfMissing = true添加到@ConditionalOnProperty内,只是为了进行实验并查看property的值是什么,那么就创建了豆 ,并且我看到了该值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}", havingValue="true"),并将属性property=truetrue更改为false,则永远不会创建该bean(对于truefalse都不会)

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.

组件扫描不包括您的类,因此需要在类顶部添加@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批注无法按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆