@Primary – use wisely

On a previous post we revised how to use @Qualifier and how it allows you to disambiguate what Bean to inject, when there are several candidates. However, that is not the the only way you can tell Spring which candidate to take – you can also resort to @Primary.

When you create a bean, you can mark it with @Primary, therefore instructing Spring which bean to give precedence in case of doubt. So given the following beans:

@Bean
@Primary
public Rho rho() {
    return new Rho();
}

@Bean
public Rho rhoSystems() {
    return new Rho();
}

The following injection would work:

@Autowired //Would work as the "rho" bean is marked as "Primary"
public Rho rhoSystemsLda;

Note: as explained on this previous post, the injection would also work without the @Primary, as long as the name of the property matched the name of one of the beans.

@Primary can potentially be mixed with @Qualifier (although it usually makes no sense). In that case, you should note that @Qualifier will take precedence, since it is more specific. So if you had the following beans:

@Bean
@Primary
public Rho rho() {
    return new Rho();
}

@Bean
public Rho rhoSystems() {
    return new Rho();
}

The following injection would still work as intended :

@Autowired
@Qualifier("rhoSystems") //Would inject "rhoSystems" even if not "Primary"
public Rho rhoSystemsLda;

Caution

Although @Primary may be handy now and then, I would generally advise against its use. It may be ok in very small codebases that you know really well and that are maintained by few people, but generally speaking it may be quite dangerous. Setting a bean as primary may mislead people into believing that there is a single candidate for what they are asking for and the one that they may want is not the default one.

Being explicit is always better than being implicit, so I would strongly advise to prefer using @Qualifier, even if it feels that you are adding more boilerplate. I would stress this even more if you are producing a lib/starter – never use @Primary inside one, as it will be very misleading to its users.

That said, do you see legitimate use cases on which you would advise using @Primary? Please do let me know in the comment section!

Discover more from Engineering @ Rho

Subscribe now to keep reading and get access to the full archive.

Continue reading