north
north

Reputation: 91

Service Implementation - how to choose which service implementation will be used based on application.properties attribute?

I have two service implementations:

Service interface:

/** 
* Service used for resolving external ID for the entity.
*/
public interface ResolveService {
   String valueToResolve(String id);
}

Implementation of Service - A:

@Service
public class ResolveServiceAImpl implements {

  @Override
  public String valueToResolve(String id) {
    // grpc impl...
  }

}

Implementation of Service - B:

@Service
public class ResolveServiceBImpl implements {

  @Override
  public String valueToResolve(String id) {
    // jpa impl...
  }

}

For now, this is resolved with @Qualifier and this implementation works:

   @Qualifier("resolveServiceBImpl")
   @Autowired
   private ResolveService resolveService;

The problem for me is that I don't want to define in every class String value of @Qualifier. I would like to define @Qualifier value in one place, let's say in application.properties file.

application.properties:

resolve.service.active=resolveServiceBImpl

This implementation is not working:

   @Value("'${resolve.service.active}')")
   private String resolveServiceActive;

   @Qualifier(resolveServiceActive)
   @Autowired
   private ResolveService resolveService;

The error I am getting is Attribute value must be constant. Cannot find bean with qualifier null.

Is there any other way how to resolve @Qualifier value, so that I need to assign it manually in every class separately?

Upvotes: 3

Views: 865

Answers (1)

north
north

Reputation: 91

@jonrsharpe tnx for answer.

I resolved it with a @Profile.

SOLUTION:

Service A Implementation:

@Service
@Profile("A")
public class ResolveServiceAImpl implements ResolveService {...

Service B Implementation:

@Service
@Profile("B")
public class ResolveServiceBImpl implements ResolveService {...

and application.properties:

spring.profiles.active=A

And for the test I used @ActiveProfiles("A").

This solved my problem.

Upvotes: 4

Related Questions