Home > database >  Dependency injection with @Qualifier
Dependency injection with @Qualifier

Time:10-11

Suppose the following code:


@Service
public class SearchService {

    @Autowired
    DependencyService dependencyService;
}

@Service
public class DependencyService {
    private final Util util;


    DependencyService(Util util){
        this.util = util;
        execute();
    }
    public void execute(){
        util.execte();
    }


}
@Component
public class ConcreteUtil implements Util{
    @Override
    public void execte() {
        System.out.println("I'm the first concrete Util");
    }
}
@Component
public class SecondConcreteUtil implements Util{
    @Override
    public void execte() {
        System.out.println("I'm the second concrete Util");

    }
}

In Plain Java I can do something like this:


public class SearchService {


    DependencyService first = new DependencyService(new ConcreteUtil());
    DependencyService second = new DependencyService(new SecondConcreteUtil());

}

But in Spring, it's not resolved by the client. We instruct Spring which bean to take from inside DependencyService:

   DependencyService(@Qualifier("concreteUtil")Util util){
        this.util = util;
        execute();
    }

And not like that:


 @Autowired
 @Qualifier("concreteUtil")
 DependencyService dependencyService;

Why? To me this approach sounds like the opposite of decoupling. What do I miss? And how can Plain Java's result be achieved?

Edit: I want this behaviour

public class SomeSerice {
 
    DependencyService firstConcrete = new DependencyService(new ConcreteUtil());
}

public class OtherService {
 
    DependencyService SecondConcrete = new DependencyService(new SecondConcreteUtil());
}

So I can reuse the code

CodePudding user response:

You can declare multiple beans of type Dependency service inside some configuration class, like

@Qualifier("ConcreteUtilDepService")
@Bean
public DependencyService concreteUtilDS(@Qualifier("ConcreteUtil")Util util){
   return new DependencyService (util);
}
  • Related