Sobes.tech
Junior — Middle

How can two instances of the same service be implemented in the context of Dependency Injection?

sobes.tech AI

Answer from AI

To implement two instances of the same service in the context of Dependency Injection in Java, you can use:

  1. Named beans (Qualifier) — with the @Qualifier annotation, you can distinguish between different implementations or instances of the same interface.

  2. Configuration methods with different names — in the configuration class, you can declare two methods that create different instances of the service.

Example using Spring and @Qualifier:

public interface MyService {
    void perform();
}

@Service
@Qualifier("serviceA")
public class MyServiceImplA implements MyService {
    public void perform() {
        System.out.println("Service A");
    }
}

@Service
@Qualifier("serviceB")
public class MyServiceImplB implements MyService {
    public void perform() {
        System.out.println("Service B");
    }
}

@Component
public class Consumer {
    private final MyService serviceA;
    private final MyService serviceB;

    public Consumer(@Qualifier("serviceA") MyService serviceA, @Qualifier("serviceB") MyService serviceB) {
        this.serviceA = serviceA;
        this.serviceB = serviceB;
    }

    public void useServices() {
        serviceA.perform();
        serviceB.perform();
    }
}

Thus, you can inject two different instances of the same interface and use them as intended.

How can two instances of the same service be… - sobes.tech