88 lines
2.2 KiB
Plaintext
88 lines
2.2 KiB
Plaintext
== Why is this an issue?
|
|
|
|
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
|
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
@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
|
|
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
----
|
|
@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();
|
|
}
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* https://docs.spring.io/spring-framework/reference/core/beans/java/bean-annotation.html[Spring Framework - Using the @Bean Annotation]
|
|
* https://docs.spring.io/spring-framework/reference/core/beans/annotation-config/autowired-qualifiers.html[Spring Framework - Using @Qualifier]
|
|
|
|
=== Articles & blog posts
|
|
|
|
* https://www.baeldung.com/spring-qualifier-annotation[Baeldung - Spring @Qualifier Annotation]
|
|
* https://www.baeldung.com/spring-bean-annotations[Baeldung - Spring Bean Annotations]
|
|
|