e
c
t
i
o
n
Simple
Object
The Spring Triangle
!
s
p
e
c
t
-
"
r
i
e
n
t
e
d
#
r
o
g
r
$
m
m
i
n
g
%nterprise Ser&ice !bstr$ctions
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
8+4
,eveloping an +pplication from $lain %ava
O"/ects
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Spring Quick Start
Introducing the Spring Application Context and
Springs XML-based configuration language
2
Topics in this session
Spring quick strt
!riting bean definitions
" Configuring ob#ects
" $oing be%ond constructor instantiation
Creating an application context
Su&&ar%
3
'o( Spring !orks
Spring
ApplicationContext
Configuration
Instructions
Your Application Classes (POJOs)
Fully configured
application system
Ready for use
Creates
4
)our Application Classes
public class ransferSer!iceImpl implements ransferSer!ice "
public ransferSer!iceImpl(Account#epository ar) "
t$is%account#epository & ar'
(
)
(
public class JdbcAccount#epository implements Account#epository "
public JdbcAccount#epository(*ataSource ds) "
t$is%dataSource & ds'
(
)
(
+eeded to load accounts from t$e database
+eeded to perform money transfers
bet,een accounts
5
Configuration Instructions
-beans.
-bean id&/transferSer!ice0 class&/app%impl%ransferSer!iceImpl0.
-constructor1arg ref&/account#epository0 2.
-2bean.
-bean id&/account#epository0 class&/app%impl%JdbcAccount#epository0.
-constructor1arg ref&/dataSource0 2.
-2bean.
-bean id&/dataSource0 class&/com%oracle%3dbc%pool%Oracle*ataSource0.
-property name&/4#50 !alue&/3dbc6oracle6t$in67local$ost689:86;A+<0 2.
-property name&/user0 !alue&/moneytransfer1app0 2.
-2bean.
-2beans.
6
Creating and *sing the
Application
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(/application1config%xml0)'
22 5oo> up t$e application ser!ice interface
ransferSer!ice ser!ice &
(ransferSer!ice) context%get;ean(/transferSer!ice0)'
22 4se t$e application
ser!ice%transfer(ne, ?onetaryAmount(/@AA%AA0)B /80B /:0)'
7
Inside the Spring Application
Context
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(/application1config%xml0)'
Application Context
Oracle*ataSource
dataSource
JdbcAccount#epository
account#epository
ransferSer!iceImpl
transferSer!ice
8
Quick Start Su&&ar%
Spring &anages the lifec%cle of the application
" All beans are full% initiali+ed before the% are used
,eans are al(a%s created in the right order
" ,ased on their dependencies
-ach bean is bound to a uni.ue id
" The id reflects the ser/ice the bean pro/ides to clients
Spring encapsulates the bean i&ple&entations
chosen for a gi/en application deplo%&ent
" Conceals i&ple&entation details
9
Topics in this session
Spring .uick start
!riting ben de"initions
" Configuring ob#ects
" $oing be%ond constructor instantiation
Creating an application context
Su&&ar%
10
,asic Spring XML ,ean
0efinition Te&plate
-Cxml !ersion&/8%A0 encoding&/4F1D0C.
-beans xmlns&/$ttp622,,,%springframe,or>%org2sc$ema2beans0
xmlns6xsi&/$ttp622,,,%,@%org2:AA82=?5Sc$ema1instance0
xsi6sc$ema5ocation&/
$ttp622,,,%springframe,or>%org2sc$ema2beans
$ttp622,,,%springframe,or>%org2sc$ema2beans2spring1beans1:%9%xsd0.
-E11 Add your bean definitions $ere 11.
-2beans.
11
Si&plest 1ossible ,ean
0efinition
-bean id&/ser!ice0 class&/example%Ser!iceImpl02.
Ser!iceImpl ser!ice & ne, Ser!iceImpl()'
2esults in 3/ia 2eflection45
ApplicationContext
ser!ice 1. instance of Ser!iceImpl
A class ,it$ no dependencies
12
Constructor 0ependenc%
In#ection
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-constructor1arg ref&/repository02.
-2bean.
-bean id&/repository0 class&/example%#epositoryImpl02.
#epositoryImpl repository & ne, #epositoryImpl()'
Ser!iceImpl ser!ice & ne, Ser!iceImpl(repository)'
-.ui/alent to5
ApplicationContext
ser!ice 1. instance of Ser!iceImpl
repository 1. instance of #epositoryImpl
A class ,it$ a single
dependency expected
by its constructor
13
Setter 0ependenc% In#ection
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-property name&/repository0 ref&/repository02.
-2bean.
-bean id&/repository0 class&/example%#epositoryImpl02.
#epositoryImpl repository & ne, #epositoryImpl()'
Ser!iceImpl ser!ice & ne, Ser!iceImpl()'
ser!ice%set#epository(repository)'
-.ui/alent to5
ApplicationContext
ser!ice 1. instance of Ser!iceImpl
repository 1. instance of #epositoryImpl
A class ,it$ a single
dependency expected
by a setter met$od
14
!hen to *se Constructors /s6
Setters7
Spring supports both
)ou can &ix and &atch
15
The Case for Constructors
-nforce &andator% dependencies
1ro&ote i&&utabilit%
" Assign dependencies to final fields
Concise for progra&&atic usage
" Creation and in#ection in one line of code
16
The Case for Setters
Allo( optional dependencies and defaults
'a/e descripti/e na&es
8ollo( 9a/a,ean: con/entions
Inherited auto&aticall%
17
$eneral 2eco&&endations
8ollo( standard 9a/a design guidelines
" *se constructors to set re.uired properties
" *se setters for optional or those (ith default /alues
So&e classes are designed for a particular
in#ection strateg%
" In that case go (ith it; do not fight it
,e consistent abo/e all
18
Co&bining Constructor and
Setter In#ection
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-constructor1arg ref&/reFuired0 2.
-property name&/optional0 ref&/optional0 2.
-2bean.
-bean id&/reFuired0 class&/example%#eFuiredImpl0 2.
-bean id&/optional0 class&/example%OptionalImpl0 2.
#eFuiredImpl reFuired & ne, #eFuiredImpl()'
OptionalImpl optional & ne, OptionalImpl()'
Ser!iceImpl ser!ice & ne, Ser!iceImpl(reFuired)'
ser!ice%setOptional(optional)'
-.ui/alent to5
19
In#ecting Scalar <alues
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-property name&/stringProperty0 !alue&/foo0 2.
-2bean.
Ser!iceImpl ser!ice & ne, Ser!iceImpl()'
ser!ice%setStringProperty(/foo0)'
-.ui/alent to5
ApplicationContext
ser!ice 1. instance of Ser!iceImpl
public class Ser!iceImpl "
public !oid setStringProperty(String s) " %%% (
22 %%%
(
20
Auto&atic <alue T%pe
Con/ersion
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-property name&/integerProperty0 !alue&/:G0 2.
-2bean.
Ser!iceImpl ser!ice & ne, Ser!iceImpl()'
Integer !alue & ne, Integer(/:G0)'
ser!ice%setIntegerProperty(!alue)'
-.ui/alent to5
ApplicationContext
ser!ice 1. instance of Ser!iceImpl
public class Ser!iceImpl "
public !oid setIntegerProperty(Integer i) " %%% (
22 %%%
(
21
In#ecting lists
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-property name&/listProperty0.
-list.
-ref bean&HxyIH2.
-!alue.8:@J-2!alue.
-null2.
-2list.
-2property.
-2bean.
Ser!iceImpl ser!ice & ne, Ser!iceImpl()'
22 create list ,it$ bean referenceB 8:@J !alue and null element
ser!ice%set5istProperty(list)'
-.ui/alent to5
ApplicationContext
ser!ice 1. instance of Ser!iceImpl
22
In#ecting collections
Si&ilar support a/ailable for
" 1roperties 3through props = prop ele&ents4
" Set 3through a set ele&ent; si&ilar to list4
" Map 3through &ap = ke% ele&ents4
23
Topics in this session
'o( Spring (orks
!riting Spring bean definitions
" Configuring ob#ects
" #oing beyond constructor instntition
Creating a Spring application context
Su&&ar%
24
Calling 8actor% Methods
So&e ob#ects cannot be created b% a constructor
public class 5egacySingleton "
pri!ate static 5egacySingleton inst & ne, 5egacySingleton()'
pri!ate 5egacySingleton() " %%% (
public static 5egacySingleton getInstance() "
return inst'
(
(
-bean id&/ser!ice0 class&/example%5egacySingleton0
factory-method="getInstance" 2.
25
Calling 8actor% ,eans
So&eti&es %ou (ant Spring to al(a%s delegate
to 9a/a code to create another bean
public class ComplexSer!iceFactory m!"ements #actory$ean "
Ob3ect getOb3ect() t$ro,s Kxception "
22 create complex ser!ice impl in Ja!a code
(
(
-bean id&/ser!ice0 class&/example%ComplexSer!iceFactory0.
-property name&/neededoCreateSer!ice0 !alue&/)0 2.
-2bean.
26
The 8actor%,ean Contract
Spring auto detects an% bean that i&ple&ents
Factory;ean and returns the ob#ect created b%
get>b#ect34 to clients
" The factor% itself is concealed
ApplicationContext
Factory;ean
get;ean(bean+ame)
getOb3ect() ob3ect
27
A $ood 8actor% ,ean
-xa&ple
-ncapsulating the creation of a test *ataSource
ApplicationContext
est*ataSourceFactory
(8) get;ean(/dataSource0)
(:) getOb3ect() (9) dataSource
%3& createIn'emory(ata)ase%&*
%4& !o!u"ate+th,est(ata%&*
#uns before
t$e data source
is usable by
t$e application
28
8actor%,eans in Spring
9ndi>b#ect8actor%,ean
" >ne option for looking up 9?0I ob#ects
8actor%,eans for creating re&oting proxies
8actor%,eans for configuring data access
technologies like 'ibernate; 91A or i,atis
29
Topics in this session
Spring .uick start
!riting bean definitions
" Configuring ob#ects
" $oing be%ond constructor instantiation
Creting n ppliction context
Su&&ar%
30
Creating a Spring Application
Context
Spring application contexts can be
bootstrapped in an% en/iron&ent; including
" 9*nit s%ste& test
" !eb application
" -nterprise 9a/a ,ean 3-9,4
" Standalone application
Loadable (ith bean definitions fro& files
" In the class path
" >n the local file s%ste&
" At an en/iron&ent-relati/e resource path
31
-xa&ple5 *sing an Application
Context Inside a 9*nit S%ste& Test
import static org%3unit%Assert%L'
public !oid ransferSer!iceest "
pri!ate ransferSer!ice ser!ice'
7;efore public !oid set4p() "
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(/application1config%xml0)'
22 5oo> up t$e application ser!ice interface
ser!ice & (ransferSer!ice) context%get;ean(/transferSer!ice0)'
(
7est public !oid moneyransfer() "
Confirmation receipt &
ser!ice%transfer(ne, ?onetaryAmount(/@AA%AA0)B /80B /:0))'
assertEquals(receipt%get+e,;alance()B /9AA%AA0)'
(
)
(
ests t$e system
;ootstraps t$e system to test
32
Spring@s 8lexible 2esource
Loading Mechanis&
ApplicationContext i&ple&entations ha/e
default resource loading rules
ne, ClassPat$=mlApplicationContext(/com2acme2application1config%xml0)'
ne, FileSystem=mlApplicationContext(/C6MMetcMMapplication1config%xml0)'
NC5ASSPAO2com2acme2application1config%xml
C6MetcMapplication1config%xml
ne, =mlPebApplicationContext(/PK;1I+F2application1config%xml0)'
NO?CAQ#OO2,ebapp2my,ebapp2PK;1I+F2application1config%xml
33
Spring@s 8lexible 2esource
Loading Mechanis& 3A4
'o(e/er; default rules can be o/erridden (ith
resource loading prefixes
These prefixes can be used anywhere Spring
needs to deal (ith resources
" ?ot #ust in constructor args to application context
<arious prefixes
" classpath5
" file5
" http5
ne, =mlPebApplicationContext(/c"ass!ath-com2acme2application1config%xml0)'
NC5ASSPAO2com2acme2application1config%xml
34
Creating a Spring Application
Context fro& Multiple 8iles
A context can be configured fro& &ultiple files
Allo(s partitioning of bean definitions into
logical groups
$enerall% a best practice to separate out
BapplicationC beans fro& BinfrastructureC beans
" Infrastructure often changes bet(een en/iron&ents
" -/ol/es at a different rate
35
Mixed Configuration
-beans.
-bean id&/transferSer!ice0 class&/app%impl%ransferSer!iceImpl0.
-constructor1arg ref&/account#epository0 2.
-2bean.
-bean id&/account#epository0 class&/app%impl%JdbcAccount#epository0.
-constructor1arg ref&/dataSource0 2.
-2bean.
-bean id&/dataSource0 class&/com%oracle%3dbc%pool%Oracle*ataSource0.
-property name&/4#50 !alue&/3dbc6oracle6t$in67local$ost689:86;A+<0 2.
-property name&/user0 !alue&/moneytransfer1app0 2.
-2bean.
-2beans.
Coupled to an Oracle en!ironment
36
-beans.
-bean id&/dataSource0 class&/app%testdb%est*ataSourceFactory0 2.
-2beans.
1artitioning Configuration
-beans.
-bean id&/transferSer!ice0 class&/app%impl%ransferSer!iceImpl0.
-constructor1arg ref&/account#epository0 2.
-2bean.
-bean id&/account#epository0 class&/app%impl%JdbcAccount#epository0.
-constructor1arg ref&/dataSource0 2.
-2bean.
-2beans.
+o, substitutable for ot$er en!ironments
37
,ootstrapping in -ach
-n/iron&ent
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(ne, StringRS "
/application1config%xml0B
/test1infrastructure1config%xml0
()'
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(ne, StringRS "
/application1config%xml0B
/oracle1infrastructure1config%xml0
()'
In the test en/iron&ent
In the production >racle en/iron&ent
38
Topics in this session
'o( Spring (orks
!riting Spring bean definitions
" Configuring ob#ects
" $oing be%ond constructor instantiation
Creating a Spring application context
Summry
39
,enefits of 0ependenc%
In#ection
)our ob#ect is handed (hat it needs to (ork
" 8rees %our ob#ect fro& the burden of resol/ing its
dependencies
" Si&plifies %our code; i&pro/es code reusabilit%
1ro&otes progra&&ing to interfaces
" Conceals the i&ple&entation details of each dependenc%
I&pro/es testabilit%
" 0ependencies can be easil% stubbed out for unit testing
Allo(s for centrali+ed control o/er ob#ect lifec%cle
" >pens the door for ne( possibilities
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibit
LA,
*sing Spring to Configure an Application
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Understanding the Bean
Lifecycle
An In-depth Look at Springs Lifecycle
Management Features
2
Topics in this session
Introduction to Spring's !" n#mesp#ces
The lifecycle of a Spring application conte!t
" The initiali#ation phase
" The use phase
" The destruction phase
Bean scoping
3
Introduction to Spring$s
%ustom &ML 'amespaces
Spring pro(ides higher-le(el configuration
languages that )uild on the generic *)eans+,
language
" -ro(ide a)straction and semantic (alidation
" Simplify common configuration needs
.ach language is defined )y its o/n &ML
namespace you may import
" 0ou can e(en /rite your o/n
4
Importing a %ustom &ML
'amespace
<?xml version=1.0 encoding=UTF-8?>
<beans xmlns=h!"##$$$.s!ring%rame$or&.org#schema#beans
xmlns"xsi=h!"##$$$.$'.org#(001#)*+,chema-insance
xmlns"conex=h!"##$$$.s!ring%rame$or&.org#schema#conex
xsi"schema+ocaion=
h!"##$$$.s!ring%rame$or&.org#schema#beans
h!"##$$$.s!ring%rame$or&.org#schema#beans#s!ring-beans-(.-.xsd
h!"##$$$.s!ring%rame$or&.org#schema#conex
h!"##$$$.s!ring%rame$or&.org#schema#conex#s!ring-conex-(.-.xsd>
<.-- /o0 can no$ 0se <conex"1#> ags -->
<#beans>
2ssign names!ace a !re%ix
2ssociae names!ace $ih is ),3
5
Benefits of Using 'amespace
%onfiguration
<beans>
<bean class=org.s!ring%rame$or&.beans.%acor4.con%ig.
5ro!er45laceholder6on%ig0rer>
<!ro!er4 name=locaion val0e=#789-:;F#daaso0rce.!ro!eries #>
<#bean>
<#beans>
<beans ... >
<conex"!ro!er4-!laceholder locaion=#789-:;F#daaso0rce.!ro!eries #>
<#beans>
Before
After
<eneric bean#!ro!er4
s4nax is all ha=s available
>e?0ires remembering
%rame$or& classnames
6reaes same bean as
above@ b0 hides
%rame$or& deails
2rib0es are s!eci%ic o
he as&@ raher han
generic name#val0e !airs
6
'amespaces Summary
'amespace configuration is a)out simplification
and e!pressi(eness
" 1eneric )ean+property synta! can )e too lo/-le(el
" 2ides frame/ork details
'amespaces are defined for categories of
related frame/ork functionality
3
" aop4 )eans4 conte!t4 5ee4 5ms4 t!4 util
6e /ill use namespaces to simplify
configuration throughout this training
* an incomplete list. see http://www.springframework.org/schema/ for details
7
Topics in this session
Introduction to Spring$s &ML namespaces
$he li%ecycle o% # Spring #pplic#tion
context
" The initiali#ation phase
" The use phase
" The destruction phase
Bean scoping
8
-hases of the Application
Lifecycle
:niialiAaion Use 3esr0cion
-repares for use
Application
ser(ices
" Are created
" %onfigured
" May allocate
system resources
Application is not
usa)le until this
phase is complete
Used )y clients
Application
ser(ices
" -rocess client
re7uests
" %arry out
application
)eha(iors
88988: of the
time is spent in
this phase
Shuts do/n
Application
ser(ices
" ;elease any
system resources
" Are eligi)le for
gar)age
collection
9
Springs ;ole as a Lifecycle
Manager
For nearly any class of application
" Standalone <a(a application
" <Unit System Test
" <a(a ..= /e) application
" <a(a ..= enterprise application
Spring fits in to manage the application
lifecycle
" -lays an important role in all phases
10
Topics in this session
Introduction to Spring$s &ML namespaces
The lifecycle of a Spring application conte!t
" $he initi#li&#tion ph#se
" The use phase
" The destruction phase
Bean scoping
:niialiAaion Use 3esr0cion
11
The Lifecycle of a Spring Application
%onte!t >?@ - The Initiali#ation -hase
6hen you create a conte!t the initiali#ation
phase completes
But e!actly /hat happens in this phaseA
## 6reae he a!!licaion %rom he con%ig0raion
2!!licaion6onex conex =
ne$ 6lass5ah)ml2!!licaion6onexBne$ ,ringCD E
a!!licaion-con%ig.xml@
es-in%rasr0c0re-con%ig.xml
FGH
12
Inside The Application %onte!t
Initiali#ation Lifecycle
"o#d be#n de%initions
Initiali#e )ean instances
13
Load Bean Befinitions
The &ML files are parsed
Bean definitions are loaded into the conte!ts
9eanFacor4
I
.ach inde!ed under its id
Special 9eanFacor45os5rocessor )eans are
in(oked
I %an modify the definition of any )ean
14
2!!licaion 6onex
Load Bean Befinitions
<beans>
<bean id=rans%er,ervice J
<bean id=acco0n>e!osior4J
<#beans>
a!!licaion-con%ig.xml
<beans>
<bean id=daa,o0rce J
<#beans>
es-in%rasr0c0re-con%ig.xml
rans%er,ervice
acco0n>e!osior4
9eanFacor4
9eanFacor45os5rocessors
!os5rocessB9eanFacor4G
rans%er,ervice
acco0n>e!osior4
daa,o0rce
6an modi%4 he de%iniion o%
an4 bean in he %acor4
be%ore an4 obKecs are creaed
15
The BeanFactory-ost-rocessor
.!tension -oint
Useful for applying transformations to groups
of )ean definitions
" Before any o)5ects are actually created
Se(eral useful implementations are pro(ided
)y the frame/ork
0ou can also /rite your o/n
" Implement the BeanFactory-ost-rocessor interface
16
An .!ample
BeanFactory-ost-rocessor
I
PropertyPlaceholderConfigurer su)situtes
CD(aria)lesE in )ean definitions /ith (alues
from 9properties files
17
2o/ -roperty-laceholder%onfigurer
6orks
5ro!er45laceholder6on%ig0rer
,!ring 2!!licaion 6onex
Ba%er bean de%iniions are loadedG
!os5rocessB9eanFacor4G
9ean de%iniion
daa,o0rce
U>+=LEdaaso0rce.0rlF
0ser=LEdaaso0rce.0serF
9ean de%iniion
daa,o0rce
U>+=Kdbc"oracle"J
0ser=mone4rans%er-a!!
18
Using
-roperty-laceholder%onfigurer
<beans>
<bean id=daa,o0rce class=com.oracle.Kdbc.!ool.Mracle3aa,o0rce>
<!ro!er4 name=U>+ val0e=LEdaaso0rce.0rlF #>
<!ro!er4 name=0ser val0e=LEdaaso0rce.0serF #>
<#bean>
<bean class=org.s!ring%rame$or&.beans.%acor4.con%ig.
5ro!er45laceholder6on%ig0rer>
<!ro!er4 name=locaion val0e=#789-:;F#daaso0rce.!ro!eries #>
<#bean>
<#beans>
File $here he variable
val0es reside
datasource.url!d"c#oracle#thin#$localhost#1521#%&'(
datasource.user)oneytransfer*app
daaso0rce.!ro!eries
Nariables o re!lace
8asil4 ediable
19
Simplifying configuration /ith
*conte!tFproperty-placeholder,
<beans ... >
<bean id=daa,o0rce class=com.oracle.Kdbc.!ool.Mracle3aa,o0rce>
<!ro!er4 name=U>+ val0e=LEdaaso0rce.0rlF #>
<!ro!er4 name=0ser val0e=LEdaaso0rce.0serF #>
<#bean>
<conex"!ro!er4-!laceholder locaion=#789-:;F#daaso0rce.!ro!eries #>
<#beans>
6reaes he same 5ro!er45laceholder6on%ig0rer
bean de%iniion in a more concise %ashion
20
Inside the Application %onte!t
Initiali#ation Lifecycle
Load )ean definitions
Initi#li&e be#n inst#nces
21
Initiali#ing Bean Instances
.ach )ean is eagerly instantiated )y default
" %reated in the right order /ith its dependencies
in5ected
After dependency in5ection each )ean goes
through a post-processing phase
" 6here further configuration and initiali#ation can
occur
After post processing the )ean is fully
initiali#ed and ready for use
" Tracked )y its id until the conte!t is destroyed
22
Bean Initiali#ation Steps
9ean
:nsaniaed
3e!endencies
:nKeced
9ean 5os
5rocessed
9ean
>ead4
For Use
23
Bean -ost -rocessing
Bean post processing can )e )roken do/n into
t/o steps
" Initiali#e the )ean if instructed
" %all special 9ean5os5rocessors to perform additional
configuration
24
Bean -ost -rocessing Steps
Initi#li&e the be#n i% instructed
%all special 9ean5os5rocessors to perform
additional configuration
25
Initiali#e the Bean if
Instructed
A )ean can optionally register for one or more
initiali#ation call)acks
" Useful for e!ecuting custom initiali#ation )eha(iors
There$s more than one /ay to do it
" <S;-GHI J-ost%onstruct
" *)ean+, init-method attri)ute
" Implement Spring$s Initiali#ingBean interface
26
Bean Initiali#ation
Techni7ues
'(ostConstruct
init-method
Initiali#ingBean
27
First4 a -rimer on <S;-GHI
K%ommon AnnotationsL
<S;-GHI pro(ides a set of common annotations
for use in <a(a .. applications
" 2elps a(oid proliferation of frame/ork-specific
annotations
" Facilitates porta)ility
" Used )y .<B M9I
" Used )y Spring4 starting /ith (ersion G9H
28
<S;-GHI -rimer4 cont9
All annotations reside in the 5a(a!9annotation
package
" Included in the <BN starting in <a(a O
" A(aila)le as part of the $5a(aee-api$ 5ar for <a(a H
To name a fe/
" J-ost%onstruct
" J-reBestroy
" J;esource
Which brings us back to... initiali#ationP
" Spring makes use of these annotations to trigger
lifecycle e(ents
29
;egistering for Initiali#ation
/ith J-ost%onstruct
!0blic class Trans%er,ervice:m!l E
O5os6onsr0c
void iniBG E
## 4o0r c0som iniialiAaion code
F
F
;o resricions on
mehod name or visibili4
Tells ,!ring o call his
mehod a%er
de!endenc4 inKecion
This is the preferred initiali#ation techni7ue
" Fle!i)le4 a(oids depending on Spring A-Is
" ;e7uires Spring G9H or )etter
30
.na)ling %ommon Annotation-
Based Initiali#ation
J-ost%onstruct /ill )e ignored unless Spring is
instructed to detect and process it
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice:m!l #>
<bean class=org.s!ring%rame$or&.conex.annoaion.
6ommon2nnoaion9ean5os5rocessor #>
<#beans>
3eecs and invo&es an4
mehods annoaed $ih
O5os6onsr0c
31
Simplifying %onfiguration /ith
*conte!tFannotation-config,
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice:m!l #>
<conex"annoaion-con%ig#>
<#beans>
8nables m0li!le 9ean5os5rocessors@ incl0ding"
>e?0ired2nnoaion9ean5os5rocessor
6ommon2nnoaion9ean5os5rocessor
32
Bean Initiali#ation
Techni7ues
J-ost%onstruct
init-method
Initiali#ingBean
33
Initiali#ing a Bean 0ou Bo
'ot %ontrol
Use init-method to initiali#e a )ean you do not
control the implementation of
<bean id=bro&er
class=org.a!ache.acivem?.bro&er.9ro&er,ervice
ini-mehod=sar>
J
<#bean>
*ehod m0s be !0blic $ih no arg0mens
6lass $ih no ,!ring de!endenc4
34
Bean Initiali#ation
Techni7ues
J-ost%onstruct
init-method
Initi#li&ing)e#n
35
;egistering for an Initiali#ation
%all)ack /ith Initiali#ingBean
Initiali#ation techni7ue used prior to Spring G9H
" ;e7uires implementing a Spring-specific interface
" Fa(or use of J-ost%onstruct if possi)le
!ac&age org.s!ring%rame$or&.beans.%acor4H
!0blic iner%ace :niialiAing9ean E
!0blic void a%er5ro!eries,eBGH
F
36
!0blic class *essage>eceiver im!lemens :niialiAing9ean E
!0blic void a%er5ro!eries,eBG E
## allocae message receiving reso0rces
F
F
<beans>
<bean id=message>eceiver class=exam!le.*essage>eceiver #>
<#beans>
:m!lemens
s!ecial ,!ring
li%ec4cle iner%ace
,!ring invo&es mehod a0omaicall4
;o oher con%ig0raion re?0ired
;egistering for an Initiali#ation
%all)ack /ith Initiali#ingBean
37
Bean -ost -rocessing Steps
Initiali#e the )ean if instructed
C#ll speci#l %eanPostProcessors to per%orm
#ddition#l con%igur#tion
38
The Bean-ost-rocessor
.!tension -oint
An important e!tension point in Spring
%an modify )ean instances in any /ay
" -o/erful ena)ling feature
Se(eral implementations are pro(ided )y the
frame/ork
'ot common to /rite your o/n
39
An .!ample
Bean-ost-rocessor
;e7uiredAnnotationBean-ost-rocessor
" -ro(ided )y the frame/ork
" .nforces that '*e+uired properties are set
" Must )e e!plicitly ena)led (ia configuration
40
Using
;e7uiredAnnotationBean-ost-rocessor
!0blic void Trans%er,ervice:m!l im!lemens Trans%er,ervice E
!rivae 2cco0n>e!osior4 acco0n>e!osior4H
O>e?0ired
!0blic void se2cco0n>e!osior4B2cco0n>e!osior4 arG E
his.acco0n>e!osior4 = arH
F
F
:ndicaes he de!endenc4
is re?0ired
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice:m!l #>
<bean class=org.s!ring%rame$or&.beans.%acor4.annoaion.
>e?0ired2nnoaion9ean5os5rocessor #>
<#beans>
20omaicall4 deecedH no oher con%ig0raion is necessar4
41
Simplifying %onfiguration
/ith *conte!tFannotation-config,
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice:m!l #>
<conex"annoaion-con%ig#>
<#beans>
20omaicall4 enables >e?0ired2nnoaion9ean5os5rocessor
;emem)er *conte!tFannotation-config,A
42
Topics in this session
Introduction to Spring$s &ML namespaces
The lifecycle of a Spring application conte!t
" The initiali#ation phase
" $he use ph#se
" The destruction phase
Bean scoping
Use 3esr0cion :niialiAaion
43
The Lifecycle of a Spring Application
%onte!t >G@ - The Use -hase
6hen you in(oke a )ean o)tained from the
conte!t the application is used
But e!actly /hat happens in this phaseA
2!!licaion6onex conex = ## ge i %rom some$here
## +oo&0! he enr4 !oin ino he a!!licaion
Trans%er,ervice service =
BTrans%er,erviceG conex.ge9eanBrans%er,erviceGH
## Use i.
service.rans%erBne$ *onear42mo0nB-0.00G@ 1@ (GH
44
Inside The Bean ;e7uest
>Use@ Lifecycle
If the )ean is 5ust your ra/ o)5ect it is simply
in(oked directly >nothing special@
If your )ean has )een /rapped in a pro!y
things get more interesting
Trans%er,ervice:m!l
rans%erBL-0@ 1@ (G
rans%erBL-0@ 1@ (G
Trans%er,ervice:m!l
,!ring 5rox4
45
-ro!y -o/er
A 9ean5os5rocessor may /rap your )eans in a
dynamic pro!y and add )eha(ior to your
application logic transparently
Trans%er,ervice:m!l
rans%erBL-0@ 1@ (G
,!ring
Transacion:nerce!or
Transacion*anager
begin commi
Transacion
managemen
behavior is added
aro0nd 4o0r code
,!ring 5rox4
46
-ro!ies are %entral to the Spring
Triangle
Simple
Object
,
e
p
e
n
d
e
n
c
y
I
n
-
e
c
t
i
o
n
.
s
p
e
c
t
-
/
r
i
e
n
t
e
d
(
r
o
g
r
#
m
m
i
n
g
0nterprise Ser1ice .bstr#ctions
1. The 2!!licaion
conex drives bean
con%ig0raion
(. 34namic !roxies
add behaviors o
4o0r beans
'. ,!ring can inegrae man4
ener!rise behaviors
47
Bean Initiali#ation Steps
9ean
:nsaniaed
3e!endencies
:nKeced
9ean 5os
5rocessed
9ean
>ead4
For Use
5roxies are
creaed here
48
Topics in this session
:niialiAaion
Introduction to Spring$s &ML namespaces
The lifecycle of a Spring application conte!t
" The initiali#ation phase
" The use phase
" $he destruction ph#se
Bean scoping
Use 3esr0cion
49
The Lifecycle of a Spring Application
%onte!t >M@ - The Bestruction -hase
6hen you close a conte!t the destruction
phase completes
But e!actly /hat happens in this phaseA
6on%ig0rable2!!licaion6onex conex = J
## 3esro4 he a!!licaion
conex.closeBGH
50
Inside the Application
%onte!t Bestruction Lifecycle
Bestroy )ean instances if instructed
Bestroy itself
" The conte!t is not usa)le again
51
Bestroy Bean Instances if
Instructed
A )ean can optionally register for one or more
destruction call)acks
" Useful for releasing resources and $cleaning up$
There$s more than one /ay to do it
" <S;-GHI J-reBestroy
" *)ean+, destroy-method attri)ute
" Implement Spring$s Bisposa)leBean interface
52
Bean Bestruction Techni7ues
'(re,estroy
destroy-method
Bisposa)leBean
53
;egistering for Bestruction
/ith J-reBestroy
!0blic class Trans%er,ervice:m!l E
O5re3esro4
void release>eso0rcesBG E
## 4o0r c0som desr0cion code
F
F
;o resricions on mehod
name or visibili4
Tells ,!ring o call his
mehod !rior o desro4ing he
bean insance
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice:m!l #>
<conex"annoaion-con%ig#>
<#beans>
8nables common annoaion
!rocessing
54
Bean Bestruction Techni7ues
J-reBestroy
destroy-method
Bisposa)leBean
55
Bestroying a Bean 0ou Bo
'ot %ontrol
Use destroy-method to dispose a )ean you do
not control the implementation of
<bean id=daa,o0rce
class=org.a!ache.commons.dbc!.9asic3aa,o0rce
desro4-mehod=close>
J
<#bean>
*ehod m0s be !0blic $ih no arg0mens
6lass $ih no ,!ring de!endenc4
56
Bean Bestruction Techni7ues
J-reBestroy
destroy-method
,ispos#ble)e#n
57
;egistering for a Bestruction
%all)ack /ith Bisposa)leBean
;egister for a )ean destruction call)ack )y
implementing the +isposa"le%ean interface
Spring in(okes this method at the right time
!ac&age org.s!ring%rame$or&.beans.%acor4H
!0blic iner%ace 3is!osable9ean E
!0blic void desro4BGH
F
58
Topics in this session
Introduction to Spring$s &ML namespaces
The lifecycle of a Spring application conte!t
" The initiali#ation phase
" The use phase
" The destruction phase
)e#n scoping
59
Bean Scoping
Spring puts each )ean instance in a scope
Singleton scope is the default
" The KsingleL instance is scoped )y the conte!t itself
" By far the most common
Qther scopes can )e used on a )ean-)y-)ean
)asis
<bean id=m49ean class=exam!le.*49ean
sco!e=J>
<#bean>
50 his bean in some oher sco!e
60
A(aila)le Scopes
I
prototype - A ne/ instance is created each time
the )ean is referenced
I
session - A ne/ instance is created once per
user session
I
re,uest - A ne/ instance is created once per
re7uest
I
custo) - 0ou define your o/n rules
" Ad(anced feature
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
LAB
Understanding the Bean Lifecycle
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Simplifying Application
Configuration
Techniques for Creating Reusable and
Concise Bean Definitions
2
Topics in this session
Bean e!inition "nheritance
Inner Beans
Property ditors
Importing Configuration !iles
Bean "aming
The p "amespace
The util "amespace
3
Bean Definition Inheritance
#$%
Sometimes se&eral beans need to be
configured in the same 'ay
(se bean definition inheritance to define the
common configuration once
) Inherit it 'here needed
4
*ithout Bean Definition
Inheritance
<beans>
<bean id=pool-A class=com.oracle.jdbc.pool.OracleDataSource>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-a"%&'%"(A)* +>
<property name=user !alue=moneytrans,er-app +>
<+bean>
<bean id=pool-( class=com.oracle.jdbc.pool.OracleDataSource>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-b"%&'%"(A)* +>
<property name=user !alue=moneytrans,er-app +>
<+bean>
<bean id=pool-- class=com.oracle.jdbc.pool.OracleDataSource>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-c"%&'%"(A)* +>
<property name=user !alue=moneytrans,er-app +>
<+bean>
<+beans>
-an you ,ind t#e duplication.
5
*ith Bean Definition
Inheritance
<beans>
<bean id=abstract/ool
class=com.oracle.jdbc.pool.OracleDataSource abstract=true>
<property name=user !alue=moneytrans,er-app +>
<+bean>
<bean id=pool-A parent=abstractPool>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-a"%&'%"(A)* +>
<+bean>
<bean id=pool-( parent=abstractPool>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-b"%&'%"(A)* +>
<+bean>
<bean id=pool-- parent=abstractPool>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-c"%&'%"(A)* +>
<+bean>
<+beans>
0ill not be instantiated
1ac# pool in#erits its parent con,i2uration
6
+&erriding Parent Bean Configuration
<beans>
<bean id=de,ault/ool class=com.oracle.jdbc.pool.OracleDataSource>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-a"%&'%"(A)* +>
<property name=user !alue=moneytrans,er-app +>
<+bean>
<bean id=pool-( parent=de,ault/ool>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-b"%&'%"(A)* +>
<+bean>
<bean id=pool-- parent=de,ault/ool class=e3ample.SomeOt#er/ool>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-c"%&'%"(A)* +>
<+bean>
<+beans>
)ot abstract4 acts as a concrete de,ault
O!errides class as 5ell
O!errides UR property
7
Topics in this session
Bean Definition Inheritance
"nner Beans
Property ditors
Importing Configuration !iles
Bean "aming
The p "amespace
The util "amespace
8
Inner Beans
Sometimes a bean naturally scopes the
definition of another bean
) The ,scoped- bean is not useful to anyone else
.a/e the scoped bean an inner bean
) .ore manageable
) A&oids polluting the bean namespace
9
*ithout an Inner Bean
<beans>
<bean id=restaurantRepository
class=re5ards.internal.restaurant.6dbcRestaurantRepository>
<property name=dataSource re,=dataSource +>
<property name=bene,itA!ailability/olicy7actory re,=,actory +>
<+bean>
<bean id=,actory
class=re5ards.internal.restaurant.a!ailability.
De,ault(ene,itA!ailability/olicy7actory>
<constructor-ar2 re,=re5ard8istorySer!ice +>
<+bean>
9
<+beans>
-an be re,erenced by ot#er beans
:e!en i, it s#ould not be;
10
*ith an Inner Bean
<beans>
<bean id=restaurantRepository
class=re5ards.internal.restaurant.6dbcRestaurantRepository>
<property name=dataSource re,=dataSource +>
<property name=bene,itA!ailability/olicy7actory>
<bean class=re5ards.internal.restaurant.a!ailability.
De,ault(ene,itA!ailability/olicy7actory>
<constructor-ar2 re,=re5ard8istorySer!ice +>
<+bean>
<+property>
<+bean>
9
<+beans>
<nner bean #as no id :it is anonymous;
-annot be re,erenced outside t#is scope
11
<beans>
<bean id=restaurantRepository
class=re5ards.internal.restaurant.6dbcRestaurantRepository>
<property name=dataSource re,=dataSource +>
<property name=bene,itA!ailability/olicy7actory>
<bean class=re5ards.internal.restaurant.a!ailability.
De,ault(ene,itA!ailability/olicy7actory>
<constructor-ar2>
<bean class=re5ards.internal.re5ards.6dbcRe5ard8istory>
<property name=dataSource re,=dataSource +>
<+bean>
<+constructor-ar2>
<+bean>
<+property>
<+bean>
<+beans>
.ultiple 0e&els of "esting
12
Topics in this session
Bean Definition Inheritance
Inner Beans
#roperty $ditors
Importing Configuration !iles
Bean "aming
The p "amespace
The util "amespace
13
Introducing Propertyditor
#$%
In 1.0 all literal &alues are te2t strings
In your code there are often rich ob3ect types
<bean id=p#one=alidator class=sample./#one=alidator>
<property name=pattern !alue=>?-@ABCD->?-@ABCD->?-@ABED +>
<+bean>
public class /#one=alidator B
pri!ate /attern pattern4
public !oid set/attern:/attern pattern; B
t#is.pattern = pattern4
D
D
A ric# object 5it# be#a!ior
A te3t strin2
14
Introducing Propertyditor
#4%
5our code should not be burdened 'ith the
responsibility of type con&ersion
Spring 'ill con&ert for you using a PropertyEditor
) Comes 'ith many property editors pre6installed
) 5ou may 'rite and install your o'n
15
Built6In Propertyditor
implementations
See the or2.sprin2,rame5orF.beans.propertyeditor
pac/age
Some highlights
G )umber1ditor con&erts to the "umber types
G (oolean1ditor con&erts to Boolean
G Date1ditor con&erts to 3a&a7util7Date
G Resource1ditor con&erts to a Resource
G /roperties1ditor con&erts to 3a&a7util7Properties
G (yteArray1ditor con&erts to a byte89
G ocale1ditor con&erts to a 0ocale
16
Built6In Propertyditor
2ample
<bean id=session7actory
class=or2.sprin2,rame5orF.orm.#ibernateC.support.
ocalSession7actory(ean>
9
<property name=#ibernate/roperties>
<!alue>
#ibernate.,ormatHsIl=true
#ibernate.jdbcHbatc#HsiJe=C?
<+!alue>
<+property>
<+bean>
public class ocalSession7actory(ean B
public !oid set8ibernate/roperties:/roperties p; B 9
D
Strin2-encoded properties
Kyped ja!a.util./roperties object
17
Implementing 5our +'n
Propertyditor
Create a custom editor by e2tending /roperty1ditorSupport
+&erride setAsKe3t:Strin2; to con&ert from String
+&erride 2etAsKe3t:; to format the &alue #optional%
public class /attern1ditor e3tends /roperty1ditorSupport B
public !oid setAsKe3t:Strin2 te3t; B
set=alue:te3t L= null . /attern.compile:te3t; " null;4
D
public Strin2 2etAsKe3t:; B
/attern !alue = :/attern; 2et=alue:;4
return :!alue L= null . !alue.pattern:; " ;4
D
D
-on!erts ,rom Strin2
18
Installing your Custom
Property ditor
(se a -ustom1ditor-on,i2urer to install your
custom editor #a (ean7actory/ost/rocessor%
<bean class=or2.sprin2,rame5orF.beans.,actory.con,i2.
-ustom1ditor-on,i2urer>
<property name=custom1ditors>
<map>
<entry Fey=ja!a3.util.re2e3./attern
!alue=e3ample./attern1ditor +>
<+map>
<+property>
<+bean>
7ully-Iuali,ied con!ertible type
K#e /roperty1ditor to
per,orm con!ersions
to t#at type
*A PatternEditor implementation is built-in as of Spring 2.0.1
19
Topics in this session
Bean Definition Inheritance
Inner Beans
Property ditors
"mporting Con!iguration %iles
Bean "aming
The p "amespace
The util "amespace
20
Importing Configuration !iles
#$%
(se the import tag to encapsulate including
another configuration file
<beans>
<import resource=accounts+account-con,i2.3ml +>
<import resource=restaurant+restaurant-con,i2.3ml +>
<import resource=re5ards+re5ards-con,i2.3ml +>
<+beans>
application-con,i2.3ml
<beans>
<import resource=application-con,i2.3ml+>
<bean id=dataSource class=e3ample.KestDataSource7actory +>
<+beans>
system-test-con,i2.3ml
ne5 -lass/at#MmlApplication-onte3t:system-test-con,i2.3ml;4
-lient only imports one ,ile
21
Importing Configuration !iles
#4%
Promotes splitting configuration into logical groups of
bean definitions
nables reuse across modules 'ithin an application
Compliments the option of creating an
ApplicationConte2t from multiple files
Application-onte3t conte3t =
ne5 -lass/at#MmlApplication-onte3t:
ne5 Strin2>A B
classpat#"+module%+module-con,i2.3mlN
classpat#"+module'+module-con,i2.3ml
D;4
22
Topics in this session
Bean Definition Inheritance
Inner Beans
Property ditors
Importing Configuration !iles
Bean &aming
The p "amespace
The util "amespace
23
Bean "aming
.ost beans are assigned a unique name 'ith the id
attribute
As an 1.0 ID this attribute has se&eral limitations
) Can only hold a single &alue
) Some special characters cannot be used #' (%
<bean id=dataSource 9+>
<bean id=dataource!a 9+>
O+P not allo5ed
24
Assigning a Bean .ultiple
"ames
(se the name attribute 'hen special characters
are needed
Also consider it 'hen you need to assign a
bean multiple names
<bean name=dataSource+primary 9+>
<bean name=dataSourceN dataSource+primary 9+>
25
Topics in this session
Bean Definition Inheritance
Inner Beans
Property ditors
Importing Configuration !iles
Bean "aming
)he p &amespace
The util "amespace
26
Shortcut to specifying bean
properties
After:
<bean name=e3ample class=com.,oo.13ample>
<property name=email !alue=,oo$,oo.com+>
<+bean>
<bean name=e3ample class=com.,oo.13ample
p"email=,oo$,oo.com+>
The p namespace allo's properties to be set as
an attribute to the bean definition
Before:
27
Shortcut to specifying bean
references
<bean name=e3ample class=com.,oo.13ample>
<property name=dataSource re,=dataSource+>
<+bean>
<bean name=e3ample class=com.,oo.13ample
p"dataSource-re,=dataSource+>
References to other beans require the format
p:<property-name>-ref=<reference>
Before:
After:
28
Considerations of the p
namespace
Requires a namespace definition:
"amespace not specified in an 1SD file; unli/e
other Spring namespaces
) So no e2tra schema0ocation entry required
3mlns"p=#ttp"++555.sprin2,rame5orF.or2+sc#ema+p
29
Topics in this session
Bean Definition Inheritance
Inner Beans
Property ditors
Importing Configuration !iles
Bean "aming
The p "amespace
)he util &amespace
30
Spring<s (til "amespace
*util('+ is one of the ,out6of6the6bo2- namespaces you
can import
+ffers high6le&el configuration for common utility tas/s
) Populating collections
) Accessing constants #static fields%
) 0oading properties
Before this namespace you 'rote more to do the same
thing
) (sing internal concepts li/e !ieldRetrie&ing!actoryBean
31
Configuring a 0ist
<bean id=in!entoryQana2er class=,oo.Qy<n!entoryQana2er>
<property name=5are#ouses>
<util"list>
<re, bean=primary0are#ouse +>
<re, bean=secondary0are#ouse +>
<bean class=,oo.0are#ouse 9+>
<+util"list>
<+property>
<+bean>
<bean id=primary0are#ouse ...+>
<bean id=secondary0are#ouse ...+>
1lements are beans :one inner;
ist is an inner bean
32
Configuring a Set
<bean id=noti,icationSer!ice class=,oo.Qy)oti,icationSer!ice>
<property name=subscribers re,=subscribers+>
<+bean>
<util"set id=subscribers>
<!alue>larry$,oo.com<+!alue>
<!alue>curly$,oo.com<+!alue>
<!alue>moe$,oo.com<+!alue>
<+util"set>
1lements are literal !alues
Set is a top-le!el bean
33
Configuring a .ap #$%
<bean id=in!entoryQana2er class=,oo.Qy<n!entoryQana2er>
<property name=5are#ouses>
<util"map>
<entry Fey=primary !alue-re,=primary0are#ouse +>
<entry Fey=secondary>
<bean class=,oo.0are#ouse 9+>
<+entry>
<+util"map>
<+property>
<+bean>
<bean id=primary0are#ouse ...+>
=alue is a top-le!el bean
=alue is an inner bean
34
Configuring a .ap #4%
<bean id=in!entoryQana2er class=,oo.Qy<n!entoryQana2er>
<property name=5are#ouses>
<util"map>
<entry>
<Fey>
<bean class=,oo.0are#ouse*ey>
<constructor-ar2 !alue=%'CE&RST@ +>
<+bean>
<+Fey>
<bean class=,oo.0are#ouse 9+>
<+entry>
<+util"map>
<+property>
<+bean>
*ey is an inner bean
35
Accessing Constants
<bean id=noti,icationSer!ice
class=e3ample.Qy)oti,icationSer!ice>
<property name=#ostname>
<util"constant static-,ield=e3ample.Qy-onstants.8OSKH)AQ1 +>
<+property>
<+bean>
Accesses static ,ield in t#e Qy-onstants class
36
0oading Properties
<bean id=noti,icationSer!ice
class=e3ample.Qy)oti,icationSer!ice>
<property name=emailQappin2s>
<util"properties location=classpat#"mail.properties +>
<+property>
<+bean>
oads a ja!a.util./roperties ,rom t#e location
37
Summary
Spring offers many techniques to simplify
configuration
) *e=&e seen 3ust a fe' here
) It=s about e2pressi&eness and elegance; 3ust li/e code
Don=t repeat yourself>
) (se bean inheritance if you=re seeing repetiti&e 1.0
Consider hiding lo'6le&el beans
) (se inner beans 'here it=s natural to do so
A&oid monolithic configuration
) (se *import'+ to aid in modulari?ing your 1.0
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Annotation-Based
Dependency Injection
Introducing Springs Annotations for
Dependency Injection
2
Topics in this Session
Annotation Quick Start
All Configuration Annotations
Suary
3
!o" Spring #orks
Spring
Application Context
Configuration
Instructions
Your Application Classes (POJOs)
Fully configured
application system
Ready for use
Creates
4
The Approach $oure %sed to
public class ransferSer!iceImpl implements ransferSer!ice "
public ransferSer!iceImpl(Account#epository ar) "
t$is%account#epository & ar'
(
)
(
public class JdbcAccount#epository implements Account#epository "
public JdbcAccount#epository(*ataSource ds) "
t$is%dataSource & ds'
(
)
(
+eeded to load accounts from t$e database
+eeded to perform money transfers
bet,een accounts
5
The Approach $oure %sed to
-beans.
-bean id&/transferSer!ice0 class&/app%impl%ransferSer!iceImpl0.
-constructor1arg ref&/account#epository0 2.
-2bean.
-bean id&/account#epository0 class&/app%impl%JdbcAccount#epository0.
-constructor1arg ref&/dataSource0 2.
-2bean.
-bean id&/dataSource0 class&/com%oracle%3dbc%pool%Oracle*ataSource0.
-property name&/4#50 !alue&/3dbc6oracle6t$in67local$ost689:86;A+<0 2.
-property name&/user0 !alue&/moneytransfer1app0 2.
-2bean.
-2beans.
6
The Annotation-Based Approach
public class ransferSer!iceImpl implements ransferSer!ice "
@Autowired
public ransferSer!iceImpl(Account#epository ar) "
t$is%account#epository & ar'
(
)
(
public class JdbcAccount#epository implements Account#epository "
@Autowired
public JdbcAccount#epository(*ataSource ds) "
t$is%dataSource & ds'
(
)
(
Spring6 =automatically try to ,ire t$is>?
7
The Annotation-Based Approach
-beans.
-bean id&/transferSer!ice0
class&/app%impl%ransferSer!iceImpl02.
-bean id&/account#epository0
class&/app%impl%JdbcAccount#epository02.
-bean id&/dataSource0 class&/com%oracle%3dbc%pool%Oracle*ataSource0.
-property name&/4#50 !alue&/3dbc6oracle6t$in67local$ost689:86;A+<0 2.
-property name&/user0 !alue&/moneytransfer1app0 2.
-2bean.
-context6annotation1config2.
-2beans.
+o more need to
specify
constructor1args
8
%sage - &othing Changes'
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$@mlApplicationContext(/application1config%xml0)'
22 5ooA up t$e application ser!ice interface
ransferSer!ice ser!ice &
(ransferSer!ice) context%get;ean(/transferSer!ice0)'
22 4se t$e application
ser!ice%transfer(ne, BonetaryAmount(/CDD%DD0E /80)E /:0)'
9
Quick Start Suary
Spring container needs ()*)s and "iring
instructions to asse+le your application
#iring instructions can +e pro,ided in -./0
0+ut also using annotations0
0or a co+ination of the t"o
10
Topics in this Session
Annotation Quick Start
Configuration nnotations
Suary
11
Configuration Annotations
1Auto"ired
12esource
1Coponent 3 12epository
1(ostConstruct 3 1(reDestroy 3 12e4uired
5 As sho"n earlier
12
1Auto"ired
Asks Spring to auto"ire fields6 ethods or
constructors +y using the type
5 2e4uires uni4ue atch'
e$ecution(
5org%springframework%transaction%annotation%6ransactional
0oid 8(%%))
" An, method mared with the LTransactional
annotation
3 e$ecution( (5e$ample%6racked 8) 8(%%))
" An, method that returns a value mared with the
LTraced annotation
59
E$ample
5"ecured(allowedRoles){7teller9-9manager9()
public 0oid wai0eFee () {
+
(
Requirements:
Run a securit# ceck before an# 5"ecured ser0ice operation
"ecurit# logic depends on: