简体   繁体   English

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

[英]Inject using spring lots of beans instances in a map/list without xml configuration

How can I inject in a Map (or a List) of a java bean , instances of some different classes using spring but without using xml configurations (we should use only annotations) ? 如何使用spring注入java bean的Map(或List),一些不同类的实例但不使用xml配置(我们应该只使用注释)? I want to be able to specify the particular instances to be injected in that map by name or by implementing class 我希望能够通过名称或实现类来指定要在该映射中注入的特定实例

Instances will be declared using something like this: 实例将使用以下内容声明:

@Component ("instanceA") public class A implements I { @Component(“instanceA”)公共类A实现I {
... ...
} }

PS For simplification we may assume first that all instances implement the same interface, but this will not always be true... PS为简化起见,我们首先假设所有实例都实现相同的接口,但这并不总是正确的......

You can use a bean factory to get access to all necessary beans 您可以使用bean工厂来访问所有必需的bean

@Autowired
private ListableBeanFactory beanFactory;

beansOfType.getBeansOfType() returns a map BeanName -> Bean . beansOfType.getBeansOfType()返回一个映射BeanName -> Bean

You just need to know bean names, which you want to "inject." 你只需要知道你要“注入”的bean名称。 List necessaryBeanNames; 列出必要的BeanNames;

Then you can take only necessary beans. 然后,您只能服用必要的豆子。

Map<String, YourInterface> beansOfType = beanFactory.getBeansOfType(YourInterface.class);

List<YourInterface> necessaryBeanNames.stream().map(b-> beansOfType.get(b)).filter(b -> b != null).collect(toList());

there is no already present annotation which can do this for you but you can use @Bean and @Qualifier to get the desired results. 目前尚没有可以为您完成此操作的注释,但是您可以使用@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