Middle — Middle+
What happens if you inject a dependency through an interface that is implemented by two different implementations?
sobes.tech AI
Answer from AI
If you pass an interface to a dependency injection system (for example, Spring) that is implemented by two different implementations, and try to inject this dependency without additional configuration, an ambiguity will occur — the container will not be able to determine which implementation to use.
What happens:
- During autowiring by interface type, the container will find multiple candidates.
- This will lead to a
NoUniqueBeanDefinitionExceptionor a similar error indicating that multiple beans of the same type are found.
How to solve the problem:
- Use the
@Qualifierannotation to specify the exact bean name. - Mark one of the implementations as
@Primaryso it is chosen by default. - Inject a list or collection of all implementations if you need to work with all of them.
Example with @Qualifier:
@Autowired
@Qualifier("firstImplementation")
private MyInterface myDependency;
Thus, when there are multiple implementations of an interface, it is necessary to explicitly specify which one to use to avoid conflicts during injection.