Sobes.tech
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 NoUniqueBeanDefinitionException or a similar error indicating that multiple beans of the same type are found.

How to solve the problem:

  • Use the @Qualifier annotation to specify the exact bean name.
  • Mark one of the implementations as @Primary so 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.