繁体   English   中英

在没有xml配置的情况下,在地图/列表中使用大量的bean实例进行注入

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM