0 day streak
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
@Primary
public class DefaultService implements MessageService { }
@Component
public class SecondaryService implements MessageService { }
spring
Breakdown
1
@Primary
Specifies the default bean to use when multiple candidates are available.