Sobes.tech
Junior — Middle

How is a specific implementation of the Bean interface in Spring integrated and configured considering the conditions?

sobes.tech AI

Answer from AI

In Spring, the injection of a specific implementation of an interface with conditions is usually implemented using annotations and configurations that allow selecting the required bean depending on the profile, property, or other conditions.

Main methods:

  • @Primary — marks a bean as preferred if there are multiple implementations of an interface.
  • @Qualifier — allows explicitly specifying which implementation to inject.
  • @Profile — the bean is active only under a specific application profile.
  • @Conditional — a more flexible way to create beans when certain conditions are met.

Example using @Qualifier:

public interface Service {
    void execute();
}

@Component("implA")
public class ServiceImplA implements Service {
    public void execute() { System.out.println("ImplA"); }
}

@Component("implB")
public class ServiceImplB implements Service {
    public void execute() { System.out.println("ImplB"); }
}

@Component
public class Client {
    private final Service service;

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

Thus, it is possible to inject the required implementation of an interface depending on conditions, profiles, or explicit directives.