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

  1. Use the @Qualifier annotation — explicitly specify the name of the bean to be injected.
@Autowired
@Qualifier("beanName")
private MyService myService;
  1. Use the name of the field or method parameter that matches the bean name — Spring will attempt to match by name.

  2. @Primary annotation — 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();
}
  1. 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.

How does Spring resolve conflicts when there are two… - sobes.tech