Sobes.tech
Junior — Middle

How to perform dependency injection by a specific interface field in Spring if it has two implementations?

sobes.tech AI

Answer from AI

In Spring, if an interface has two implementations and you need to inject a dependency for a specific one, you can use the @Qualifier annotation to specify which implementation to inject.

Example:

public interface Service {
    void execute();
}

@Service
@Qualifier("serviceA")
public class ServiceA implements Service {
    public void execute() { /* implementation A */ }
}

@Service
@Qualifier("serviceB")
public class ServiceB implements Service {
    public void execute() { /* implementation B */ }
}

@Component
public class Client {
    private final Service service;

    @Autowired
    public Client(@Qualifier("serviceA") Service service) {
        this.service = service;
    }
}

Thus, with @Qualifier, you can explicitly specify which implementation to inject when there are multiple.

How to perform dependency injection by a specific… - sobes.tech