In Spring Framework, the @Qualifier
annotation is typically used to disambiguate between multiple beans of the same type when
auto-wiring dependencies. It is not necessary to use @Qualifier
when defining a bean using the @Bean
annotation because the
bean’s name can be explicitly specified using the name
attribute or derived from the method name. Using @Qualifier
on
@Bean
methods can lead to confusion and redundancy. Beans should be named appropriately using either the name
attribute of
the @Bean
annotation or the method name itself.
Noncompliant code example
@Configuration
public class MyConfiguration {
@Bean
@Qualifier("myService")
public MyService myService() {
// ...
return new MyService();
}
@Bean
@Qualifier("betterService")
public MyService aBetterService() {
// ...
return new MyService();
}
@Bean
@Qualifier("evenBetterService")
public MyService anEvenBetterService() {
// ...
return new MyService();
}
@Bean
@Qualifier("differentService")
public MyBean aDifferentService() {
// ...
return new MyBean();
}
}
Compliant solution
@Configuration
public class MyConfiguration {
@Bean
public MyService myService() {
// ...
return new MyService();
}
@Bean(name="betterService")
public MyService aBetterService() {
// ...
return new MyService();
}
@Bean(name="evenBetterService")
public MyService anEvenBetterService() {
// ...
return new MyService();
}
@Bean(name="differentService")
public MyBean aDifferentService() {
// ...
return new MyBean();
}
}