Search code examples
spring-bootdependency-injectionbackendautowired

What is the need for primary if Qualifier can do the work?


I understand that using @Primary gives a default choice. But what is the harm in always specifying your preference using @Qualifier? As, in case if both are used then priority goes to @Qualifier. And if there is nothing wrong then Why is even @Primary needed?

Suppose i have a piece of code lets say :

@Component
@Primary
public class FooFormatter implements Formatter {
    //...
}

@Component
public class BarFormatter implements Formatter {
    //...
}

if i want to inject any if the above two i can always do:

@Qualifier("FooFormatter")
@Autowired
private Formatter formatter;

//OR

@Qualifier("BarFormatter")
@Autowired
private Formatter formatter;

Solution

  • @Primary allows you to override a bean that would be present by default. This can be used to override a default/fallback implementation with something more specific.

    Example use case: have a default (maybe even no-op) implementation, and a special implementation activated by a configuration property (with @ConditionalOnProperty).

    With @Qualifier, you're dealing with known variants of an bean, and pick an appropriate one. Example: differently configured RestTemplate beans, one for each system you connect to.