Sobes.tech
Middle

Will the Spring context rise or fall if there is an interface with two implementations and a bean into which this interface is injected without specifications?

sobes.tech AI

Answer from AI

If there is an interface with two implementations in the Spring context, and you try to inject this interface without clarification (for example, without using @Qualifier or @Primary annotations), the context will not start and will fail with a NoUniqueBeanDefinitionException error.

Spring will not be able to unambiguously determine which bean to use, as there are several. To avoid this error, you need to:

  • Use @Primary on one of the beans to make it the preferred one.
  • Use @Qualifier with the specific bean name during injection.

Example:

@Component
@Primary
public class ImplA implements MyInterface {}

@Component
public class ImplB implements MyInterface {}

@Component
public class MyService {
    private final MyInterface myInterface;

    public MyService(MyInterface myInterface) {
        this.myInterface = myInterface; // ImplA will be injected because of @Primary
    }
}
Will the Spring context rise or fall if there is an… - sobes.tech