Senior
How does Spring resolve conflicts when there are two beans of the same type? How to inject dependencies?
sobes.tech AI
Answer from AI
If multiple beans of the same type are defined in the Spring container, an autowiring conflict occurs because Spring cannot unambiguously select the required bean.
How to resolve the conflict:
- Use the
@Qualifierannotation — explicitly specify the name of the bean to be injected.
@Autowired
@Qualifier("beanName")
private MyService myService;
-
Use the name of the field or method parameter that matches the bean name — Spring will attempt to match by name.
-
@Primaryannotation — mark one of the beans as primary, so it will be injected by default.
@Bean
@Primary
public MyService myPrimaryService() {
return new MyServiceImpl1();
}
@Bean
public MyService mySecondaryService() {
return new MyServiceImpl2();
}
- Inject a collection of beans — if you need to work with all implementations:
@Autowired
private List<MyService> services;
Thus, to inject dependencies in case of conflict, you should either specify the specific bean using @Qualifier, or use @Primary, or inject a collection of beans.