簡體   English   中英

Spring @ConditionalOnProperty注釋無法按預期工作

[英]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 獲得創建和我看到的價值propertytrue

如果刪除matchIfMissing = true ,則將條件保留為@ConditionalOnProperty(name="${property}", havingValue="true")並將屬性property=truetrue更改為false永遠不會創建該bean(都不為true也不是false )。

我應該怎么做才能基於該屬性有條件地創建bean?

請在課程上方添加@Configuration

組件掃描不包括您的類,因此需要在@Component頂部添加@Component或任何其他繼承的注釋。 然后,您的@Bean應該從spring創建。

希望這可以幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM