Rahul Rabhadiya Rahul Rabhadiya - 3 months ago 21
reST (reStructuredText) Question

Can we implement @Conditional Bean based on rest api's path param in spring boot?

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 ?

Answer Source

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

 private List<MyDataSource> dataSources;

Then you can choose the proper DataSource, something like this:

      .filter(dataSource -> dataSource.doesSupport(pathParam)
      .orElseThrow(() -> new IllegalArgumentException("No datasource"))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download