MS13
MS13

Reputation: 377

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...

Upvotes: 1

Views: 445

Answers (2)

Raghvendra Garg
Raghvendra Garg

Reputation: 515

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});
}

Upvotes: 0

dehasi
dehasi

Reputation: 2773

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());

Upvotes: 1

Related Questions