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:
-
Use the
@QualifierannotationWhen injecting dependencies, explicitly specify the name of the required bean:
@Autowired @Qualifier("beanName") private MyClass myClass; -
Assign unique names to beans
When declaring a bean via
@Beanor@Component, you can specify a name:@Component("beanName") public class MyClass { ... } -
Use
@PrimaryMark one of the beans as primary so that Spring chooses it by default:
@Bean @Primary public MyClass primaryBean() { ... } -
Inject a collection of beans
If you need to work with all beans of this type:
@Autowired private List<MyClass> myClasses; -
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.