0 ratings0% found this document useful (0 votes) 23 views8 pagesSa
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, Guide to Spring @Autowired | Bacldung
“
Guide to Spring @Autowired
constancy | jtec- compli:
solutions
Bec
F (httos //adsfreestarcom/?
| written by baeldung htips/wanubaeldung.com/author/baeldung)
Spring (https://wwerbaeldung.com/category/spring) +
‘Spring Core Basics (https://wwwbaeldung.com/tag/spring-core-basics)
‘Spring DI (https://wawbaeldung.com/tag/spring-ai)
Get started with Spring 5 and Spring Boot 2, through the reference Learn
Spring course:
>> LEARN SPRING (/ls-course-start)
hitpsilwa.baeldung.comispring-autowire
veozrti2023 18.48, Guide to Spring @Autowiced | Baeldung
“
y (https /ads freestaccom/?
Uutm_campaignsbrandinggutm .medium-banner&utm_source-baeldung.com&utm.content-baeldung_incontent
2
1. Overview
Starting with Spring 2.5, the framework introduced annotations-criven Dependency Injection The main annotation
of this feature is @Aulowired It allows Spring to resolve and inject collaborating beans into our bean,
Further reading:
Spring Component Scant
1g (/spring-component-scani
9)
Learn about the mechanism bchind Spring component scanning, and how you can tweak ito your own needs
Read more (/spring-component-scanning) >
Intro to Inversion of Control and Dependency Injection with Spring (/inversion-
control-and-dependency-injection-in-spring)
‘A quick introduction tothe concepts of Inversion of Control and Dependency Injection, followed by a simple
demonstration using the Spring Framework
Read more (/Inversion-control-
1d-dependency-injection-in-spring) >
In this tutorial, woll fist take a look at how to enable autowiing and the various ways to autowire beans. Afterward,
‘well talk about resolving bean conflicts using @Qualifier annotation, as well as potential exception scenarios,
2. Enabling @Autowired Annotations
‘The Spring framework enables automatic dependency injection, In other words, by declaring all the bean
dependencies in a Spring configuration file, Spring container can autowire relationships between
collaborating beans, This is called Spring bean autowiring.
“To use Java-based configuration in our application. let's enable annot
configuration
configuration oO
[econponentScan(*com. baeldung.autowire.sampte")
public class aasconfig. ©
1n-driven injection to load our Spring
Alternatively, the annotation (/spring-contextannotation.
contextcomponentscanit = text: The%20%3Ccontext%3Aannotation’%2Dconfig annotation®%eDconfig3E%s20can%20
resolve) is mainly used to activate the dependency injection annotations in Spring XML files
Change is coming, get ready
(automate!)
V wet
(https /ads freestarcom/?
v
hitpsilwa.baeldung.comispring-autowire 28ozrti2023 18.48, Guide to Spring @Autowired | Bavidung
Mevaover Snring Boot introduces the @iSpringBootApplication (/spring-boot-annatations#spring-boot-
appleationannotation. Tris singie annotation ls equivalent to using @Configuration, @EnableAutoConfiguration
ang aComponent8can.
Lets use this annotation in the main class of the application:
public class App { O
,
‘Asa result, when we run this Spring Boot apalication, it will automatically scan the components in the current
package and its sub-packages. Thus it will egister them in Spring's Application Context. and allow us to inject,
beans using @Autowired.
3. Using @Autowired
‘After enabling annotation injection, we ean use autowiring on properties, setters, and constructors,
3.1, @Autowired on Properties
Lets see how we can annotate a property using @Autowired. This eliminates the need for getters and setters.
Stockage de données rentable pour le
cloud hybride
mm 18M
: thtips//adsfreestarcom/?
Fist ets define a fooFormatter bear
conponent("ooFeraatter") O
public class FooFormatter <
public string format) (
return "Fo
Then, welllinject this bean into the FooService bean using @Autowired on the field definition:
I es essere ( O
teu
Asa result, Spring injects fooFormatter when FooService's created.
3.2, @Autowired on Setters
Now lets try adding @Autowired annotation on a setter method,
ntips:fmaew-baeldung.comispring-autowire 38ozrti2023 18.48, Guide to Spring @Autowired | Bavidung
In‘ followirg axarrele, the Setar method is called wit te instance of FaoFormatterwhen FooServiceis
created
pubic clas rcservice{
cites
Pee vol stzoattertecorormaser fotos) ¢
3.3. @Autowired on Constructors
Finally. lets use @Autowired on a constructor.
‘Well see that an instance of FooFormatter's injected by Spring as an argument to the FoaService constructor:
pubic cass rsservee ¢
Tests efter tororeater O
Siar
Mi Feserveetororanier fnrrster) ¢
)
4. @Autowired and Optional Dependencies
When a beans being constructed. the @Autowired dependencies should be available. Otherwise, if Spring
‘cannot resolve a bean for wiring, it wll throw an exception,
‘Consequently, it prevents the Spring container from launching successfully with an exception of the form:
Caused by! org.springfranenork.beans. factory. NoSuchBeanDef initionExcept ion: oO
No qualifying bean of type [con.autowire.sanple.Fo00A0} Fund for dependency:
expected st least 1 bean which qualities se sucowire candidate for this dependency.
Dependency annstations
Gorg. spr ingfranework. beans. Factory annotation. Autowired (requir
rue)
To fix this, we need to declare a bean of the required type:
pubic class Foocervice (
ehotonreeeired © fase) oO
privete Toso daranceasors
5. Autowire Disambiguation
ntips:fmaew-baeldung.comispring-autowire
48ozrti2023 18.48, Guide to Spring @Autowired | Bavidung
By default, Srring resolves @Autqwired entries by type. If more than one bean of the same type is available in
the container, the tramewsrk wil throw a fatal exception.
To resolve this conflict, wo naed total Spring expicty which bean we want to inact.
5.1. Autowiring by @Qualifier
For instance. let's see how we can use the @Qualifer (/s
required bean
{ng-qualifier-annotation) annotation to indicate the
“Nos réunions sont
bien plus vivantes” Pour en savoir plus, regardez cette
WIMP. vidéo
F tom team
(https /ads reestarcom/?
First, well define 2 beans of type Formatter
SoC an Perm tres forte 0
“cain
sith Css rts ntenets Frese O
Meare es
,
Now lets try to inject a Formatterbean into the FooService class:
pte cass Fuser |
tera O
Inour example, there are two concrete implementations of Formatter available for the Spring container. As a result
‘Spring will throw a NoUniqueBeanDefinitionException exception when constructing the FooService.
Caused by: org.springfranenork. beans. factory NoUn‘queBasndef init fonéxcept ion oO
No qualifying bean of type [con.autowire.sanple.Fornatter) %s defined:
expected single matching bean but found 2: Dartornacter, fooFormatter
‘We can avoid this by narrowing the implementation using a @Qualifier annotation:
pubic class FooService (
oeotonred oO
teat or ("fooFormtter")
‘When there are multiple beans of the same type. its a good idea to use @Qualifier to avoid ambiguity.
Please note that the value of the @Qualifer annotation matches with the name declared in the @Component
‘annotation of our FooFormatter implementation
v
ntips:fmaew-baeldung.comispring-autowire
seo2/112028 18.48 Guide to Spring @Autowred | Badung
5.2. Auto irina by Custos Qualifier -
Spring also allows us to ereate our own custom @Qualifier annotation. To do so, we should provide the @Qualifior
annotation with the definition
equatitier oO
rarger({
Elenenciype.FIELD, ElenentType.HETHOD, Elenentlype. VPE, EtenencIype.PARAMETER))
ekerenvion(RotensionPoliey-RUNTINE)
Public interface FormateerType {
String valued);
d
‘Then we can use the FormatterType within various implementations to specify a custom value:
gene 0
Sei ss rxromaee mtenees Fraser {
sear
eforsoterype ("tar")
tconganent, O
DAbUIC Class arFormatter imlenents Formtter(
btte suring format
‘turn "oor
)
Finally, cur custom Qualifier annotation is ready to use for autowiring:
component oO
public class Fooservice {
‘katowired
GormatterType(*Fo0")
Private Frornatter formattery
‘The value specified in the @Target meta-annotation restricts where to apply the qualifer, which in our example
is elds, methods, types, and parameters,
5.3. Autowiring by Name
‘Spring uses the bear's name as a default qualifier value. It willinspect the container and look for a bean with the
‘exact name as the property to autowire it.
Hence, in our example, Spring matches the fooFormatter property name to the FooFormatterimplementation.
‘Therefore, it injects that specific implementation when constructing FooService,
v
ntips:fmaew-baeldung.comispring-autowire oeo2rii2023 18.48 Guide to Spring @Autowited | Bavidung
waters rennin Vi
aise O
erie tr fener
;
6. Conclusion
In this article, we discussed autowiring and the diferent ways to use it. We also examined ways to solve two
‘common autowiting exceptions caused by either a missing bean or an ambiguous bean injection,
“The source code ofthis article is available on the GitHub project
{httpsi//githucom/eugenp/tutorials/tree/master/spring-di-3).
Get started with Spring 5 and Spring Boot 2, through the Learn Spring
course:
>» THE COURSE (/ls-course-ond)
Learning to build your API
with Spring?
Download the E-book (/rest-api-spring-guide)
Comments are closed on this article!
ntips:fmaew-baeldung.comispring-autowire 718ozrti2023 18.48, Guide to Spring @Autowired | Bavidung
“
‘couRSES
SERIES
‘ABOUT
ntips:fmaew-baeldung.comispring-autowire