Issue
I have a case , in which I am supposed to make spring boot webservice which will fetch data from any of source & My rest api is (/fetchData/{src}) where src is path variable & It is name of source(database) e.g casandra , mongodb or any other nosql .. so based on that I want to initialized bean to make connection with that database . so can we use @Conditional bean in such case. but problem with that is , @Conditional bean check condition based on property file values & here we have to apply condition based on rest api's path param. So should I use @Conditional or any other design pattern like factory ?
Solution
You cannot use @Conditional
, since it is evaluated at startup time, while the path parameter value is only known at runtime.
There are many solutions you can do. You could use a simple factory or chain.
Another example I used a few time:
Create an interface
public interface MyDataSource {
SomeOutputData query(Data someDataIn);
boolean supports(String pathParam);
}
Create all implementation (Cassandra, MongoDB, etc.) and inject a list of these into your service
@Autowired
private List<MyDataSource> dataSources;
Then you can choose the proper DataSource, something like this:
dataSources.stream()
.filter(dataSource -> dataSource.doesSupport(pathParam)
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("No datasource"))
.query(dataIn);
Answered By - helospark