Sobes.tech
Junior — Middle

How does Spring determine which interface implementation to choose when using @Autowired with multiple options?

sobes.tech AI

Answer from AI

When there are multiple implementations of the same interface in Spring, and the @Autowired annotation is used, the framework tries to determine which implementation to inject based on the following rules:

  1. By bean name: Spring looks for a bean whose name matches the name of the field or parameter where the injection occurs.
  2. @Qualifier annotation: If there are multiple candidates, you can explicitly specify the desired bean using @Qualifier("beanName").
  3. @Primary annotation: If one of the beans is marked as @Primary, it will be chosen by default.
  4. Exception on ambiguity: If none of the conditions help, Spring throws a NoUniqueBeanDefinitionException.

Example:

@Component
@Primary
public class ServiceImpl1 implements MyService {}

@Component
public class ServiceImpl2 implements MyService {}

@Autowired
private MyService myService; // ServiceImpl1 will be injected due to @Primary

@Autowired
@Qualifier("serviceImpl2")
private MyService myService2; // explicitly specifies ServiceImpl2
How does Spring determine which interface… - sobes.tech