Home > front end >  Is it still loose coupling if we use @qualifier
Is it still loose coupling if we use @qualifier

Time:02-08

we use interface for autowiring service into controller

this is for loose coupling , coz the interface can hold object of any of its implementations. so no need to write the implementation name and create tight coupling.

however when we have more than one implementations for an interface, we write the @qualifier .

my question is if we have to write qualifier to tell which implementation needs to be injected, then should we still call it loose coupling??

class ServiceInterface {
interfaceMethod();
}

implementation 1:
    @component("service1")
    class ServiceImpl1 implements ServiceInterface {
    interfacemethod(){
        
    }
    }
implementation 2:
    @component("service2")
    class ServiceImpl2 implements ServiceInterface {
    interfaceMethod(){
        
    }
    
   now  only instead of directly creating Object of ServiceImpl1() using new 
   ServiceImpl1 obj = new ServiceImpl1();
    we write in
    class Controller {
    @autowired
    @qualifier("service1")
    ServiceInterface se;
    
    sc.interfaceMethod();
    
    }

CodePudding user response:

Partially yes, because the component that uses the injected qualified bean still didn't create it or handle its lifecycle.

But indeed using @Qualifier creates some sort of coupling. If you want to avoid this, consider making one of your ServiceInterface beans the primary implementation for the interface annotating its class with @Primary as follows:

@Component
@Primary
class ServiceImpl1 implements ServiceInterface {
    interfacemethod(){
        
    }
}

With this, every time you need a ServiceInterface implementation but you don't actually specify which one you want (using @Qualifier) the primary one is injected by Spring.

CodePudding user response:

Even though you are using the @Qualifier annotation you are still using inversion of control to let the framework manage your dependencies.

Furthermore, lets say you wouldn't autowire this implementation but use 'new' to create your object.

When the implementation changes you would need to update all the places where this is created. However, with dependency injection you wouldn't need to do so. Therefore you still have the advantages of dependency injection with regards to loose coupling.

If you would like to have your implementation less coupled with your target class then you could do a few things

  1. Use @Primary for a bean to determine the default implementation.
  2. Autowire your implementations into a List<ServiceInterface>
  3. Use Spring's ObjectFactory to determine which bean to use at runtime
  4. Use Profiles to determine which bean to autowire
  •  Tags:  
  • Related