Junior — Middle
When there are two beans of the same type with different implementations, how does Spring determine which one to use for dependency injection?
sobes.tech AI
Answer from AI
If there are two beans of the same type with different implementations in the Spring container, then dependency injection without additional information leads to ambiguity, and Spring will throw a NoUniqueBeanDefinitionException.
To specify which bean to use, the following approaches are applied:
@Qualifierannotation — explicitly specifies the name of the desired bean:
@Autowired
@Qualifier("beanName")
private MyService myService;
-
Field or parameter name matches the bean name — Spring attempts to match by name.
-
@Primaryannotation — marks one of the beans as preferred if@Qualifieris not specified:
@Bean
@Primary
public MyService primaryService() {
return new MyServiceImpl1();
}
@Bean
public MyService secondaryService() {
return new MyServiceImpl2();
}
- Using collections — inject all beans of this type into a list or map:
@Autowired
private List<MyService> services;
Thus, Spring determines which bean to use based on explicit instructions via @Qualifier, @Primary, or name, or throws an error if ambiguous.