Bharateesh Diggavi
Bharateesh Diggavi

Reputation: 21

Conditionally choosing implementation in spring boot

I have two implementations for a single interface and I segregated them using @Qualifier("IMP1") and @Qualifier("IMP2") and this is the case for most of the interfaces in my application.

And the requirement is autowire "IMP2" of an interface if available or autowire "IMP1".

As of now, I'm handling like

    @Autowired(required = false)
    @Qualifier("IMP1")
    HelloService imp1Service;

    @Autowired(required = false)
    @Qualifier("IMP2")
    HelloService imp2Service;


    @GetMapping("/hello")
    public String hello() {
        if(l1Service != null){
            return imp2Service.getString();
        } else {
            return imp1Service.getString();
        }
    }

But this is not an elegant way as I've to check for all interfaces in the same way. how to do this

Upvotes: 0

Views: 1240

Answers (1)

Ashish Lahoti
Ashish Lahoti

Reputation: 978

Consider using @ConditionalOnMissingBean on IMP1Service. In this case, IMP1Service will only be loaded in spring context when IMP2Service is missing. This will make sure that you have only implementation of HelloService interface in spring context i.e. either IMP1Service or IMP2Service

@Service
@ConditionalOnMissingBean(IMP2Service.class)
class IMP1Service implements HelloService {
    // TODO
}

Since you have only one implementation of HelloService, you don't need to use @Qualifier annotation anymore

    @Autowired(required = false)
    HelloService impService;

    @GetMapping("/hello")
    public String hello() {
        return impService.getString();
    }

You can read more about Conditional Annotations here:- https://codingnconcepts.com/spring-boot/conditional-annotations-in-spring-boot/

Upvotes: 3

Related Questions