Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Injecting multiple implementations to a single service in Spring

I have a servive interface called DataSource and more than 1 implementations like XMLDataSource, DataBaseDataSource etc.

I want to inject(Spring) appropriate implementation to my Struts2 Action based on some user interaction like if User clicks on XML then I need to use XML implementation. Spring has been used for DI framework.

@Autowired
private DataSource dataSource;

Please suggest what is best way to achieve this.

like image 329
Tapas Jena Avatar asked Nov 28 '22 17:11

Tapas Jena


1 Answers

If you need to choose the implementation at runtime, based on a user interaction, you have to autowire all the possible implementations of the DataSource interface.

When you autowire a List of the desired interface, Spring will populate the list automatically with an instance of each implementation.

@Autowired
private List<DataSource> dataSources;

It is up to you, then to select the right interface based on the user interaction.

If you need to discriminate based on the bean name, you can also choose to autowire the dictionary of the DataSource object indexed on bean name.

@Autowired
private Map<String, DataSource> dataSourceIndex;

This is available from the 2.5 version of Spring, and you can find here the autowire documentation

like image 156
MPavesi Avatar answered May 22 '23 08:05

MPavesi