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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With