Sobes.tech
Senior

Spring: How to resolve a conflict of beans of the same class?

sobes.tech AI

Answer from AI

If multiple beans of the same class are declared in the Spring container, a conflict arises during autowiring because Spring cannot unambiguously determine which bean to use.

Solutions:

  1. Use the @Qualifier annotation

    When injecting dependencies, explicitly specify the name of the required bean:

    @Autowired
    @Qualifier("beanName")
    private MyClass myClass;
    
  2. Assign unique names to beans

    When declaring a bean via @Bean or @Component, you can specify a name:

    @Component("beanName")
    public class MyClass { ... }
    
  3. Use @Primary

    Mark one of the beans as primary so that Spring chooses it by default:

    @Bean
    @Primary
    public MyClass primaryBean() { ... }
    
  4. Inject a collection of beans

    If you need to work with all beans of this type:

    @Autowired
    private List<MyClass> myClasses;
    
  5. Use explicit configuration

    In configuration classes, you can explicitly create and name beans.

Thus, the conflict is resolved either by specifying which bean to use or by organizing the code so that Spring can unambiguously select the required bean.