簡體   English   中英

如何在春季從@Autowired List <>的每個bean中獲取@Qualifier

[英]How to get @Qualifier from each bean of @Autowired List<> in Spring

有沒有辦法從Spring中的@Autowired List<Bean>每個bean中獲取@Qualifier名稱。 或更廣泛地講:如果我有一個bean實例,是否可以在運行時獲取Bean @Qualifier信息?

假設我有:

//Config.java
@Bean(name = "en-db")
@ConfigurationProperties(prefix = "spring.datasource.en")
public DataSource dataSourceEN() {...}

@Bean(name = "de-db")
@ConfigurationProperties(prefix = "spring.datasource.de")
public DataSource dataSourceDE() {...}

//Repository.java
public Repository(List<DataSource> ds) { 
    // Is there any way to create a hashmap of Qualifier => Bean? 
    // like {"en-db" : ds.get(0), "de-db" : ds.get(1)}
    // or maybe there is a way to autowire the Hashmap<Qualifier, Bean>
}

現在我正在使用它(它工作正常):

public Repository(@Qualifier("en-db") DataSource en, 
                  @Qualifier("de-db") DataSource de, //... and many more  
){ 
   Map<String, EntityManager> dataSources = new HashMap<>();
   dataSources.put("en-db", en);
   dataSources.put("de-db", de);
   ...

}

但是我有10多個數據源,即使自動裝配后,我也應該有某種方法可以檢測到Bean Qualifier,而且我只能使用@Autowired List。

PS:這不是本地化問題,我在單個頁面上使用了所有10個分貝

為了獲得Bean的最詳細的元數據信息,最好的選擇是注入DefaultListableBeanFactory並使用其API。

但是,您的情況(即,獲取通過其beanName鍵入的特定類型的bean的映射)可以簡單地通過注入ApplicationContext並調用其getBeansOfType

@Autowired
public Repository(ApplicationContext ctx) { 
   //The key is the beanName which is en-db , de-db .....  
   Map<String, DataSource> map = ctx.getBeansOfType(DataSource.class);
}

或者更好的方法是注入Map<String, DataSource>

public class Repository {

   @Autowired
   private Map<String, DataSource> dataSources;

}

暫無
暫無

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

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