[英]Inject using spring lots of beans instances in a map/list without xml configuration
如何使用spring注入java bean的Map(或List),一些不同類的實例但不使用xml配置(我們應該只使用注釋)? 我希望能夠通過名稱或實現類來指定要在該映射中注入的特定實例
實例將使用以下內容聲明:
@Component(“instanceA”)公共類A實現I {
...
}
PS為簡化起見,我們首先假設所有實例都實現相同的接口,但這並不總是正確的......
您可以使用bean工廠來訪問所有必需的bean
@Autowired
private ListableBeanFactory beanFactory;
beansOfType.getBeansOfType()
返回一個映射BeanName -> Bean
。
你只需要知道你要“注入”的bean名稱。 列出必要的BeanNames;
然后,您只能服用必要的豆子。
Map<String, YourInterface> beansOfType = beanFactory.getBeansOfType(YourInterface.class);
List<YourInterface> necessaryBeanNames.stream().map(b-> beansOfType.get(b)).filter(b -> b != null).collect(toList());
目前尚沒有可以為您完成此操作的注釋,但是您可以使用@Bean和@Qualifier獲得所需的結果。
@Bean
public List<YourInterface> getList(@Qualifier("yourCherryPickedInterfaceImpl1") YourInterface yourCherryPickedInterfaceImpl1, @Qualifier("yourCherryPickedInterfaceImpl2") YourInterface yourCherryPickedInterfaceImpl2) {
return Arrays.asList(new YourInterface[]{yourCherryPickedInterfaceImpl1, yourCherryPickedInterfaceImpl2});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.