我在属性文件中定义了一个属性:property=true
然后我有 SomeClass.java
类,如果属性 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);
}
}
如果我在 @ConditionalOnProperty
中添加 matchIfMissing = true
,只是为了试验并查看 property
的值是多少,然后bean 确实被创建了,我看到 property
的值为 true
。
如果我删除 matchIfMissing = true
,将条件保留为 @ConditionalOnProperty(name="${property}", havingValue="true")
并更改属性 property=true
从 true
到 false
永远不会创建 bean(无论是 true
还是 假
)。
我该怎么办根据属性有条件地创建 bean?
最佳答案
请在您的类上方添加@Configuration
。
组件扫描不包括您的类,为此需要在您的类之上添加 @Component
或任何其他继承的注释。然后你的 @Bean
应该从 spring 创建。
希望这对您有所帮助。
关于java - Spring @ConditionalOnProperty 注释未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53297465/