![](/img/trans.png)
[英]@ConditionalOnProperty annotation not working in spring boot project
[英]Spring @ConditionalOnProperty annotation not working as expected
我在屬性文件中定義了一個屬性: property=true
然后,我有了SomeClass.java
類, 僅當property property
設置為true時, 才 應創建Property Configuration bean。
這是我的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
永遠不會創建該bean(都不為true
也不是false
)。
我應該怎么做才能基於該屬性有條件地創建bean?
請在課程上方添加@Configuration
。
組件掃描不包括您的類,因此需要在@Component
頂部添加@Component
或任何其他繼承的注釋。 然后,您的@Bean
應該從spring創建。
希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.