Sobes.tech
Senior

Question 5. There are two implementations of the interface, what happens when injecting a variable of interface type into a Spring bean? - The first implementation will be in the variable - A compile-time error will occur - A context startup error will occur - It depends on the Spring version

sobes.tech AI

Answer from AI

If there are two implementations of the same interface in the Spring context, and you try to inject a dependency by interface type without additional qualification (for example, without using @Qualifier or @Primary), an error will occur during application startup at the context initialization stage. Spring will not be able to unambiguously determine which implementation to use and will throw a NoUniqueBeanDefinitionException.

Example solution:

@Component
@Primary
public class FirstImplementation implements MyInterface { ... }

@Component
public class SecondImplementation implements MyInterface { ... }

// Then, when injecting
@Autowired
private MyInterface myInterface; // FirstImplementation will be injected

Or using @Qualifier:

@Autowired
@Qualifier("secondImplementation")
private MyInterface myInterface;

Therefore, the correct answer is: An error will occur during context startup.