简体   繁体   English

如何在春季从@Autowired List <>的每个bean中获取@Qualifier

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

Is there any way to get @Qualifier name from each bean of @Autowired List<Bean> in Spring. 有没有办法从Spring中的@Autowired List<Bean>每个bean中获取@Qualifier名称。 Or more broadly: Can i get a Bean @Qualifier information at runtime if i have a bean instance? 或更广泛地讲:如果我有一个bean实例,是否可以在运行时获取Bean @Qualifier信息?

Lets suppose i have: 假设我有:

//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>
}

right now i'm using this (and it works fine): 现在我正在使用它(它工作正常):

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

}

But i have 10+ data sources and it feels that there should be some way to detect the Bean Qualifier even after autowire and i can just use @Autowired List. 但是我有10多个数据源,即使自动装配后,我也应该有某种方法可以检测到Bean Qualifier,而且我只能使用@Autowired List。

PS: it is not a localisation issue, i'm using all 10 db on a single page PS:这不是本地化问题,我在单个页面上使用了所有10个分贝

To get a bean 's most detailed metadata information , your best bet is to inject DefaultListableBeanFactory and play around its API . 为了获得Bean的最详细的元数据信息,最好的选择是注入DefaultListableBeanFactory并使用其API。

But your case (ie Get a map for certain type of bean keyed by its beanName) can be simply achieved by injecting ApplicationContext and call its getBeansOfType : 但是,您的情况(即,获取通过其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);
}

Or better yet is to inject Map<String, DataSource> : 或者更好的方法是注入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