[英]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.