0 ratings0% found this document useful (0 votes) 31 views7 pagesS 8
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
ozrti2023 18.48, ‘Spring @Qualier Annotation | Baelsung
“
The Spring @Qualifier Annotation
Cee eee)
Ragjster now to NowattsDatz
ata Scientists
Great - Cont Keri
—
F (httos //adsfreestarcom/?
Last updated: September 30, 20
| written by baeldung htips/wanubaeldung.com/author/baeldung)
Spring https://awrwbaeldung.com/category/spring) +
Spring Annotations htips:// wwwbaeldung com/tag/sping-annotations)
‘Spring Core Basics (https://wwwbaeldung.com/tag/spring-core-basics)
Get started with Spring 5 and Spring Boot 2, through the reference Learn
Spring course:
>> LEARN SPRING (/ls-course-start)
“Nos réunions sont
Bion plus vivantos"™ Pour en savoir plus, regardez cette
vidA©o
on ~ v
hitpssivww-baeldung.comispring-qualfer-annotation weozrti2023 18.48, ‘Spring @Qualifer Annotation | Baeldung
mo OU
y thttps:/ads freestarcom/?
utm_campaign-brandinggutm . medium-banner&utm_source-baeldung.com&ulm content-baeldung_incontent
=
. Overview
In this tutorial, well explore what the @Qualifier annotation can help us with, which problems it solves, and how
touseit,
Further reading:
Spring @Primary Annotation (/spring-primary)
Leatn how to use Spring's Primary annotation to give preference to beans when autowiting
Read more (/spring-primary) >
Wiring in Spring: @Autowired, @Resource and @Inject (/spring-annotations-
resource-inject-autowire)
This artcte wil compare and contrast
aalnject and @Autowired annotations.
2 use of annotations related to dependency injection, namely the @Resource,
Read more (/spring-annotations-resource-injet-autowire) >
@Lookup Annotation in Spring (/spring-lookup)
Learn how to efectvely use the Lookup annotation in Spring for procedural injection,
Read more (/spring-Lockup) —>
‘Well also explain how its diferent from the @Primary annotation, and from autowiring by name,
Digital train data
TF ration
y (https /ads freestarcom/?
Uutm_campaign-brandinggutm .medium-banner8utm -source-baeldung.com&utm cont
2
2. Autowire Need for Disambiguation
baeldung_incontent
‘The @Autowired (/spring-autowire) annotation is a great way of making the need to inject a dependency in Spring
explicit Although its useful, there are use cases for which this annotation alone isnt enough for Spring to
Understand which bean to inject.
By default, Spring resolves autowired entries by type.
Hf more than one bean of the same type is available in the container, the framework will throw
‘NoUniqueBeanDefinitionException. indicating that more than one bean is available for autowiring.
hitpssivww-baeldung.comispring-qualifer-annotation anozrti2023 18.48, ‘Spring @Qualier Annotation | Baelsung
“
. (https /adssreestarcom/?
Lets imagine a stuation in which two possible candidates exist for Spring to inject as bean collaborators in a given.
instance
component("foarernatter™ oO
public class FooFornatter “mplenents Fornatter (
public String forme) {
return "Yoo":
y
eomponent("harForeatter")
public class BarFormatter “melexents Fornatter
public String formt() (
return "bar's
,
,
component
public class Fooservice {
anutowired
Private Fornatter formatter;
Ifwe ty to load FooService into our context, the Spring framework will throw a NoUniqueBeanDefinitionException.
‘This is because Spring doesn't know which bean to inject To avoid this problem, there are several solutions; the
@Qualifier annotation is one of them,
3. @Qualifier Annotation
By using the @@ualifer annotation, we can eliminate the issue of which bean needs to be injected.
Lets revisit our previous example to see how we solve the problem by including the @Qualifer annotation to
indicate which bean we want to use:
public class FosService { oO
enutowired
‘aqua Fer ("¥ooFormacter")
Private Frornatter formatters
By including the @Qualiffer annotation, together with the name of the specific implementation we want to use, in
this example Foo. we can avoid ambiguity when Spring finds multiple beans of the same type.
itpsuwaew-baeldung.comlspring-quaifer-annotation anozrti2023 18.48, ‘Spring @Qualier Annotation | Baelsung
“
(https /adssreestarcom/?
\We need to take into consideration that the qualifier name to be used is the one declared in the @Component
annotation.
Note that we could have also used the @Qualifor annotation on the Formattorimplementing classes. instead of
‘specifying the names in thelr Component annotations, to obtain the same effect
component oO
qualifier ("fooForeatter")
public class FooFormatter ‘mplenents Formatter (
WN
,
component
qualifier (*barFormatter"
public class Barrormatter ‘mplenents Formatter {
Ww
y
4. @Qualifiervs @Primary
There's ancther annotation called @Primary (/spring-primary) that we can use to decide which bean to inject when
ambiguity is present regarding dependency injection
‘This annotation defines a preference when multiple beans of the same type are present. The bean associated
with the @Primary annotation will be used unless otherwise indicated
Lets see an example
itpsuwaew-baeldung.comlspring-quaifer-annotationozrti2023 18.48, Spring @Qualier Annotation | Baeldung
Figur cin “ oO
public class Config. ¢
etean
Fublic Employee joménployee() {
return new Exployee( "John
)
ean
errimary
Public Enployee tonyEnployes() {
return new enployee("'ony"
Inthis example, both methods return the same Employee type. The bean that Spring will injects the one returned
by the method tonyEmployee. This is because it contains the @Primary annotation, This annotation is useful when
‘we want to specify which bean of a certain type should be injected by default.
If we require the other bean at some injection point, we would need to specifically inicate it. We can do that via
the @Quatifer annotation, For instance, we could specify that we want to use the bean returned by the
JohnEmployee method by using the @Qualifer annotation.
Its worth noting that if both the @Qualifier and @Primary annotations are present, then the @Qualifier
annotation will have precedence. Basically. @Primarydefines a default, while @Qualiferis very specific.
Lets look at another way of using the Primary annotation, this time using the initial example:
‘@Component Oo
@erinary
public class FooFormatter ‘mslenents Formatter {
We
d
component
public class BarFormatter ‘mplonents Formatter {
We
)
In this case, the @Primary annotation is placed in one of the implementing classes, and will disambiguate the
scenario.
5. @Qualifier vs Autowiring by Name
Another way to decide between multiple beans when autowiring, is by using the name of the field to inject. This is
the default in case there are no other hints for Spring. Let's see some code based on our intial example:
public class FooService oO
utowi red
Private Fornatter foorornatter;
In this case, Spring will determine that the bean to inject is the FooFormatter one, since the field name is matched
to the value that we used in the @Component annotation for that bean.
6. Conclusion
Inthis article, we described the scenarios where we need to disambiguate which beans to inject. In particular, we
‘examined the @Quatifer annotation, and compared it with other similar ways of determining which beans need to
be used.
v
itpsuwaew-baeldung.comlspring-quaifer-annotation sro2rii2023 18.48 ‘Spring @Qualier Annotation | Baelsung
“
. Ihttps//adsfreestarcom/?
‘As usual, the complete code for this article is available over on GitHub
{httpsi//githucom/eugenp/tutorials/tree/master/spring-di
Get started with Spring 5 and Spring Boot 2, through the Learn Spring
course:
>» THE COURSE (/ls-course-end)
Learning to build your API
with Spring?
Download the E-book (/rest-api-spring-guide)
‘Comments are closed on this article!
htipsifwnew.baeldung,comspring-qualiferannotationozrti2023 18.48, ‘Spring @Qualier Annotation | Baelsung
“
‘couRSES
SERIES
‘ABOUT
htipsifwnew.baeldung,comspring-qualiferannotation
W