java / beginner
Snippet
Handling Multiple Beans with @Primary
If multiple beans of the same type exist, @Primary gives precedence to a specific bean. This avoids ambiguity errors during dependency injection.
snippet.java
java
1
2
3
4
5
6
@Component@Primarypublic class DefaultService implements MessageService { }@Componentpublic class SecondaryService implements MessageService { }
spring
Breakdown
1
@Primary
Specifies the default bean to use when multiple candidates are available.