简体   繁体   中英

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) ? 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 {
...
}

PS For simplification we may assume first that all instances implement the same interface, but this will not always be true...

You can use a bean factory to get access to all necessary beans

@Autowired
private ListableBeanFactory beanFactory;

beansOfType.getBeansOfType() returns a map BeanName -> Bean .

You just need to know bean names, which you want to "inject." List necessaryBeanNames;

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
public List<YourInterface> getList(@Qualifier("yourCherryPickedInterfaceImpl1") YourInterface yourCherryPickedInterfaceImpl1, @Qualifier("yourCherryPickedInterfaceImpl2") YourInterface yourCherryPickedInterfaceImpl2) {
    return Arrays.asList(new YourInterface[]{yourCherryPickedInterfaceImpl1, yourCherryPickedInterfaceImpl2});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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