Sobes.tech
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:

  1. @Qualifier annotation — explicitly specifies the name of the desired bean:
@Autowired
@Qualifier("beanName")
private MyService myService;
  1. Field or parameter name matches the bean name — Spring attempts to match by name.

  2. @Primary annotation — marks one of the beans as preferred if @Qualifier is not specified:

@Bean
@Primary
public MyService primaryService() {
    return new MyServiceImpl1();
}

@Bean
public MyService secondaryService() {
    return new MyServiceImpl2();
}
  1. 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.