You are on page 1of 830

Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.

Welcome to Core Spring


A 4-day bootcamp that trains you how to use the
Spring Framework to create well-designed, testable
business applications
2
Course Introduction
Core Spring coers the essentials o! deeloping
applications with the Spring Framework
Course is "#$ theory, "#$ lab work
% &heory highlights how to use Spring
% 'ab enironment based on SpringSource &ool Suite
(emory keys contain
% &he Spring Framework
% 'ab enironment based on S&S and &omcat
% 'ab materials and documentation
3
Course 'ogistics
)ours
'unch and breaks
*ther +uestions,
4
Coered in this section
Agenda
SpringSource, a diision o! -(ware
5
Course Agenda. /ay 0
Introduction to Spring
1sing Spring to con!igure an application
1nderstanding the bean li!e-cycle
Simpli!ying application con!iguration
Annotation-based dependency in2ection
6
Course Agenda. /ay 3
&esting a Spring-based application
Adding behaior to an application using aspects
Introducing data access with Spring
Simpli!ying 4/5C-based data access
/riing database transactions in a Spring
enironment
7
Course Agenda. /ay 6
Introducing ob2ect-to-relational mapping 7*8(9
:etting started with )ibernate in a Spring
enironment
;!!ectie web application architecture
:etting started with Spring (-C
8;S&!ul web serices with Spring (-C
8
Course Agenda. /ay 4
Securing web applications with Spring Security
1nderstanding Spring<s remoting !ramework
Simpli!ying message applications with Spring
4(S
Adding manageability to an application with
Spring 4(=
9
Coered in this section
Agenda
SpringSource, a diision o! "#ware
10
Build Run Manage
Spring, Grails
Tool Suite
tc server Hyperic
Application
Frameworks
and Tools
Lightweight
Application
Runtime
Application
Monitoring and
Management
B u i l d c u s t o m a p p s
f o r v i r t u a l a n d c l o u d
e n v i r o n m e n t s
R u n c u s t o m a p p s o n a
p l a t f o r m i d e a l l y s u i t e d f o r
v i r t u a l e n v i r o n m e n t s
R u n c u s t o m a p p s o n a
p l a t f o r m i d e a l l y s u i t e d f o r
v i r t u a l e n v i r o n m e n t s
SpringSource
A diision o! -(ware
11
Lightweight
App Runtime
Virtual App
Environment
Hybrid
Cloud
Spring
tc Server
VM
Spring
tc Server
Lightweight
App Framework
A /iision o! -(ware
12
*pensource contributions
Spring technologies
% SpringSource deelops >>$ o! the code o! the Spring !ramework
% Also leaders on the other Spring pro2ects 75atch, Security, Web
Flow???9
&omcat
% @#$ o! code commits in the past 3 years
% A#$ o! bug !iBes
Apache httpd 7most actie committers9
)yperic
:rooyC:rails
8abbit (D
13
&he Spring pro2ects
Spring
Framework
Spring WebFlow
Spring MVC
Spring Dynamic
Modules
Spring Security
Spring Batch
Spring Web
Services
Spring ROO
Spring .NET
Spring
Integration
Spring BlazeDS
Integration
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Overview of the Spring
Framework
Introducing Spring in the context of enterprise
application architecture
2
Topics in this session
Goal of the Spring Framework
Springs role in enterprise application
architecture
ore support
!e" application development support
#nterprise application development support
Spring Framework histor$
The Spring triangle
3
Goal of the Spring
Framework
%rovide comprehensive infrastructural support
for developing enterprise &ava' applications
Spring deals with the plum"ing
So $ou can focus on solving the domain pro"lem
4
Springs Support ()*
ore support
+pplication onfiguration
#nterprise Integration
Testing
,ata +ccess
5
+pplication onfiguration
+ t$pical application s$stem consists of several
parts working together to carr$ out a use case
Component A Component B
Component C
6
#xample- + .one$ Transfer
S$stem
TransferService
transfer(
300.00,
1, 2)
confirmatio
n
debit(300.00)
Accont!epositor"
#oadAccont(1)$
credit(300.00)
Accont 2
#oadAccont(2)$
pdateAccont(a1)$
pdateAccont(a2)$
ne%
Accont 1
ne%
a1
a2
7
Springs onfiguration
Support
Spring provides support for assem"ling such an
application s$stem from its parts
%arts do not worr$ a"out finding each other
+n$ part can easil$ "e swapped out
8
.one$ Transfer S$stem
+ssem"l$
TransferService&mp#
'dbcAccont!epositor"
Sprin(
(1) ne% 'dbcAccont!epositor"())$
(2) ne% TransferService&mp#()$
(3) service.setAccont!epositor"(repositor")$
*art 1
*art 2
Assemb#"
9
%arts are &ust %lain &ava
O"/ects
pb#ic c#ass TransferService&mp# imp#ements TransferService +
private Accont!epositor" accont!epositor"$
pb#ic void setAccont!epositor"(Accont!epositor" ar) +
accont!epositor" , ar$
-
)
-
pb#ic c#ass 'dbcAccont!epositor" imp#ements
Accont!epositor" +
)
-
*art 1
.epends on service interface$
concea#s comp#e/it" of imp#ementation$
a##o%s for s%appin( ot imp#ementation
*art 2
&mp#ements a service interface
10
0or 'dbc
Swapping Out %art
Implementations
TransferService&mp#
'dbcAccont!epositor"
Sprin(
(1) ne% 'dbcAccont!epositor"())$
(2) ne% TransferService&mp#()$
(3) service.setAccont!epositor"(repositor")$
1ibernateAccont!epositor"
(1) new HibernateAccountRepository()
(2) ne% TransferService&mp#()$
(3) service.setAccont!epositor"(repositor")$
StbAccont!epositor"
(1) new !tubAccountRepository()
(2) ne% TransferService&mp#()$
(3) service.setAccont!epositor"(repositor")$
0or 1ibernate 0or 2nit Testin(
11
#nterprise Integration
#nterprise applications do not work in isolation
The$ re0uire enterprise services and resources
,ata"ase onnection %ool
,ata"ase Transactions
Securit$
.essaging
1emote +ccess
aching
12
Spring #nterprise Integration
Spring helps $ou integrate powerful enterprise
services into $our application
!hile keeping $our application code simple and
testa"le
%lugs into all &ava ##' application servers
!hile capa"le of standalone usage
13
#nterprise .one$ Transfer
with Spring
TransferService&mp#
'dbcAccont!epositor"
Sprin(
Transaction3ana(er
.ataSorce
3Bean
4/porter
0or .B Connection *oo#in(
0or .B Transactions
0or '35 3ana(ement
14
Simple +pplication ode
pb#ic c#ass TransferService&mp# imp#ements TransferService +
6Transactiona#
pb#ic TransferConfirmation transfer(3onetar"Amont amont,
Strin( srcAccont&d, Strin( tar(etAccont&d) +
Accont src , accont!epositor".#oadAccont(srcAccont&d)$
Accont tar(et , accont!epositor".#oadAccont(tar(etAccont&d)$
src.debit(amont)$
tar(et.credit(amont)$
accont!epositor".pdateAccont(src)$
accont!epositor".pdateAccont(tar(et)$
retrn ne% TransferConfirmation(...)$
-
-
Te##s Sprin( to rn t7is met7od
in a database transaction
15
Testing
+utomated testing is essential
Spring ena"les unit testa"ilit$
,ecouples o"/ects from their environment
.aking it easier to test each piece of $our application
in isolation
Spring provides s$stem testing support
2elps $ou test all the pieces together
16
#na"ling 3nit Testing
import static or(.8nit.Assert.9$
pb#ic c#ass TransferService&mp#Tests +
private TransferService&mp# transferService$
6Before pb#ic void set2p() +
Accont!epositor" repositor" , ne% StbAccont!epositor"()$
transferService , ne% TransferService&mp#(repositor")$
-
6Test pb#ic void transfer3one"() +
TransferConfirmation confirmation ,
transferService.transfer(ne% 3onetar"Amont(300.00), 1, 2)$
assertEquals(ne% 3onetar"Amont(200.00),
confirmation.(et:e%Ba#ance())$
-
import static or(.8nit.Assert.9$
pb#ic c#ass TransferService&mp#Tests +
private TransferService&mp# transferService$
6Before pb#ic void set2p() +
Accont!epositor" repositor" , ne% StbAccont!epositor"()$
transferService , ne% TransferService&mp#(repositor")$
-
6Test pb#ic void transfer3one"() +
TransferConfirmation confirmation ,
transferService.transfer(ne% 3onetar"Amont(300.00), 1, 2)$
assertEquals(ne% 3onetar"Amont(200.00),
confirmation.(et:e%Ba#ance())$
-
3inimi;in( dependencies increases testabi#it"
Testin( #o(ic in iso#ation measres nit desi(n
and imp#ementation correctness
17
+ccessing ,ata
.ost enterprise applications access data stored
in a relational data"ase
To carr$ out "usiness functions
To enforce "usiness rules
18
Spring ,ata +ccess
Spring makes data access easier to do
effectivel$
.anages resources for $ou
%rovides +%I helpers
Supports all ma/or data access technologies
&,4
2i"ernate
&%+
&,O
i4atis
19
Spring &,4 in a 5utshell
+c0uisition of the connection
%articipation in the transaction
#xecution of the statement
%rocessing of the result set
2andling of an$ exception
1elease of the connection
int cont , 8dbcTemp#ate.<er"0or&nt(
=S4>4CT C?2:T(9) 0!?3 C2ST?34!=)$
int cont , 8dbcTemp#ate.<er"0or&nt(
=S4>4CT C?2:T(9) 0!?3 C2ST?34!=)$
A"" #an$"e$
by !prin%
!prin%&s '()* #e"per c"ass
20
Springs Support (6*
!e" application development support
Struts integration
&SF Integration
Spring .7 and !e" Flow
2andle user actions
7alidate input forms
#nforce site navigation rules
.anage conversational state
1ender responses (2T.89 :.89 etc*
21
Springs Support (;*
#nterprise application development support
,eveloping we" services
+dding managea"ilit$
Integrating messaging infrastructures
Securing services and providing o"/ect access control
Scheduling /o"s
22
Spring Framework 2istor$
http-<<www=springsource=org<download
Spring ;=> (released )6<>?9 currentl$ ;=>=>*
1e0uires &ava )=@A and &3nit B=CA
1#ST support9 &avaonfig9 Sp#89 more annotations
Spring 6=@ (released ))<>C9 currentl$ 6=@=D*
1e0uires &ava )=BA and supports &3nit B
+nnotation ,I9 E.7 controllers9 :.8 namespaces
Spring 6=> (released )><>D9 currentl$ 6=>=F*
ompati"le with &ava )=;A
:.8 simplification9 as$nc &.S9 &%+9 +spect& support
23
D
e
p
e
n
d
e
n
c
y

I
n

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
&etrie'ing bean instances
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 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'
(
)
(
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#epositor
y
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 uni0ue id
" The id reflects the ser'ice the bean pro'ides to clients
The ApplicationContext *orks as a container1
encapsulating the bean i(ple(entations
chosen for a gi'en deplo%(ent
" Conceals i(ple(entation details
9
Topics in this session
Spring 0uick start
!riting ben de"initions
" Configuring ob#ects
" $oing be%ond constructor instantiation
Creating an application context
&etrie'ing bean instances
Su((ar%
10
.asic Spring XML .ean
2efinition 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@%A%xsd0.
-E11 Add your bean definitions $ere 11.
-2beans.
-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@%A%xsd0.
-E11 Add your bean definitions $ere 11.
-2beans.
11
Si(plest 3ossible .ean
2efinition
-bean id&/ser!ice0 class&/example%Ser!iceImpl02. -bean id&/ser!ice0 class&/example%Ser!iceImpl02.
Ser!iceImpl ser!ice & ne, Ser!iceImpl()' Ser!iceImpl ser!ice & ne, Ser!iceImpl()'
&esults in 4'ia &eflection56
ApplicationContext ApplicationContext
ser!ice 1. instance of Ser!iceImpl ser!ice 1. instance of Ser!iceImpl
A class ,it$ no dependencies
12
Constructor 2ependenc%
In#ection
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-constructor1arg ref&/repository02.
-2bean.
-bean id&/repository0 class&/example%#epositoryImpl02.
-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)'
#epositoryImpl repository & ne, #epositoryImpl()'
Ser!iceImpl ser!ice & ne, Ser!iceImpl(repository)'
/0ui'alent to6
ApplicationContext ApplicationContext
ser!ice 1. instance of Ser!iceImpl
repository 1. instance of #epositoryImpl
ser!ice 1. instance of Ser!iceImpl
repository 1. instance of #epositoryImpl
A class ,it$ a single
dependency expected
by its constructor
13
Setter 2ependenc% In#ection
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-property name&/repository0 ref&/repository02.
-2bean.
-bean id&/repository0 class&/example%#epositoryImpl02.
-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)'
#epositoryImpl repository & ne, #epositoryImpl()'
Ser!iceImpl ser!ice & ne, Ser!iceImpl()'
ser!ice%set#epository(repository)'
/0ui'alent to6
ApplicationContext ApplicationContext
ser!ice 1. instance of Ser!iceImpl
repository 1. instance of #epositoryImpl
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 's7
Setters8
Spring supports both
+ou can (ix and (atch
15
The Case for Constructors
/nforce (andator% dependencies
3ro(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
Inherited auto(aticall%
17
$eneral &eco((endations
9ollo* standard :a'a design guidelines
" ,se constructors to set re0uired 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 it1 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.
-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)'
#eFuiredImpl reFuired & ne, #eFuiredImpl()'
OptionalImpl optional & ne, OptionalImpl()'
Ser!iceImpl ser!ice & ne, Ser!iceImpl(reFuired)'
ser!ice%setOptional(optional)'
/0ui'alent to6
19
In#ecting Scalar ;alues
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-property name&/stringProperty0 !alue&/foo0 2.
-2bean.
-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)'
Ser!iceImpl ser!ice & ne, Ser!iceImpl()'
ser!ice%setStringProperty(/foo0)'
/0ui'alent to6
ApplicationContext ApplicationContext
ser!ice 1. instance of Ser!iceImpl
public class Ser!iceImpl "
public !oid setStringProperty(String s) " %%% (
22 %%%
(
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.
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-property name&/integerProperty0 !alue&/:G0 2.
-2bean.
Ser!iceImpl ser!ice & ne, Ser!iceImpl()'
Integer !alue & :G'
ser!ice%setIntegerProperty(!alue)'
Ser!iceImpl ser!ice & ne, Ser!iceImpl()'
Integer !alue & :G'
ser!ice%setIntegerProperty(!alue)'
/0ui'alent to6
ApplicationContext ApplicationContext
ser!ice 1. instance of Ser!iceImpl
public class Ser!iceImpl "
public !oid setIntegerProperty(Integer i) " %%% (
22 %%%
(
public class Ser!iceImpl "
public !oid setIntegerProperty(Integer i) " %%% (
22 %%%
(
21
In#ecting lists
-bean id&/ser!ice0
class&/com%springsource%,are$ouse%In!entory?anagerImpl0.
-property name&/,are$ouse5ist0.
-list.
-ref bean&H,are$ouse8H2.
-ref bean&H,are$ouse:H2.
-ref bean&H,are$ouse@H2.
-2list.
-2property.
-2bean.
-bean id&/ser!ice0
class&/com%springsource%,are$ouse%In!entory?anagerImpl0.
-property name&/,are$ouse5ist0.
-list.
-ref bean&H,are$ouse8H2.
-ref bean&H,are$ouse:H2.
-ref bean&H,are$ouse@H2.
-2list.
-2property.
-2bean.
In!entory?anagerImpl manager & ne, In!entory?anagerImpl()'
manager%setIare$ouse5ist(list)' 22 create list ,it$ bean references
In!entory?anagerImpl manager & ne, In!entory?anagerImpl()'
manager%setIare$ouse5ist(list)' 22 create list ,it$ bean references
/0ui'alent to6
ApplicationContext ApplicationContext
manager 1. instance of In!entory?anagerImpl
22
In#ecting other t%pes of
collection
Si(ilar support a'ailable for
" 3roperties 4through props < prop ele(ents5
" Set 4through a set ele(ent1 si(ilar to list5
" Map 4through (ap < ke% ele(ents5
Some more ad!anced features about collections ,ill be seen later ,it$
t$e util namespace
23
Topics in this session
)o* Spring *orks
!riting Spring bean definitions
" Configuring ob#ects
" #oing beyond constructor instntition
Creating a Spring application context
&etrie'ing bean instances
Su((ar%
24
The factor%-(ethod attribute
=on-intrusi'e
" ,seful for existing Singletons or 9actories
public class 5egacySingleton "
pri!ate static 5egacySingleton inst & ne, 5egacySingleton()'
pri!ate 5egacySingleton() " %%% (
public static 5egacySingleton getInstance() "
return inst'
(
(
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.
-bean id&/ser!ice0 class&/example%5egacySingleton0
factory-method="getInstance" 2.
getInstance() s$ould al,ays be static
25
3>:>s as 9actor% .eans
An% 3>:> can be used as a factor%
-bean id&/clientSer!iceFactory0 class&/example%ClientSer!iceFactory02.
-bean id&/clientSer!ice0 factory-ean=!c"#ent$er%#ce&actory'
factory1met$od&Hget+e,InstanceH.
-bean id&/clientSer!iceFactory0 class&/example%ClientSer!iceFactory02.
-bean id&/clientSer!ice0 factory-ean=!c"#ent$er%#ce&actory'
factory1met$od&Hget+e,InstanceH.
public class ClientSer!iceFactory "
%%%
public ClientSer!ice get+e,Instance() "
%%%
(
(
public class ClientSer!iceFactory "
%%%
public ClientSer!ice get+e,Instance() "
%%%
(
(
+o need for class attribute
26
The 9actor%.ean interface
3art of the Spring fra(e*ork
,sed b% (an% Spring classes
" can also choose to use this %ourself
(u"#c c"ass ClientSer!iceFactory;ean #m("ements
Factory;ean-ClientSer!ice. "
22%%%
(u"#c ClientSer!ice getOb3ect() thro)s Jxception "
return clientSer!ice'
(
(u"#c Class-C. getOb3ectype() "
return ClientSer!ice%c"ass'
(
(u"#c oo"ean isSingleton() " return true' (
(
(u"#c c"ass ClientSer!iceFactory;ean #m("ements
Factory;ean-ClientSer!ice. "
22%%%
(u"#c ClientSer!ice getOb3ect() thro)s Jxception "
return clientSer!ice'
(
(u"#c Class-C. getOb3ectype() "
return ClientSer!ice%c"ass'
(
(u"#c oo"ean isSingleton() " return true' (
(
27
The 9actor%.ean interface
.eans i(ple(enting 9actor%.ean are
auto-detected
2ependenc% in#ection using the factor% bean id
causes get>b#ect45 to be in'oked transparentl%
-bean id&/cpxSer!ice0 class&/example%ComplexSer!iceFactory0 2.
-bean id&/controller0 class&/example%?yController0.
-property name&/ser!ice0 ref&/cpxSer!ice0 2.
-2bean.
-bean id&/cpxSer!ice0 class&/example%ComplexSer!iceFactory0 2.
-bean id&/controller0 class&/example%?yController0.
-property name&/ser!ice0 ref&/cpxSer!ice0 2.
-2bean.
28
9actor%.eans in Spring
:ndi>b#ect9actor%.ean
" >ne option for looking up :=2I ob#ects
9actor%.eans for creating re(oting proxies
9actor%.eans for configuring data access
technologies like )ibernate1 :3A or i.atis
29
Topics in this session
Spring 0uick 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(ent1 including
" :,nit s%ste( test
" !eb application
" /nterprise :a'a .ean 4/:.5
" 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(ple6 ,sing an Application
Context Inside a :,nit S%ste( Test
import static org%3unit%Assert%K'
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)'
(
(
import static org%3unit%Assert%K'
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 9lexible &esource
Loading Mechanis(
ApplicationContext i(ple(entations ha'e
default resource loading rules
ne, ClassPat$=mlApplicationContext(/com2acme2application1config%xml0)'

ne, ClassPat$=mlApplicationContext(/com2acme2application1config%xml0)'

ne, FileSystem=mlApplicationContext(/C6LLetcLLapplication1config%xml0)'
22 absolute pat$6 C6LetcLapplication1config%xml
ne, FileSystem=mlApplicationContext(/%2application1config%xml0)'
22 pat$ relati!e to t$e JM? ,or>ing directory
ne, FileSystem=mlApplicationContext(/C6LLetcLLapplication1config%xml0)'
22 absolute pat$6 C6LetcLapplication1config%xml
ne, FileSystem=mlApplicationContext(/%2application1config%xml0)'
22 pat$ relati!e to t$e JM? ,or>ing directory
NC5ASSPAO2com2acme2application1config%xml
=mlIebApplicationContext is also a!ailable
1 $e pat$ is relati!e to t$e Ieb application
1 4sually created indirectly !ia a declaration in ,eb%xml
33
Creating a Spring Application
Context fro( Multiple 9iles
A context can be configured fro( (ultiple files
Allo*s partitioning of bean definitions into
logical groups
$enerall% a best practice to separate out
@applicationA beans fro( @infrastructureA beans
" Infrastructure often changes bet*een en'iron(ents
" /'ol'es at a different rate
34
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.
-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 a local Oracle en!ironment
35
-beans.
-E11 creates an in1memory database populated ,it$ test data for fast testing 11.
-bean id&HdataSourceH
class&Horg%sf,%3dbc%datasource%embedded%Jmbedded*atabaseFactory;eanH.
-property name&HdatabasePopulatorH ref&HpopulatorH2.
-2bean.

-bean id&HpopulatorH %%%.
%%%
-beans.
-E11 creates an in1memory database populated ,it$ test data for fast testing 11.
-bean id&HdataSourceH
class&Horg%sf,%3dbc%datasource%embedded%Jmbedded*atabaseFactory;eanH.
-property name&HdatabasePopulatorH ref&HpopulatorH2.
-2bean.

-bean id&HpopulatorH %%%.
%%%
3artitioning 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.
-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
36
.ootstrapping in /ach
/n'iron(ent
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(
/application1config%xml0B /test1infrastructure1config%xml0 )'
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(
/application1config%xml0B /test1infrastructure1config%xml0 )'
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(
/application1config%xml0B /oracle1infrastructure1config%xml0)'
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(
/application1config%xml0B /oracle1infrastructure1config%xml0)'
In the test en'iron(ent
In the production >racle en'iron(ent
37
!orking *ith prefixes
2efault rules can be o'erridden
;arious prefixes
" classpath6
" file6
" http6
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(
/config2dao1config%xml0B /config2ser!ice1config%xml0B
/file*oracle1infrastructure1config%xml0 )'
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(
/config2dao1config%xml0B /config2ser!ice1config%xml0B
/file*oracle1infrastructure1config%xml0 )'
$ese prefixes can be used any,$ere Spring needs to deal ,it$
resources (not 3ust in constructor args to application context)
prefix
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
$etrie%ing ben instnces
Su((ar%
39
Accessing a .ean in Spring B
Cast is not co(pulsor% an%(ore
ApplicationContext context & ne, ClassPat$=mlApplicationContext(%%%)'
22 Classic ,ay6 cast is needed
ClientSer!ice ser!ice8 & (ClientSer!ice) context%get;ean(/clientSer!ice0)'
22 Since Spring @%A6 no more castB type is a met$od param
ClientSer!ice ser!ice: & context%get;ean(/clientSer!ice0B ClientSer!ice%class)'
22 +o need for bean id if type is uniFue
ClientSer!ice ser!ice@ & context%get;ean(ClientSer!ice%class )'
+e, in
Spring @%A
40
Topics in this session
)o* Spring *orks
!riting Spring bean definitions
" Configuring ob#ects
" $oing be%ond constructor instantiation
Creating a Spring application context
&etrie'ing bean instances
Summry
41
.enefits of 2ependenc%
In#ection
+our ob#ect is handed *hat it needs to *ork
" 9rees it fro( the burden of resol'ing its dependencies
" Si(plifies %our code1 i(pro'es code reusabilit%
3ro(otes progra((ing to interfaces
" Conceals the i(ple(entation details of each dependenc%
I(pro'es testabilit%
" 2ependencies 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 "ML namespaces
#S$-%&' annotations
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 /.eans01
language
) 2ro-ide a.straction and semantic -alidation
) Simplify common configuration needs
3ach language is defined .y its o4n "ML
namespace you may import
) 5ou can e-en 4rite your o4n
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-'.0.xsd
h!"##$$$.s!ring%rame$or&.org#schema#conex
h!"##$$$.s!ring%rame$or&.org#schema#conex#s!ring-conex-'.0.xsd>
<--- .o/ can no$ /se <conex"0#> ags -->
<#beans>
1ssign names!ace a !re%ix
1ssociae names!ace $ih is ),2
5
Benefits of Using ,amespace
+onfiguration
<beans>
<bean class=org.s!ring%rame$or&.beans.%acor3.con%ig.
4ro!er34laceholder5on%ig/rer>
<!ro!er3 name=locaion val/e=#678-9:F#daaso/rce.!ro!eries #>
<#bean>
<#beans>
<beans ... >
<conex"!ro!er3-!laceholder locaion=#678-9:F#daaso/rce.!ro!eries #>
<#beans>
Before
After
;eneric bean#!ro!er3
s3nax is all ha<s available
=e>/ires remembering
%rame$or& classnames
5reaes same bean as
above? b/ hides
%rame$or& deails
1rib/es are s!eci%ic o
he as&? raher han
generic name#val/e !airs
6
,amespaces Summary
,amespace configuration is a.out simplification
and e(pressi-eness
) 6eneric .ean0property synta( can .e too lo4-le-el
) 7ides frame4ork details
,amespaces are defined for categories of
related frame4ork functionality
8
) aop9 .eans9 conte(t9 :ee9 :ms9 t(9 util
;e 4ill 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
JSR-250 nnottions
The lifecycle of a Spring application conte(t
) The initiali*ation phase
) The use phase
) The destruction phase
Bean scoping
8
A 2rimer on #S$-%&'
<+ommon Annotations=
#S$-%&' pro-ides a set of common annotations
for use in #a-a 33 applications
) 7elps a-oid proliferation of frame4ork-specific
annotations
) Facilitates porta.ility
) Used .y 3#B >?'
) Used .y Spring9 starting 4ith -ersion %?&
9
#S$-%&' 2rimer9 cont?
All annotations reside in the :a-a(?annotation
package
) Included in the #@A starting in #a-a B
) A-aila.le as part of the !:a-aee-api! :ar for #a-a &
To name a fe4
) C2ost+onstruct
) C2re@estroy
) C$esource
Spring makes use of these annotations to
trigger lifecycle e-ents
10
Topics in this session
Introduction to Spring!s "ML namespaces
#S$-%&' annotations
!he li"ecycle o" Spring ppliction context
) The initiali*ation phase
) The use phase
) The destruction phase
Bean scoping
11
2hases of the Application
Lifecycle
9niiali@aion Use 2esr/cion
2repares 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
) 2rocess client
reDuests
) +arry out
application
.eha-iors
EE?EEF of the
time is spent in
this phase
Shuts do4n
Application
ser-ices
) $elease any
system resources
) Are eligi.le for
gar.age
collection
12
Springs $ole as a Lifecycle
Manager
For nearly any class of application
) Standalone #a-a application
) #Unit System Test
) #a-a 33G 4e. application
) #a-a 33G enterprise application
Spring fits in to manage the application lifecycle
) 2lays an important role in all phases
13
Topics in this session
Introduction to Spring!s "ML namespaces
The lifecycle of a Spring application conte(t
) !he initili#tion phse
) The use phase
) The destruction phase
Bean scoping
9niiali@aion Use 2esr/cion
14
The Lifecycle of a Spring Application
+onte(t HIJ - The Initiali*ation 2hase
;hen a conte(t is created the initiali*ation
phase completes
But 4hat e(actly happens in this phaseK
## 5reae he a!!licaion %rom he con%ig/raion
1!!licaion5onex conex = ne$ 5lass4ah)ml1!!licaion5onexA
a!!licaion-con%ig.xml?
es-in%rasr/c/re-con%ig.xml
BC
15
Inside The Application +onte(t
Initiali*ation Lifecycle
$od ben de"initions
Initiali*e .ean instances
16
Load Bean @efinitions
The "ML files are parsed
Bean definitions are loaded into the conte(ts
8eanFacor3
D 3ach inde(ed under its id
Special 8eanFacor34os4rocessor .eans are
in-oked
D +an modify the definition of any .ean
17
1!!licaion 5onex 1!!licaion 5onex
Load Bean @efinitions
<beans>
<bean id=rans%er,ervice E
<bean id=acco/n=e!osior3E
<#beans>
<beans>
<bean id=rans%er,ervice E
<bean id=acco/n=e!osior3E
<#beans>
a!!licaion-con%ig.xml
<beans>
<bean id=daa,o/rce E
<#beans>
<beans>
<bean id=daa,o/rce E
<#beans>
es-in%rasr/c/re-con%ig.xml
rans%er,ervice
acco/n=e!osior3
rans%er,ervice
acco/n=e!osior3
8eanFacor3
8eanFacor34os4rocessors
!os4rocessA8eanFacor3B
rans%er,ervice
acco/n=e!osior3
daa,o/rce
rans%er,ervice
acco/n=e!osior3
daa,o/rce
5an modi%3 he de%iniion o%
an3 bean in he %acor3
be%ore an3 obFecs are creaed
18
The BeanFactory2ost2rocessor
3(tension 2oint
Useful for applying transformations to groups of
.ean definitions
) Before any o.:ects are actually created
Se-eral useful implementations are pro-ided .y
the frame4ork
5ou can also 4rite your o4n
) Implement the BeanFactory2ost2rocessor interface
19
An 3(ample
BeanFactory2ost2rocessor
D
PropertyPlaceholderConfigurer su.stitutes
LM-aria.lesN in .ean definitions 4ith -alues
from ?properties files
20
7o4 2roperty2laceholder+onfigurer
;orks
4ro!er34laceholder5on%ig/re
r
,!ring 1!!licaion 5onex
Aa%er bean de%iniions are loadedB
!os4rocessA8eanFacor3B
8ean de%iniion
daa,o/rce
U=+=GHdaaso/rce./rlI
/ser=GHdaaso/rce./serI
8ean de%iniion
daa,o/rce
U=+=Fdbc"oracle"E
/ser=mone3rans%er-a!!
21
Using
2roperty2laceholder+onfigurer
<beans>
<bean id=daa,o/rce class=com.oracle.Fdbc.!ool.Jracle2aa,o/rce>
<!ro!er3 name=U=+ val/e=GHdaaso/rce./rlI #>
<!ro!er3 name=/ser val/e=GHdaaso/rce./serI #>
<#bean>
<bean class=org.s!ring%rame$or&.beans.%acor3.con%ig.
4ro!er34laceholder5on%ig/rer>
<!ro!er3 name=locaion val/e=#678-9:F#daaso/rce.!ro!eries #>
<#bean>
<#beans>
File $here he variable
val/es reside
datasource.url!d"c#oracle#thin#$localhost#1521#%&'(
datasource.user)oneytransfer*app
daaso/rce.!ro!eries
Kariables o re!lace
7asil3 ediable
22
Simplifying configuration 4ith
/conte(tOproperty-placeholder1
<beans ... >
<bean id=daa,o/rce class=com.oracle.Fdbc.!ool.Jracle2aa,o/rce>
<!ro!er3 name=U=+ val/e=GHdaaso/rce./rlI #>
<!ro!er3 name=/ser val/e=GHdaaso/rce./serI #>
<#bean>
<conex"!ro!er3-!laceholder locaion=#678-9:F#daaso/rce.!ro!eries #>
<#beans>
5reaes he same 4ro!er34laceholder5on%ig/rer
bean de%iniion in a more concise %ashion
23
Inside the Application +onte(t
Initiali*ation Lifecycle
Load .ean definitions
%nitili#e ben instnces
24
Initiali*ing Bean Instances
3ach .ean is eagerly instantiated .y default
) +reated in the right order 4ith its dependencies
in:ected
After dependency in:ection each .ean goes
through a post-processing phase
) ;here 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
25
Bean Initiali*ation Steps
8ean
9nsaniaed
8ean
9nsaniaed
2e!endencies
9nFeced
2e!endencies
9nFeced
8ean 4os
4rocessed
8ean 4os
4rocessed
8ean
=ead3
For Use
8ean
=ead3
For Use
26
Bean 2ost 2rocessing
Bean post processing can .e .roken do4n into
t4o steps
) Initiali*e the .ean if instructed
) +all special 8ean4os4rocessors to perform additional
configuration
27
Bean 2ost 2rocessing Steps
%nitili#e the ben i" instructed
+all special 8ean4os4rocessors to perform
additional configuration
28
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 4ay to do it
) #S$-%&' C2ost+onstruct
) /.ean01 init-method attri.ute
) Implement Spring!s Initiali*ingBean interface
29
Bean Initiali*ation
TechniDues
&'ostConstruct
init-method
Initiali*ingBean
30
$egistering for Initiali*ation
4ith C2ost+onstruct
!/blic class Trans%er,ervice9m!l H
L4os5onsr/c
void iniAB H

## 3o/r c/som iniiali@aion code
I
I
!/blic class Trans%er,ervice9m!l H
L4os5onsr/c
void iniAB H

## 3o/r c/som iniiali@aion code
I
I
:o resricions on
mehod name or visibili3
Tells ,!ring o call his
mehod a%er
de!endenc3 inFecion
This is the preferred initiali*ation techniDue
) Fle(i.le9 a-oids depending on Spring A2Is
) $eDuires Spring %?& or .etter
31
3na.ling +ommon Annotation-
Based Initiali*ation
C2ost+onstruct 4ill .e ignored unless Spring is
instructed to detect and process it
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice9m!l #>
<bean class=org.s!ring%rame$or&.conex.annoaion.
5ommon1nnoaion8ean4os4rocessor #>
<#beans>
2eecs and invo&es an3
mehods annoaed $ih
L4os5onsr/c
32
Simplifying +onfiguration 4ith
/conte(tOannotation-config1
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice9m!l #>
<conex"annoaion-con%ig#>
<#beans>
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice9m!l #>
<conex"annoaion-con%ig#>
<#beans>
7nables m/li!le 8ean4os4rocessors? incl/ding"

=e>/ired1nnoaion8ean4os4rocessor
5ommon1nnoaion8ean4os4rocessor
33
Bean Initiali*ation
TechniDues
C2ost+onstruct
init-method
Initiali*ingBean
34
Initiali*ing a Bean 5ou @o
,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.8ro&er,ervice
ini-mehod=sar>
E
<#bean>
*ehod can be an3 visibili3? b/ m/s have no arg/mens
5lass $ih no ,!ring de!endenc3
35
Bean Initiali*ation
TechniDues
C2ost+onstruct
init-method
%nitili#ing(en
36
$egistering for an
Initiali*ation +all.ack 4ith
Initiali*ingBean
Initiali*ation techniDue used prior to Spring %?&
) @isad-antageO Ties your code to the frame4ork
) Ad-antageO The only 4ay to enforce initiali*ation
code should run Hnot affected .y configuration
changesJ
!ac&age org.s!ring%rame$or&.beans.%acor3C
!/blic iner%ace 9niiali@ing8ean H
!/blic void a%er4ro!eries,eABC
I
37
!/blic class *essage=eceiver im!lemens 9niiali@ing8ean H
!/blic void a%er4ro!eries,eAB H
## allocae message receiving reso/rces
I
I
<beans>
<bean id=message=eceiver class=exam!le.*essage=eceiver #>
<#beans>
9m!lemens
s!ecial ,!ring
li%ec3cle iner%ace
,!ring invo&es mehod a/omaicall3
:o oher con%ig/raion re>/ired
$egistering for an
Initiali*ation +all.ack 4ith
Initiali*ingBean
38
Bean 2ost 2rocessing Steps
Initiali*e the .ean if instructed
Cll specil %eanPostProcessors to per"orm
dditionl con"igurtion
39
The Bean2ost2rocessor
3(tension 2oint
An important e(tension point in Spring
+an modify .ean instances in any 4ay
) 2o4erful ena.ling feature
Se-eral implementations are pro-ided .y the
frame4ork
,ot common to 4rite your o4n
40
An 3(ample
Bean2ost2rocessor
$eDuiredAnnotationBean2ost2rocessor
) 2ro-ided .y the frame4ork
) 3nforces that &Re)uired properties are set
) Must .e e(plicitly ena.led -ia configuration
41
Using
$eDuiredAnnotationBean2ost2rocessor
!/blic class Trans%er,ervice9m!l im!lemens Trans%er,ervice H
!rivae 1cco/n=e!osior3 acco/n=e!osior3C
L=e>/ired
!/blic void se1cco/n=e!osior3A1cco/n=e!osior3 arB H
his.acco/n=e!osior3 = arC
I
I
!/blic class Trans%er,ervice9m!l im!lemens Trans%er,ervice H
!rivae 1cco/n=e!osior3 acco/n=e!osior3C
L=e>/ired
!/blic void se1cco/n=e!osior3A1cco/n=e!osior3 arB H
his.acco/n=e!osior3 = arC
I
I
9ndicaes he de!endenc3
is re>/ired
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice9m!l #>
<bean class=org.s!ring%rame$or&.beans.%acor3.annoaion.
=e>/ired1nnoaion8ean4os4rocessor #>
<#beans>
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice9m!l #>
<bean class=org.s!ring%rame$or&.beans.%acor3.annoaion.
=e>/ired1nnoaion8ean4os4rocessor #>
<#beans>
1/omaicall3 deecedC no oher con%ig/raion is necessar3
Property 'accountRepository' is
required for bean 'transferService'
42
Simplifying +onfiguration
4ith /conte(tOannotation-config1
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice9m!l #>
<conex"annoaion-con%ig#>
<#beans>
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice9m!l #>
<conex"annoaion-con%ig#>
<#beans>
1/omaicall3 enables =e>/ired1nnoaion8ean4os4rocessor
$emem.er /conte(tOannotation-config1K
43
Topics in this session
Introduction to Spring!s "ML namespaces
The lifecycle of a Spring application conte(t
) The initiali*ation phase
) !he use phse
) The destruction phase
Bean scoping
Use 2esr/cion 9niiali@aion
44
The Lifecycle of a Spring Application
+onte(t H%J - The Use 2hase
;hen you in-oke a .ean o.tained from the
conte(t the application is used
But e(actly 4hat happens in this phaseK
1!!licaion5onex conex = ## ge i %rom some$here
## +oo&/! he enr3 !oin ino he a!!licaion
Trans%er,ervice service =
ATrans%er,erviceB conex.ge8eanArans%er,erviceBC
## Use i-
service.rans%erAne$ *onear31mo/nAM0.00B? 1? (BC
45
Inside The Bean $eDuest
HUseJ Lifecycle
If the .ean is :ust your ra4 o.:ect it is simply
in-oked directly Hnothing specialJ
If your .ean has .een 4rapped in a pro(y
things get more interesting
Trans%er,ervice9m!l
rans%erAGM0? 1? (B
rans%erAGM0? 1? (B
Trans%er,ervice9m!l
,!ring 4rox3
46
2ro(y 2o4er
A 8ean4os4rocessor may 4rap your .eans in a
dynamic pro(y and add .eha-ior to your
application logic transparently
Trans%er,ervice9m!l
rans%erAGM0? 1? (B
,!ring
Transacion9nerce!or
Transacion*anager
begin commi
Transacion
managemen
behavior is added
aro/nd 3o/r code
,!ring 4rox3
47
2ro(ies are +entral to the Spring
Triangle
Simple
Object
*
e
p
e
n
d
e
n
c
y

%
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
.nterprise Ser/ice ,bstrctions
1. The 1!!licaion
conex drives bean
con%ig/raion
(. 23namic !roxies
add behaviors o
3o/r beans
'. ,!ring can inegrae man3
ener!rise behaviors
48
Bean Initiali*ation Steps
8ean
9nsaniaed
8ean
9nsaniaed
2e!endencies
9nFeced
2e!endencies
9nFeced
8ean 4os
4rocessed
8ean 4os
4rocessed
8ean
=ead3
For Use
8ean
=ead3
For Use
4roxies are
creaed here
49
Topics in this session
9niiali@aion
Introduction to Spring!s "ML namespaces
The lifecycle of a Spring application conte(t
) The initiali*ation phase
) The use phase
) !he destruction phse
Bean scoping
Use 2esr/cion
50
The Lifecycle of a Spring Application
+onte(t H>J - The @estruction 2hase
;hen you close a conte(t the destruction phase
completes
But e(actly 4hat happens in this phaseK
5on%ig/rable1!!licaion5onex conex = E
## 2esro3 he a!!licaion
conex.closeABC
51
Inside the Application
+onte(t @estruction Lifecycle
@estroy .ean instances if instructed
@estroy itself
) The conte(t is not usa.le again
52
@estroy 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 4ay to do it
) #S$-%&' C2re@estroy
) /.ean01 destroy-method attri.ute
) Implement Spring!s @isposa.leBean interface
53
Bean @estruction TechniDues
&'re*estroy
destroy-method
@isposa.leBean
54
$egistering for @estruction
4ith C2re@estroy
!/blic class Trans%er,ervice9m!l H
L4re2esro3
void release=eso/rcesAB H
## 3o/r c/som desr/cion code
I
I
!/blic class Trans%er,ervice9m!l H
L4re2esro3
void release=eso/rcesAB H
## 3o/r c/som desr/cion code
I
I
:o resricions on mehod
name or visibili3
Tells ,!ring o call his
mehod !rior o desro3ing he
bean insance
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice9m!l #>
<conex"annoaion-con%ig#>
<#beans>
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice9m!l #>
<conex"annoaion-con%ig#>
<#beans>
7nables common
annoaion !rocessing
55
Bean @estruction TechniDues
C2re@estroy
destroy-method
@isposa.leBean
56
@estroying a Bean 5ou @o
,ot +ontrol
Use destroy-method to dispose a .ean you do
not control the implementation of
<bean id=daa,o/rce
class=org.a!ache.commons.dbc!.8asic2aa,o/rce
desro3-mehod=close>
E
<#bean>
*ehod can be an3 visibili3? b/ m/s have no arg/mens
5lass $ih no ,!ring de!endenc3
57
Bean @estruction TechniDues
C2re@estroy
destroy-method
*isposble(en
58
$egistering for a @estruction
+all.ack 4ith @isposa.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.%acor3C
!/blic iner%ace 2is!osable8ean H
!/blic void desro3ABC
I
59
Topics in this session
Introduction to Spring!s "ML namespaces
#S$-%&' annotations
The lifecycle of a Spring application conte(t
) The initiali*ation phase
) The use phase
) The destruction phase
(en scoping
60
Bean Scoping
Spring puts each .ean instance in a scope
Singleton scope is the default
) The <single= instance is scoped .y the conte(t itself
) By far the most common
Pther scopes can .e used on a .ean-.y-.ean
.asis
<bean id=m38ean class=exam!le.*38ean
sco!e=E>
<#bean>
4/ his bean in some oher sco!e
61
A-aila.le Scopes
D
prototype - A ne4 instance is created each time
the .ean is referenced
D
session - A ne4 instance is created once per
user session
D
re,uest - A ne4 instance is created once per
reDuest
D
custo) - 5ou define your o4n rules
) Ad-anced feature
62
Scoped @ependencies of
Singletons
Session-9 reDuest- or custom-scoped .eans often
act as dependency of singleton
;hat 4ill happen in this caseK
<bean id=Nsho!!ing,erviceN class=Nexam!le.,ho!!ing,ervice9m!lN>
<!ro!er3 name=Nsho!!ing5arN re%=Nsho!!ing5arN#>
<#bean>
<bean id=Nsho!!ing5arN class=Nexam!le.,ho!!ing5arN scope-session-#>
63
Pne-time In:ection
Singleton 4ill only .e in:ected once, on startup
,o current 7TT2 Session9 so you!ll get an error
) 3-en if there 4as a Session9 the ser-ice 4ould use the
same Shopping+art e-ery time
+ould fi( .y using lookup instead of in:ection
) In:ect the conte(t and call 1!!licaion5onex.ge8ean
) UglyO ties your code to Spring9 hard to test
<bean id=Nsho!!ing,erviceN class=Nexam!le.,ho!!ing,ervice9m!lN>
<!ro!er3 name=Nsho!!ing5arN re%=Nsho!!ing5arN#>
<#bean>
<bean id=Nsho!!ing5arN class=Nexam!le.,ho!!ing5arN sco!e=NsessionN#>
64
Scoped 2ro(ies
Solution is to proxy the scoped dependency
2ro(y delegates to correct instance for current
reDuest or session or custom conte(t
Same pro(y can .e used .y singleton for its
entire lifecycle9 so dependency in:ection 4orks
Built-in feature of Spring using ao! namespaceO
<bean id=Nsho!!ing,erviceN class=Nexam!le.,ho!!ing,ervice9m!lN>
<!ro!er3 name=Nsho!!ing5arN re%=Nsho!!ing5arN#>
<#bean>
<bean id=Nsho!!ing5arN class=Nexam!le.,ho!!ing5arN sco!e=NsessionN>
.aop#scoped*pro/y01
<#bean>
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
Spring #pression $anguage
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>
<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>
<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>
<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
Spring #pression $anguage
8
Inner Beans
Sometimes a bean naturally scopes the
definition of another bean
+ The .scoped/ bean is not useful to anyone else
0a1e the scoped bean an inner bean
+ 0ore 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>
<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>
<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>
0ultiple $e(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
Spring #pression $anguage
13
Introducing Propertyditor
%&'
In 20$ all literal (alues are te#t 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>
<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
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
pac1age
Some highlights
G -ustom)umber1ditor con(erts to the "umber types
G -ustom(oolean1ditor con(erts to Boolean
G -ustomDate1ditor con(erts to 3a(a7util7Date
G Resource(undle1ditor con(erts to a Resource
G /roperties1ditor con(erts to 3a(a7util7Properties
G (yteArray/roperty1ditor con(erts to a byte89
G ocale1ditor con(erts to a $ocale
16
Built6In Propertyditor
#ample
<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 e#tending /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
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
Spring #pression $anguage
20
Importing Config !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 Config !iles %4'
import tag uses relati(e path by default
This can be o(erriden using prefi#es
<beans>
<import resource=account-con,i2.3ml +>
<import resource=re5ards-con,i2.3ml +>
...
<+beans>
<beans>
<import resource=classpat#"com+sprin2source+account-con,i2.3ml +>
...
<+beans>
22
Importing Configuration !iles
%:'
Promotes splitting configuration into logical groups of
bean definitions
nables reuse across modules )ithin an application
Complements the option of creating an
ApplicationConte#t from multiple files
Application-onte3t conte3t =
ne5 -lass/at#MmlApplication-onte3t:
ne5 Strin2> A B
classpat#"com+module%+module-con,i2.3mlN
classpat#"com+module'+module-con,i2.3ml
D;4
23
Topics in this session
Bean Definition Inheritance
Inner Beans
Property ditors
Importing Configuration !iles
Bean &aming
The p "amespace
The util "amespace
Spring #pression $anguage
24
Bean "aming
0ost beans are assigned a unique name )ith the id
attribute
As an 20$ 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
25
Assigning a Bean 0ultiple
"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+>
26
Topics in this session
Bean Definition Inheritance
Inner Beans
Property ditors
Importing Configuration !iles
Bean "aming
)he p &amespace
The util "amespace
Spring #pression $anguage
27
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;
28
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;
29
Considerations of the p
namespace
Requires a namespace definition;
"amespace not specified in an 2SD file< unli1e
other Spring namespaces
+ So no e#tra schema$ocation entry required
3mlns"p=#ttp"++555.sprin2,rame5orF.or2+sc#ema+p
30
Topics in this session
Bean Definition Inheritance
Inner Beans
Property ditors
Importing Configuration !iles
Bean "aming
The p "amespace
)he util &amespace
Spring #pression $anguage
31
Spring=s *til "amespace
*util('+ is one of the .out6of6the6bo#/ namespaces you
can import
-ffers high6le(el configuration for common utility tas1s
+ Populating collections
+ Accessing constants %static fields'
+ $oading properties
Also possible to load collections using the default .beans/
namespace
+ Collections in the .util/ namespace propose some more
ad(anced features
32
Configuring a $ist
<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
33
Ad(anced configuration
<bean id=in!entoryQana2er class=,oo.Qy<n!entoryQana2er>
<property name=5are#ouses>
<util"list list-class=ja!a.util.Arrayist
!alue-type=,oo.0are#ouse>
<re, 9 +>
<+util"list>
<+property>
<+bean>
De,ault 6a!a type ,or
nested !alues
ist implementation
instantiated by Sprin2
34
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.
id is reIuired
35
Configuring a 0ap %&'
<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
36
Configuring a 0ap %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>
<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
37
Accessing Constants
<bean id=noti,icationSer!ice
class=e3ample.Qy)oti,icationSer!ice>
<property name=#ttp/ort>
<util"constant static-,ield=e3ample.Qy-onstants.8KK/H/ORK +>
<+property>
<+bean>
Accesses static ,ield in t#e Qy-onstants class
public class Qy-onstants B
...
public static ,inal int HTTP_POT = T?4
...
D
38
$oading 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
39
Topics in this session
Bean Definition Inheritance
Inner Beans
Property ditors
Importing Configuration !iles
Bean "aming
The p "amespace
The util "amespace
Spring $xpression ,anguage
40
Spring #pression $anguage
Spring :7> introduces ne) #pression $anguage
+ Sp$ for short
*se programmatically< )ith 20$ or annotations
Inspired by ,eb!lo) $< superset of unified $
+ Property ? inde#ed collections access< incl7 filtering
and pro3ection
+ !unctions< operators< etc7
+ Can also call methods@constructors
Pluggable@e#tendable by other Spring6based
frame)or1s
41
Sp$ Conte#t Attributes
$ Attributes can be;
+ "amed Spring beans
+ Implicit references
Some global implicit references;
+ system/roperties
+ system1n!ironment
0ore a(ailable in )eb applications
#tensible through API
+ e7g7 Spring Security adds AprincipalA
42
Sp$ 20$ #ample
<bean class=Umycompany.Re5ardsKestDatabaseU>
<property name=Udatabase)ameU
!alue=U"#syste$Properties%database&a$e'U +>
<property name=UusernameU
!alue=U"#dbProps%userna$e'U+>
<property name=UFeyVeneratorU
!alue=U"#strate(y)ean%database*ey+enerator'U +>
<+bean>
<util"properties id=Udb/ropsU
location=Uclasspat#"db-con,i2.propertiesU+>
<bean id=Ustrate2y(eanU class=Umycompany.De,aultStrate2iesU>
<property name=Udatabase*eyVeneratorU re,=Umy*eyVeneratorU+>
...
<+bean>
43
Summary
Spring offers many techniques to simplify
configuration
+ ,eA(e seen 3ust a fe) here
+ ItAs about e#pressi(eness and elegance< 3ust li1e code
DonAt repeat yourselfB
+ *se bean inheritance if youAre seeing repetiti(e 20$
Consider hiding lo)6le(el beans
+ *se inner beans )here itAs natural to do so
A(oid monolithic configuration
+ *se *import'+ to aid in modulariCing your 20$
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Annotation- and Java-Based
Configuration Styles
2
History
2004: Spring 1.0
!"#-$ased %onfiguration
200&: Spring 2.'
Adds support for annotation-$ased
%onfiguration
200(: Spring ).0
Adds support for Java-$ased
%onfiguration
XML
XML
Annot.
XML
Annot.
Java
3
*opi%s in t+is Session
Annotation-based coniguration
Co,ponent-s%annning and $est pra%ti%es
Standard annotations
Java-$ased %onfiguration
"i-ing %onfiguration styles
.+en to use /+at
4
!"#0Annotation 12
<bean id=transferService class=com.springsource.TransferServicempl!
<constructor"arg ref=account#epositor$ %!
<%bean!
<bean id=transferService class=com.springsource.TransferServicempl!
<constructor"arg ref=account#epositor$ %!
<%bean!
!"#-$ased dependen%y in3e%tion
Annotation-$ased dependen%y in3e%tion
&'omponent
public class TransferServicempl implements TransferService (
&Auto)ired
public TransferServicempl*Account#epositor$ repo+ (
this.account#epositor$ = repo,
-
-
&'omponent
public class TransferServicempl implements TransferService (
&Auto)ired
public TransferServicempl*Account#epositor$ repo+ (
this.account#epositor$ = repo,
-
-
./ternal configuration
Annotations embedded
)it0 12J2s
<conte/t3component"scan base"pac4age=com.springsource%! <conte/t3component"scan base"pac4age=com.springsource%!
Minimal /ml config
5
1efinitions: 4Auto/ired
4Auto/ired
2ndi%ates t+at Spring s+ould in3e%t a dependen%y
Based on its type 5default6
Based on its na,e if used /it+ t+e 47ualifier annotation
@Autowired
public TransferServicempl*Account#epositor$ repo+ (
this.account#epositor$ = repo,
-
@Autowired
public TransferServicempl*Account#epositor$ repo+ (
this.account#epositor$ = repo,
-
@Autowired
public TransferServicempl* @Qualifier*account#epositor$+
Account#epositor$ repo+ (
this.account#epositor$ = repo,
-
@Autowired
public TransferServicempl* @Qualifier*account#epositor$+
Account#epositor$ repo+ (
this.account#epositor$ = repo,
-
6
1efinitions: Co,ponent s%anning
Co,ponent-s%anning
Base-pa%8age s%anned at startup
Su$-pa%8ages of t+e $ase-pa%8age also s%anned
All %lasses annotated /it+ 4Co,ponent loaded as
Spring $eans
So,e ot+er annotations /ill also $e dis%ussed later
<conte/t3component"scan base"pac4age=com.springsource%! <conte/t3component"scan base"pac4age=com.springsource%!
7
9sage of 4Auto/ired
%onstru%tor-in3e%tion
,et+od-in3e%tion
field-in3e%tion
&Auto)ired
public TransferServicempl*Account#epositor$ repo+ (
this.account#epositor$ = repo,
-
&Auto)ired
public TransferServicempl*Account#epositor$ repo+ (
this.account#epositor$ = repo,
-
&Auto)ired
public void setAccount#epositor$*Account#epositor$ repo+ (
t0is.account#epositor$ = repo,
-
&Auto)ired
public void setAccount#epositor$*Account#epositor$ repo+ (
t0is.account#epositor$ = repo,
-
&Auto)ired
private Account#epositor$ account#epositor$,
&Auto)ired
private Account#epositor$ account#epositor$,
'an also contain
multiple params
Met0od name does not
0ave to start )it0 set
8
Auto/iring and disa,$iguation
.+at +appens +ere:
&'omponent
public class TransferServicempl implements TransferService (
&Auto)ired
public TransferServicempl*Account#epositor$ account#epositor$+
( 5 -
-
&'omponent
public class JdbcAccount#epositor$ implements Account#epositor$ (..-
&'omponent
public class 6ibernateAccount#epositor$ implements Account#epositor$ (..-
&'omponent
public class TransferServicempl implements TransferService (
&Auto)ired
public TransferServicempl*Account#epositor$ account#epositor$+
( 5 -
-
&'omponent
public class JdbcAccount#epositor$ implements Account#epositor$ (..-
&'omponent
public class 6ibernateAccount#epositor$ implements Account#epositor$ (..-
70ic0 one s0ould get in8ected9

At startup3 :oSuc0;ean<efinition./ception= no uni>ue bean of t$pe
?Account#epositor$@ is defined3 e/pected single bean but found A...
9
Auto/iring and disa,$iguation
9se of t+e 47ualifier annotation
&'omponent
public class TransferServicempl implements TransferService (
&Auto)ired
public TransferServicempl* &Bualifier*C8dbcAccount#epositor$C+
Account#epositor$ account#epositor$+
( 5 -
-
&'omponent*C8dbcAccount#epositor$C+
public class JdbcAccount#epositor$ implements Account#epositor$ (..-
&'omponent*C0ibernateAccount#epositor$C+
public class 6ibernateAccount#epositor$ implements Account#epositor$ (..-
&'omponent
public class TransferServicempl implements TransferService (
&Auto)ired
public TransferServicempl* &Bualifier*C8dbcAccount#epositor$C+
Account#epositor$ account#epositor$+
( 5 -
-
&'omponent*C8dbcAccount#epositor$C+
public class JdbcAccount#epositor$ implements Account#epositor$ (..-
&'omponent*C0ibernateAccount#epositor$C+
public class 6ibernateAccount#epositor$ implements Account#epositor$ (..-
Bualifier
&Bualifier can also be used )it0 met0od in8ection and field in8ection
!
Co,ponent na,es
.+en not spe%ified
na,es are auto-generated
1e-%apitali;ed non-<ualified na,es $y default
=ever rely on generated na,es>
.+en spe%ified
#ess refa%toring-friendly
'ommon strateg$3 avoid using names )0en possible.
In many cases, it is not needed to have 2 implementations
of the same bean in the ApplicationContext

#ife%y%le
;eanDac11
XML
config
Annotations
config
;ean
detection
;ean instantiation and
dependenc$ in8ection
;ean11
&'omponent
scanning
nstantiation %
&Auto)ired
on constructor
n8ection of
&Auto)ired
met0ods and fields
Load /ml
definitions
nstantiation
% constr. in8ection
1ropert$
in8ection
;eanDac11 E ;eanDactor$1ost1rocessor
;ean11 E ;ean1ost1rocessor
2
!"# vs Annotations synta-
Sa,e options are availa$le
&'omponent*CtransferServiceC+
&Scope*Cprotot$peC+
public class TransferServicempl
implements TransferService (


&1ost'onstruct
public void init*+ ( %%.. -
&1re<estro$
public void destro$*+ ( %%.. -
-
&'omponent*CtransferServiceC+
&Scope*Cprotot$peC+
public class TransferServicempl
implements TransferService (


&1ost'onstruct
public void init*+ ( %%.. -
&1re<estro$
public void destro$*+ ( %%.. -
-
<bean id="transferService"
scope="prototype"
class="TransferServiceImpl"

init"met0od="init"
destro$"met0od="destroy" %!
<bean id="transferService"
scope="prototype"
class="TransferServiceImpl"

init"met0od="init"
destro$"met0od="destroy" %!
xml config annotations
3
Stereotype annotations
Co,ponent s%anning also %+e%8s for annotations
t+at are t+e,selves annotated /it+ 4Co,ponent
So-%alled stereotype annotations
?-a,ple:
&Target*(.lementT$pe.TYP-+
...
&'omponent
public @interface Service (...-
&Target*(.lementT$pe.TYP-+
...
&'omponent
public @interface Service (...-
&Service
public class TransferServicempl
implements TransferService (...-
&Service
public class TransferServicempl
implements TransferService (...-
<conte/t3component"scan
base"pac4age=com.springsource%!
<conte/t3component"scan
base"pac4age=com.springsource%!
scans
!eclaration of the "Service annotation
&Service annotation is part of t0e Spring frame)or4
4
Stereotype annotations
Spring fra,e/or8 stereotype annotations
&Service
&#epositor$ &'ontroller
&'onfiguration
&'omponent
Service classes
!ata access classes #eb classes $Spring %&C'
(ava Config)ration
2t0er Spring pro8ects provide t0eir o)n stereot$pe annotations
*Spring 7S= Spring ntegration...+
5
"eta-annotations
Annotation /+i%+ %an $e used to annotate ot+er
annotations
e.g. all servi%e $eans s+ould $e %onfigura$le using
%o,ponent s%anning and $e transa%tional
&#etention*#etention1olic$.*+,TI%+
&Target*.lementT$pe.TYP+
@"ervice
&Transactional*timeout=FG+
public &interface #$%ransactional"ervice (
String value*+ default CC,
-
&#etention*#etention1olic$.*+,TI%+
&Target*.lementT$pe.TYP+
@"ervice
&Transactional*timeout=FG+
public &interface #$%ransactional"ervice (
String value*+ default CC,
-
@#$%ransactional"ervice
public class TransferServicempl
implements TransferService (...-
@#$%ransactional"ervice
public class TransferServicempl
implements TransferService (...-
<conte/t3component"scan
base"pac4age=com.springsource%!
<conte/t3component"scan
base"pac4age=com.springsource%!
scans
recogni-es
C)stom annotation
6
4@alue and syste,Aroperties
9se 4@alue for Sp?# e-pressions in Java %ode
Bn a field or ,et+od or on para,eter of auto/ired
,et+od or %onstru%tor
&Halue*CI( s$stem1roperties?Juser.regionJ@ -C+
private String defaultLocale,
&Halue*CI( s$stem1roperties?Juser.regionJ@ -C+
public void set<efaultLocale*String defaultLocale+ ( 5 -
&Auto)ired
public void configure*Account#epositor$ account#epositor$=
&Halue*CI( s$stem1roperties?Juser.regionJ@ -C+ String defaultLocale+ (
5
-
&Halue*CI( s$stem1roperties?Juser.regionJ@ -C+
private String defaultLocale,
&Halue*CI( s$stem1roperties?Juser.regionJ@ -C+
public void set<efaultLocale*String defaultLocale+ ( 5 -
&Auto)ired
public void configure*Account#epositor$ account#epositor$=
&Halue*CI( s$stem1roperties?Juser.regionJ@ -C+ String defaultLocale+ (
5
-
Sp.L3 Spring ./pression Language *available since Spring K.G+
7
*opi%s in t+is Session
Annotation-$ased %onfiguration
Component-scanning
Standard annotations
Java-$ased %onfiguration
"i-ing %onfiguration styles
.+en to use /+at
8
Co,ponent s%anning
Co,ponents are s%anned at startup
Jar dependen%ies also s%anned>
Could result in slo/er startup ti,e if too ,any files
s%anned
?spe%ially for large appli%ations
A fe/ se%onds slo/er in t+e /orst %ase
.+at are t+e $est pra%ti%es:
9
Best pra%ti%es
<conte/t3component"scan base"pac4age=org=com%! <conte/t3component"scan base"pac4age=org=com%!
<conte/t3component"scan base"pac4age=com%! <conte/t3component"scan base"pac4age=com%!
<conte/t3component"scan base"pac4age=com.acme.app%! <conte/t3component"scan base"pac4age=com.acme.app%!
<conte/t3component"scan
base"pac4age=com.acme.app.repositor$=
com.acme.app.service= com.acme.app.controller%!
<conte/t3component"scan
base"pac4age=com.acme.app.repositor$=
com.acme.app.service= com.acme.app.controller%!
Ceally $ad:
Bad:
BD:
Bpti,i;ed:
All org and com
pac4ages in t0e classpat0
)ill be scannedLL
2!
2n%luding E ?-%luding Beans
9sing filtersF possi$ility to in%lude or e-%lude
$eans
Based on type
Based on %lass-level annotation
<conte/t3component"scan base"pac4age=Ccom.acme.appC!
<conte/t3include"filter t$pe=Crege/C e/pression=C.MStub.M#epositor$C%!
<conte/t3e/clude"filter t$pe=CannotationC
e/pression=Corg.springframe)or4.stereot$pe.#epositor$C%!
<%conte/t3component"scan!
<conte/t3component"scan base"pac4age=Ccom.acme.appC!
<conte/t3include"filter t$pe=Crege/C e/pression=C.MStub.M#epositor$C%!
<conte/t3e/clude"filter t$pe=CannotationC
e/pression=Corg.springframe)or4.stereot$pe.#epositor$C%!
<%conte/t3component"scan!
;ased on name
2
*opi%s in t+is Session
Annotation-$ased %onfiguration
Co,ponent s%anning
Standard annotations
Java-$ased %onfiguration
"i-ing %onfiguration styles
.+en to use /+at
22
JSC ))0
Java Spe%ifi%ation Ce<uest ))0
Also 8no/n as 42n3e%t
Joint JCA effort $y Google and SpringSour%e
Standardi;es internal 12 annotations
Au$lis+ed late 200(
Spring is a valid JSC-))0 i,ple,entation
Su$set of fun%tionality %o,pared to SpringHs
4Auto/ired support
42n3e%t +as I0J of /+at you need
Cely on 4Auto/ired for t+e rest
23
JSC ))0 annotations
import 8ava/.in8ect.n8ect,
import 8ava/.in8ect.:amed,
@&amed
public class TransferServicempl implements TransferService (
@'n(ect
public TransferServicempl* @&amed*Caccount#epositor$C+
Account#epositor$ account#epositor$+ ( 5 -
-
import 8ava/.in8ect.n8ect,
import 8ava/.in8ect.:amed,
@&amed
public class TransferServicempl implements TransferService (
@'n(ect
public TransferServicempl* @&amed*Caccount#epositor$C+
Account#epositor$ account#epositor$+ ( 5 -
-
import 8ava/.in8ect.:amed,
@&amed*Caccount#epositor$C+
public class JdbcAccount#epositor$ implements Account#epositor$ (..-
import 8ava/.in8ect.:amed,
@&amed*Caccount#epositor$C+
public class JdbcAccount#epositor$ implements Account#epositor$ (..-
<conte/t3component"scan base"pac4age=com.springsource%! <conte/t3component"scan base"pac4age=com.springsource%!
Also scans JS#"KKG annotations
S0ould be specified for component
scanning *even )it0out a name+
24
Kro, 4Auto/ired to 42n3e%t
Spring 3ava-.in3e%t.L
8ava/.in8ect restrictions
4Auto/ired 42n3e%t
&n8ect 0as no Jre>uiredJ attribute
4Co,ponent 4=a,ed
Spring supports scanning for
&:amed
4S%ope 4S%ope
for meta"annotation and in8ection
points onl$
&Scope
*CsingletonC+
4Singleton
8sr"KKG default scope is li4e SpringJs
Jprotot$peJ
47ualifier 4=a,ed
4@alue
no equivalent
4Ce<uired
no equivalent
4#a;y
no equivalent
25
*opi%s in t+is Session
Annotation-$ased %onfiguration
Co,ponent-s%anning
Standard annotations
!a"a-based coniguration
"i-ing %onfiguration styles
.+en to use /+at
26
*+e Java-$ased Approa%+
Spring ).0 introdu%es Java-$ased %onfiguration
9sed to $e a separate pro3e%t %alled Spring JavaConfig
4Configuration-annotated %lasses are t+e 8ey artifa%t
4Bean ,et+ods instead of M$ean0N ele,ents
9se Java %ode to define and %onfigure $eans
Configuration still e-ternal to ABJB %lasses to $e
%onfigured
"ore %ontrol over $ean instantiation and %onfiguration
"ore type-safety
27
4Configuration ?-a,ple
@)onfi*uration
public class #e)ards'onfig (

@+ean
public TransferService transferService*+ (
TransferServicempl service = ne) TransferServicempl*+,
service.setAccount#epositor$*account#epositor$*++,
return service,
-

@+ean
public Account#epositor$ account#epositor$*+ (
%%...
-
-
@)onfi*uration
public class #e)ards'onfig (

@+ean
public TransferService transferService*+ (
TransferServicempl service = ne) TransferServicempl*+,
service.setAccount#epositor$*account#epositor$*++,
return service,
-

@+ean
public Account#epositor$ account#epositor$*+ (
%%...
-
-
bean id
T0is met0od produces a bean definition
<ependenc$ in8ection
28
?na$ling 4Configuration %lass
pro%essing
2 /ays:
9se %o,ponent s%anning
9se AnnotationConfigAppli%ationConte-t
no !"# re<uired at all
<conte/t3component"scan base"pac4age=com.springsource%! <conte/t3component"scan base"pac4age=com.springsource%!
scans &'onfiguration
annotated classes
Application'onte/t conte/t =
ne) 'lass1at0XmlApplication'onte/t*application"config./ml+,
Application'onte/t conte/t =
new AnnotationConfigApplicationContext(AppConfig.class);
29
2,ple,enting 4Bean "et+ods
Configuration in Java: %all any %ode you /ant
=ot 3ust %onstru%tors and property setters
"ay not $e private
"et+od na,e $e%o,es $ean id
Call &;ean ,et+od to refer to $ean in sa,e %lass
.eHll s+o/ +o/ to refer to e-ternal $eans later
Sa,e defaults as !"#: $eans are singletons
9se &Scope annotation to %+ange s%ope
&;ean @"cope,-protot$pe-.
public StatefulService service*+ (
5
&;ean @"cope,-protot$pe-.
public StatefulService service*+ (
5
3!
2,ple,enting 4Configuration
Classes
"ust +ave default %onstru%tor
2,pli%it or not
"ultiple &'onfiguration %lasses ,ay e-ist
@)onfi*uration
public class #e)ards'onfig (
%%..
-
@)onfi*uration
public class #e)ards'onfig (
%%..
-
@)onfi*uration
public class Securit$'onfig ( %%.. -
@)onfi*uration
public class Securit$'onfig ( %%.. -
3
4Configuration internals 516
By defaultF Spring %reates singletons out of
4Bean annotated ,et+ods
Ho/ is it possi$le:
@+ean
public TransferService transferService*+ (
TransferServicempl service = ne) TransferServicempl*+,
service.setAccount#epositor$*account#epositor$*++,
return service,
-
@+ean
public Account#epositor$ account#epositor$*+ (
Account#epositor$mpl repo = ne) Account#epositor$mpl*+,
%%...
return repo,
-
@+ean
public TransferService transferService*+ (
TransferServicempl service = ne) TransferServicempl*+,
service.setAccount#epositor$*account#epositor$*++,
return service,
-
@+ean
public Account#epositor$ account#epositor$*+ (
Account#epositor$mpl repo = ne) Account#epositor$mpl*+,
%%...
return repo,
-
T0is is a singletonLL
32
4Configuration internals 526
public class Proxy,ame e/tends #e)ard'onfig (
public TransferService transferService*+ (
%% c0ec4 if bean is in t0e application'onte/t
%% if not= call super.transferService*+ and store bean in application 'onte/t
-
-
public class Proxy,ame e/tends #e)ard'onfig (
public TransferService transferService*+ (
%% c0ec4 if bean is in t0e application'onte/t
%% if not= call super.transferService*+ and store bean in application 'onte/t
-
-
@)onfi*uration
public class #e)ard'onfig (
@+ean
public TransferService transferService*+ ( %%... -
-
@)onfi*uration
public class #e)ard'onfig (
@+ean
public TransferService transferService*+ ( %%... -
-
Aro-y %reated at startup ti,e
1oes all t+e ,agi%
Stores $eans in Appli%ationConte-tF %reates singletons...
1ro/$ generation uses
'NLib b$ default
33
#ife%y%le
;eanDac11
XML
config
Annotation
config
;ean
detection
;ean instantiation and
dependenc$ in8ection
;ean11
&'omponent
scanning
nstantiation %
&Auto)ired
on constructor
n8ection of
&Auto)ired
met0ods and fields
Load /ml
definitions
nstantiation
% constr. in8ection
1ropert$
in8ection
Java
config
#ead &;ean
met0od
signatures
'all &;ean met0od implementations
;eanDac11 E ;eanDactor$1ost1rocessor
;ean11 E ;ean1ost1rocessor
34
*opi%s in t+is Session
Annotation-$ased %onfiguration
Co,ponent-s%anning and $est pra%ti%es
Standard annotations
Java-$ased %onfiguration
#ixing coniguration styles
.+en to use /+at
35
"i-ing %onfiguration styles:
.+y:
Bne single appli%ation %an ,i- and ,at%+
in3e%tion styles
!"#-$ased
=o ,a3or te%+ni%al li,itation $ut ,ore ver$ose
Annotation-$ased
Can only annotate t+e %lasses you /rite
Java-$ased
does not +ave na,espa%es 5%onte-tF t-F se%urity...6
36
9sing annotations /it+out
%o,ponent s%anning 516
9se of M%onte-t:annotation-%onfig0N
Aro%esses all 12 annotations
1oes not perfor, %o,ponent-s%anning
Beans s+ould $e de%lared e-pli%itely
<beans ...!
/conte0t1annotation2confi*34
<bean id=transferService class=transfer.TransferService%!
<bean id=account#epositor$ class=transfer.JdbcAccount#epositor$%!
<%beans!
<beans ...!
/conte0t1annotation2confi*34
<bean id=transferService class=transfer.TransferService%!
<bean id=account#epositor$ class=transfer.JdbcAccount#epositor$%!
<%beans!
<propert$ %! or <constructor"arg%! are not needed an$ more
because classes use &Auto)ired
37
9sing annotations /it+out
%o,ponent s%anning 526
=o 4Co,ponent annotation any,ore
.it+out 7ualifier
.it+ 7ualifier
public class TransferServicempl implements TransferService (
@Autowired
public TransferServicempl*Account#epositor$ account#epositor$+ ( 5 -
-
public class TransferServicempl implements TransferService (
@Autowired
public TransferServicempl*Account#epositor$ account#epositor$+ ( 5 -
-
public class JdbcAccount#epositor$ implements Account#epositor$ (
public JdbcAccount#epositor$*@Qualifier*Cm$s>l<atasourceC+
Account#epositor$ account#epositor$+ ( 5 -
-
public class JdbcAccount#epositor$ implements Account#epositor$ (
public JdbcAccount#epositor$*@Qualifier*Cm$s>l<atasourceC+
Account#epositor$ account#epositor$+ ( 5 -
-
public class JdbcAccount#epositor$ implements Account#epositor$ (...- public class JdbcAccount#epositor$ implements Account#epositor$ (...-
public class JdbcAccount#epositor$ implements Account#epositor$ (...- public class JdbcAccount#epositor$ implements Account#epositor$ (...-
#efers to
declared bean id
38
9sing annotations /it+out
%o,ponent s%anning 5)6
Java-$ased %onfiguration: use of 42,port
?<uivalent to Mi,port0N in !"#
"eans in%luded %lasses donHt +ave to $e defined as
Spring $eans any ,ore
&'onfiguration
@'mport,5"ecurit$)onfi*6class7 8m0)onfi*6class9.
public class #e)ards'onfig (
5
-
&'onfiguration
@'mport,5"ecurit$)onfi*6class7 8m0)onfi*6class9.
public class #e)ards'onfig (
5
-
&'onfiguration
public class Securit$'onfig (
5
-
&'onfiguration
public class Securit$'onfig (
5
-
39
"i-ing %onfiguration styles:
4Configuration e-a,ple
Bean datasour%e de%lared in !"#
9sed in 4Configuration %lass
@)onfi*uration
public class Application'onfig (
@Autowired
private <ataSource datasource,
@+ean
public Account#epositor$ account#epositor$*+ (
Account#epositor$mpl repositor$ = new Account#epositor$mpl*+,
repositor$.set<ataSource*t0is.datasource+,
return service,
-
-
@)onfi*uration
public class Application'onfig (
@Autowired
private <ataSource datasource,
@+ean
public Account#epositor$ account#epositor$*+ (
Account#epositor$mpl repositor$ = new Account#epositor$mpl*+,
repositor$.set<ataSource*t0is.datasource+,
return service,
-
-
<conte/t3component"scan base"pac4age=com.springsource%!
<bean id=dataSource class=...%!
<conte/t3component"scan base"pac4age=com.springsource%!
<bean id=dataSource class=...%!
<ependenc$ n8ection
<eclaration
4!
*opi%s in t+is Session
Annotation-$ased %onfiguration
Co,ponent s%anning
Standard annotations
Java-$ased %onfiguration
"i-ing %onfiguration styles
$hen to use what
4
.+en to use /+at:
Annotations:
=i%e for fre<uently %+anging $eans
Start using for s,all isolated parts of your appli%ation
5e.g. Spring 4"@C %ontrollers6
Aros:
Single pla%e to edit 53ust t+e %lass6
Allo/s for very rapid develop,ent
Cons:
Configuration spread a%ross your %ode $ase
Bnly /or8s for your o/n %ode
42
.+en to use /+at:
!"#:
Kor infrastru%ture and ,ore Hstati%H $eans
Aros:
2s %entrali;ed in one 5or a fe/6 pla%es
"ost fa,iliar %onfiguration for,at for ,ost people
Can $e used for all %lasses 5not 3ust your o/n6
Cons:
#i,ited %onfiguration options
So,e people 3ust donHt li8e !"#>
43
.+en to use /+at:
4Configuration %lasses:
Kor full %ontrol over instantiation and
%onfiguration
As alternative to i,ple,enting Ka%toryBean
Aros:
Configuration still e-ternal to %ode
2ntegrates /ell /it+ lega%y %ode
Can %all ,et+ods su%+ as addDataSource(DataSource d)
Cons:
.iring /onHt s+o/ up in S*S
=o e<uivalent to t+e !"# na,espa%es
44
Su,,ary
SpringOs %onfiguration dire%tives %an $e /ritten
in !"#F using Java or using annotations
Pou %an ,i- and ,at%+ !"#F Java and
annotations as you please
Auto/iring /it+ 4Co,ponent or 4Configuration
allo/s for al,ost e,pty !"# %onfiguration files
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
#AB
9sing SpringOs annotations to Configure and
test an appli%ation
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Testing Spring Applications
Unit Testing without Spring,
and Integration Testing with Spring
2
Topics in this session
Test Drien Deelopment
Unit Testing vs. Integration Testing
Unit Testing with Stubs
Unit Testing with Mocks
Integration Testing with Spring
3
What is TDD
TDD Test Driven Develop!ent
Is it writing tests be"ore the code# Is it writing
tests at the sa!e ti!e as the code#
$ That is not what is !ost i!portant
TDD is about%
$ writing auto!ated tests that veri"& code actuall&
works
$ Driving develop!ent with well de"ined re'uire!ents
in the "or! o" tests
4
()ut I Don*t +ave Ti!e to
Write Tests,-
.ver& develop!ent process includes testing
$ .ither auto!ated or !anual
Auto!ated tests result in a "aster develop!ent
c&cle overall
$ /our ID. is better at this than &ou are
0roperl& done TDD is faster than develop!ent
without tests
5
TDD and Agilit&
1o!prehensive test coverage provides
con"idence
1on"idence enables re"actoring
2e"actoring is essential to agile develop!ent
6
TDD and Design
Testing !akes &ou think about &our design
I" &our code is hard to test then the design
should be reconsidered
7
TDD and 3ocus
A test case helps &ou "ocus on what !atters
It helps &ou not to write code that &ou don4t
need
3ind proble!s earl&
8
)ene"its o" 1ontinuous Integration
The cost to "i5 a bug grows e5ponentiall& in proportion
to the ti!e be"ore it is discovered
1ontinuous Integration 61I7 "ocuses on reducing the
ti!e be"ore the bug is discovered
.""ective 1I re'uires auto!ated tests
time
to fix
time until discovered
9
Test Driven Develop!ent
!nit Testing s. "ntegr#tion Testing
Unit Testing with Stubs
Unit Testing with Mocks
Integration Testing with Spring
Topics in this session
10
Unit Testing vs.
Integration Testing
Unit Testing
$ Tests one unit o" "unctionalit&
$ 8eeps dependencies !ini!al
$ Isolated "ro! the environ!ent 6including Spring7
Integration Testing
$ Tests the interaction o" !ultiple units working
together
$ Integrates in"rastructure
11
Unit Testing
9eri"& a unit works in isolation
$ I" A depends on ), A*s tests should not "ail because
o" a bug in )
$ A*s test should not pass because o" a bug in )
Stub or !ock out dependencies i" needed
+ave each test e5ercise a single scenario
$ A path through the unit
12
.5a!ple Unit to be Tested
public class AuthenticatorImpl implements Authenticator {
private AccountDao accountDao;

public AuthenticatorImpl(AccountDao accountDao) {
this.accountDao = accountDao;
}
public boolean authenticate(String username, String passwor) {
Account account = accountDao.getAccount(username);
i! (account.get"asswor().e#uals(passwor)) {
return true;
} else {
return !alse;
}
}
}
public class AuthenticatorImpl implements Authenticator {
private AccountDao accountDao;

public AuthenticatorImpl(AccountDao accountDao) {
this.accountDao = accountDao;
}
public boolean authenticate(String username, String passwor) {
Account account = accountDao.getAccount(username);
i! (account.get"asswor().e#uals(passwor)) {
return true;
} else {
return !alse;
}
}
}
$%ternal epenenc&
'nit business logic (( paths)
13
Test Driven Develop!ent
Unit Testing vs. Integration Testing
!nit Testing with Stubs
Unit Testing with Mocks
Integration Testing with Spring
Topics in this session
14
I!ple!enting a Stub
class StubAccountDao implements AccountDao {
public Account getAccount(String user) {
return )lisa*.e#uals(user) + new Account()lisa*, )secret*) , null;
}
}
class StubAccountDao implements AccountDao {
public Account getAccount(String user) {
return )lisa*.e#uals(user) + new Account()lisa*, )secret*) , null;
}
}
Simple state
15
Testing with a Stub
public class AuthenticatorImpl-ests {
private AuthenticatorImpl authenticator;
./e!ore public voi set'p() {
authenticator = new AuthenticatorImpl(new StubAccountDao());
}
.-est public voi success!ulAuthentication() {
assert-rue(authenticator.authenticate()lisa*, )secret*));
}
.-est public voi invali"asswor() {
assert0alse(authenticator.authenticate()lisa*, )invali*));
}
}
public class AuthenticatorImpl-ests {
private AuthenticatorImpl authenticator;
./e!ore public voi set'p() {
authenticator = new AuthenticatorImpl(new StubAccountDao());
}
.-est public voi success!ulAuthentication() {
assert-rue(authenticator.authenticate()lisa*, )secret*));
}
.-est public voi invali"asswor() {
assert0alse(authenticator.authenticate()lisa*, )invali*));
}
}
Stub is con!igure
Scenarios are e%ercise
base on the state o! stub
16
Stub 1onsiderations
Advantages
.as& to i!ple!ent and understand
2eusable
Disadvantages
A change to the inter"ace re'uires the stub to be
updated
/our stub !ust i!ple!ent all !ethods, even those
not used b& a speci"ic scenario
I" a stub is reused re"actoring can break other tests
17
Test Driven Develop!ent
Unit Testing vs. Integration Testing
Unit Testing with Stubs
!nit Testing with $oc%s
Integration Testing with Spring
Topics in this session
18
Steps to Testing with a Mock
:. Use a !ocking librar& to generate a !ock
ob;ect
I!ple!ents the dependent inter"ace on<the<"l&
=. 2ecord the !ock with e5pectations o" how it
will be used "or a scenario
What !ethods will be called
What values to return
>. .5ercise the scenario
?. 9eri"& !ock e5pectations were !et
19
Mock @ibraries
.as&Mock
$ ver& popular
$ used e5tensivel& in Spring
A!ock
$ nice A0I, ver& suitable "or co!ple5 state"ul logic
Mockito
$ uses a Test Sp& instead o" a true !ock, !aking it
easier to use !ost o" the ti!e
20
.5a!ple < Testing with .as&Mock
Bn setup
1 1reate
!ock6s7
1 1reate unit
3or each test
1 2ecord
e5pected
!ethod calls
and set !ock
return values
1 1all repla&
1 .5ercise test
scenario
1 1all veri"&
import static org.eas&moc2.classe%tensions.$as&3oc2.4;
public class AuthenticatorImpl-ests {
private AccountDao accountDao
= createMock(AccountDao.class);
private AuthenticatorImpl authenticator
= new AuthenticatorImpl(accountDao);
.-est
public voi vali'ser5ith6orrect"asswor() {
expect(accountDao.getAccount()lisa*)).
an7eturn(new Account()lisa*, )secret*));
replay(accountDao);
assert-rue(authenticator.authenticate()lisa*, )secret*));
verify(accountDao);
}
}
import static org.eas&moc2.classe%tensions.$as&3oc2.4;
public class AuthenticatorImpl-ests {
private AccountDao accountDao
= createMock(AccountDao.class);
private AuthenticatorImpl authenticator
= new AuthenticatorImpl(accountDao);
.-est
public voi vali'ser5ith6orrect"asswor() {
expect(accountDao.getAccount()lisa*)).
an7eturn(new Account()lisa*, )secret*));
replay(accountDao);
assert-rue(authenticator.authenticate()lisa*, )secret*));
verify(accountDao);
}
}
21
Mock 1onsiderations
Advantages
Co additional class to !aintain
/ou onl& need to setup what is necessar& "or
the scenario &ou are testing
Test behavior as well as state
Disadvantages
A little harder to understand at "irst
22
Mocks or Stubs#
/ou will probabl& use both
Deneral reco!!endations
$ 3avor !ocks "or non<trivial inter"aces
$ Use stubs when &ou have si!ple inter"aces with
repeated "unctionalit&
$ Alwa&s consider the speci"ic situation
2ead (Mocks Aren*t Stubs- b& Martin 3owler
$ http%EEwww.!artin"owler.co!EarticlesE!ocksArentStubs.ht!l
23
Test Driven Develop!ent
Unit Testing vs. Integration Testing
Unit Testing with Stubs
Unit Testing with Mocks
"ntegr#tion Testing with Spring
Topics in this session
24
Integration Testing
Tests the interaction o" !ultiple units
Tests application classes in the conte5t o" their
surrounding in"rastructure
In"rastructure !a& be (scaled down-
e.g. use Apache D)10 connection pool instead o"
container<provider pool obtained through ACDI
25
0ackaged as a separate !odule
$ spring<test.;ar
1onsists o" several AUnit test support classes
1entral support class is SpringAUnit?Test2unner
$ 1aches a shared Application1onte5t across test !ethods
Spring*s Integration Test
Support
26
Annotations "or Integration
Testing
Annotate the test with F1onte5t1on"iguration
Bptionall& pass a String<arra& o" con"ig "ile
locations
$ b& de"ault Spring loads GHclassna!eI<conte5t.5!l
"ro! the sa!e package
Use FAutowired annotations as be"ore
@ContextConfiguration(89trans!er:con!ig.%ml8)
@RunWith(Spring;'nit<6lass7unner.class)
public class Authenticator-ests {
@uto!ire"
pri$ate Authenticator authenticator;
}
@ContextConfiguration(89trans!er:con!ig.%ml8)
@RunWith(Spring;'nit<6lass7unner.class)
public class Authenticator-ests {
@uto!ire"
pri$ate Authenticator authenticator;
}
27
Using Spring4s test support
.7un5ith(Spring;'nit<6lass7unner.class)
.6onte%t6on!iguration()classpath,s&stem:test:con!ig.%ml*})
public !inal class Authenticator-ests {
.Autowire
private Authenticator authenticator;
.-est
public voi success!ulAuthentication() {
authenticator.authenticate(...);
...
}
}
.7un5ith(Spring;'nit<6lass7unner.class)
.6onte%t6on!iguration()classpath,s&stem:test:con!ig.%ml*})
public !inal class Authenticator-ests {
.Autowire
private Authenticator authenticator;
.-est
public voi success!ulAuthentication() {
authenticator.authenticate(...);
...
}
}
7un with Spring support
"oint to s&stem test
con!iguration !ile
De!ine a epenenc&
-est the s&stem as normal
28
Multiple test !ethods
.7un5ith(Spring;'nit<6lass7unner.class)
.6onte%t6on!iguration()classpath,s&stem:test:con!ig.%ml*)
public !inal class Authenticator-ests {
.Autowire
private Authenticator authenticator;
.-est
public voi success!ulAuthentication() {
...
}
.-est
public voi !ailureAuthentication() {
...
}
}
.7un5ith(Spring;'nit<6lass7unner.class)
.6onte%t6on!iguration()classpath,s&stem:test:con!ig.%ml*)
public !inal class Authenticator-ests {
.Autowire
private Authenticator authenticator;
.-est
public voi success!ulAuthentication() {
...
}
.-est
public voi !ailureAuthentication() {
...
}
}
-he Application6onte%t is
instantiate onl& once !or
all tests that use the same
set o! con!ig !iles
(even across test classes)
Annotate test metho with .Dirties6onte%t to !orce recreation o! the
cache Application6onte%t i! metho changes the containe beans
29
)ene"its o" Integration
Testing with Spring
Co need to deplo& to an e5ternal container to
test application "unctionalit&
2un ever&thing 'uickl& inside &our ID.
Allows reuse o" &our con"iguration between test
and production environ!ents
Application con"iguration logic is t&picall& reused
In"rastructure con"iguration is environ!ent<speci"ic
DataSources
AMS Jueues
30
Su!!ar&
Testing is an essential part o" any develop!ent
Unit testing tests a class in isolation where
e5ternal dependencies should be !ini!iKed
1onsider creating stubs or !ocks to unit test
/ou don*t need Spring to unit test
Integration testing tests the interaction o"
!ultiple units working together
Spring provides good integration testing support
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
@A)
Testing Spring Applications
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Developing Aspects with
Spring AOP
Aspect-Oriented Programming for
Declarative Enterprise Services
2
Topics in this session
What roblem !oes "# Sol$e%
Core AOP Concepts
Quic Start
Defining Pointcuts
!mplementing Advice
Advanced topics
" #amed Pointcuts
" Conte$t selecting pointcuts
" %oring with annotations
3
%hat Pro&lem Does AOP
Solve'
Aspect-Oriented Programming (AOP) ena&les
modulari*ation of cross-cutting concerns
4
%hat are Cross-Cutting
Concerns'
+eneric functionalit, that is needed in man,
places in ,our application
E$amples
" -ogging and Tracing
" Transaction .anagement
" Securit,
" Caching
" Error /andling
" Performance .onitoring
" Custom 0usiness 1ules
5
An E$ample 1e2uirement
Perform a role-&ased securit, chec
&efore ever, application method
A sign this requirement is a cross-cutting concern
6
!mplementing Cross Cutting
Concerns %ithout .odulari*ation
3ailing to modulari*e cross-cutting concerns
leads to two things
45 Code tangling
A coupling of concerns
65 Code scattering
The same concern spread across modules
7
S,mptom 748 Tangling
public class RewardNetworkImpl implements RewardNetwork {
public RewardConfirmation rewardAccountFor(Dining dining) {
if (!as!ermission("ecurit#Conte$t%get!rincipal()) {
trow new AccessDenied&$ception()'
(
Account a ) accountRepositor#%find*#CreditCard(+
Restaurant r ) restaurantRepositor#%find*#,ercantNumber(+
,onetar#Amount amt ) r%calculate*enefitFor(account- dining)'
+
(
(
,i$ing of concerns
8
S,mptom 768 Scattering
public class .ibernateAccount,anager implements Account,anager {
public Account getAccountFor&diting(/ong id) {
if (!as!ermission("ecurit#Conte$t%get!rincipal()) {
trow new AccessDenied&$ception()'
(
+
public class .ibernate,ercantReporting"er0ice implements
,ercantReporting"er0ice {
public /ist1Dining"ummar#2 findDinings("tring mercantNumber-
DateInter0al inter0al) {
if (!as!ermission("ecurit#Conte$t%get!rincipal()) {
trow new AccessDenied&$ception()'
(
+
Duplication
9
&an'Ser$ice
S,stem Evolution %ithout
.odulari*ation
Code
tangling
Transactions
Securit,
-ogging
CustomerSer$ice (eportingSer$ice
Code
scattering
10
Aspect Oriented
Programming (AOP)
Aspect-Oriented Programming (AOP)
ena&les modulari*ation of cross-cutting
concerns
" To avoid tangling
" To eliminate scattering
11
/ow AOP %ors
45 !mplement ,our mainline application logic
3 3ocusing on the core pro&lem
65 %rite aspects to implement ,our cross-cutting
concerns
3 Spring provides man, aspects out-of-the-&o$
95 %eave the aspects into ,our application
3 Adding the cross-cutting &ehaviours to the right
places
12
S,stem Evolution8 AOP &ased
Transaction
Aspect
Security
Aspect
Logging
Aspect
&an'Ser$ice CustomerSer$ice (eportingSer$ice
13
-eading AOP Technologies
Aspect:
" Original AOP technolog, (first version in 4;;<)
" Offers a full-&lown Aspect Oriented Programming
language
=ses &,te code modification for aspect weaving
Spring AOP
" :ava-&ased AOP framewor with Aspect: integration
=ses d,namic pro$ies for aspect weaving
" 3ocuses on using AOP to solve enterprise pro&lems
" )he *ocus o* this session
14
Topics in this session
%hat Pro&lem Does AOP Solve'
Core "# Concepts
Quic Start
Defining Pointcuts
!mplementing Advice
Advanced topics
" #amed Pointcuts
" Conte$t selecting pointcuts
" %oring with annotations
15
Core AOP Concepts
:oin Point
" A point in the e$ecution of a program such as a
method call or field assignment
Pointcut
" An e$pression that selects one or more :oin Points
Advice
" Code to &e e$ecuted at a :oin Point that has &een
selected &, a Pointcut
Aspect
" A module that encapsulates pointcuts and advice
16
Topics in this session
%hat Pro&lem Does AOP Solve'
Core AOP Concepts
+uic' Start
Defining Pointcuts
!mplementing Advice
Advanced topics
" #amed Pointcuts
" Conte$t selecting pointcuts
" %oring with annotations
17
AOP Quic Start
Consider this &asic re2uirement
/ow can ,ou use AOP to meet it'
/og a message e0er# time a propert# is about to cange /og a message e0er# time a propert# is about to cange
18
An Application O&>ect %hose
Properties Could Change
public class "impleCace implements Cace- *eanNameAware {
pri0ate int cace"i4e'
pri0ate Data"ource data"ource'
pri0ate "tring name'
public 0oid setCace"i4e(int si4e) { cace"i4e ) si4e' (
public 0oid setData"ource(Data"ource ds) { data"ource ) ds' (
public 0oid set*eanName("tring beanName) { name ) beanName' (
public "tring to"tring() { return name' (
+
(
public class "impleCace implements Cace- *eanNameAware {
pri0ate int cace"i4e'
pri0ate Data"ource data"ource'
pri0ate "tring name'
public 0oid setCace"i4e(int si4e) { cace"i4e ) si4e' (
public 0oid setData"ource(Data"ource ds) { data"ource ) ds' (
public 0oid set*eanName("tring beanName) { name ) beanName' (
public "tring to"tring() { return name' (
+
(
19
!mplement the Aspect
5Aspect
public class !ropert#Cange6racker {
pri0ate /ogger logger ) /ogger%get/ogger(getClass())'
5*efore(7e$ecution(0oid set8(8))9)
public 0oid trackCange() {
logger%info(7!ropert# about to cange+9)'
(
(
20
Configure the Aspect as a
0ean
1beans2

1aop:aspect;<autopro$#2
1aop:include name)7propert#Cange6racker9 =2
1=aop:aspect;<autopro$#2
1bean id)7propert#Cange6racker9 class)7e$ample%!ropert#Cange6racker9 =2
1=beans2
Configures "pring to appl# te
5Aspect to #our beans
aspects<config%$ml
21
!nclude the Aspect
Configuration
1beans2
1import resource) 7aspects<config%$ml9=2
1bean name)7cace<A9 class)7e$ample%"impleCace9 %%=2
1bean name)7cace<*9 class)7e$ample%"impleCace9 %%=2
1bean name)7cace<C9 class)7e$ample%"impleCace9 %%=2
1=beans2
application<config%$ml
22
Test the Application
ApplicationConte$t conte$t )
new Class!at>mlApplicationConte$t(7application<config%$ml9)'
Cace cace ) (Cace) conte$t%get*ean(7cace<A9)'
cace%setCace"i4e(?@AA)'
INFB: !ropert# about to cange+ INFB: !ropert# about to cange+
23
"pring AB! !ro$# (tis)
/ow Aspects are Applied
"impleCace
(target)
!ropert#Cange
6racker (aspect)
11interface22
Cace
setCace"i4e(?@AA)
C% "pring creates a pro$# tat brings
te aspect and target togeter
?% 6e pro$# implements
te business interface
of te target
D% ,atcing ad0ice is e$ecuted
E% All calls routed troug pro$#
24
Tracing Propert, Changes "
%ith Conte$t
Conte$t is provided &, the JoinPoint method
parameter
5Aspect
public class !ropert#Cange6racker {
pri0ate /ogger logger ) /ogger%get/ogger(getClass())'

5*efore(7e$ecution(0oid set8(8))9)
public 0oid trackCange(Foin!oint point) {
"tring name ) point%get"ignature()%getName()'
Bb;ect newGalue ) point%getArgs()HAI'
logger%info(name J 7 about to cange to 9 J newGalue J
7 on 9 J point%get6arget())'

(
(
Conte$t about te intercepted point
INFB: setCace"i4e about to cange to ?@AA on cace<A INFB: setCace"i4e about to cange to ?@AA on cace<A
25
Topics in this session
%hat Pro&lem Does AOP Solve'
Core AOP Concepts
Quic Start
!e*ining ointcuts
!mplementing Advice
Advanced topics
" #amed Pointcuts
" Conte$t selecting pointcuts
" %oring with annotations
26
Defining Pointcuts
%ith Spring AOP ,ou write pointcuts using
Aspect:?s pointcut e$pression language
" 3or selecting where to appl, advice
Complete e$pression language reference
availa&le at
" http8@@www5eclipse5org@aspect>
27
Common Pointcut Designator
e$ecution(Amethod patternB)
" The method must match the pattern
Can chain together to create composite
pointcuts
" CC (and)D EE (or)D F (not)
.ethod Pattern
" G.odifiersH 1eturnT,pe GClassT,peH
.ethod#ame (GArgumentsH) Gthrows
E$ceptionT,peH
28
%riting e$pressions
e$ecution(8 rewards%restaurant%8"er0ice%find8(%%))
return t#pe
package
t#pe params
metod designator
29
E$ecution E$pression
E$amples
e$ecution(0oid send8("tring))
" An, method starting with send that taes a single String
parameter and has a void return t,pe
e$ecution(8 send(8))
" An, method named send that taes a single parameter
e$ecution(8 send(int- %%))
" An, method named send whose first parameter is an int (the
I55J signifies K or more parameters ma, follow)
30
E$ecution E$pression
E$amples
e$ecution(0oid e$ample%,essage"er0iceImpl%8(%%))
" An, visi&le void method in the .essageService!mpl class
e$ecution(0oid e$ample%,essage"er0iceJ%send(8))
" An, void method named send in an, o&>ect of t,pe
MessageService (that include possi&le child classes or
implementors of .essageService)
e$ecution(5;a0a$%annotation%securit#%RolesAllowed 0oid send8(%%))
" An, void method starting with send that is annotated with
the L1olesAllowed annotation
31
E$ecution E$pression E$amples
woring with pacages
e$ecution(8 rewards%8%restaurant%8%8(%%))
" There is one director, &etween rewards and restaurant
e$ecution(8 rewards%%restaurant%8%8(%%))
" There ma, &e several directories &etween rewards and
restaurant
e$ecution(8 8%%restaurant%8%8(%%))
" An, su&-pacage called restaurant
32
Topics in this session
%hat Pro&lem Does AOP Solve'
Core AOP Concepts
Quic Start
Defining Pointcuts
,mplementing "d$ice
Advanced topics
" #amed Pointcuts
" Conte$t selecting pointcuts
" %oring with annotations
33
Advice T,pes8 0efore
*eforeAd0ice !ro$# 6arget
34
0efore Advice E$ample
=se @Before annotation
" !f the advice throws an e$ceptionD target will not &e
called
5Aspect
public class !ropert#Cange6racker {
pri0ate /ogger logger ) /ogger%get/ogger(getClass())'
5*efore(7e$ecution(0oid set8(8))9)
public 0oid trackCange() {
logger%info(7!ropert# about to cange+9)'
(
(
6rack calls to all setter metods
35
Advice T,pes8After 1eturning
AfterReturningAd0ice !ro$# 6arget
"uccessful return
36
After 1eturning Advice -
E$ample
5AfterReturning(0alue)7e$ecution(8 ser0ice%%8%8(%%))9-
returning)7reward9)
public 0oid audit(Foin!oint ;p- Reward reward) {
audit(;p%get"ignature() J 7 returns a reward ob;ect 9)'
(
Audit all operations in te service package tat return a Reward
ob;ect
=se @AfterReturning annotation with the
returning attri&ute
37
Advice T,pes8 After Throwing
After6rowingAd0ice !ro$# 6arget
Exception
38
After Throwing Advice -
E$ample
5After6rowing(0alue)7e$ecution(8 8%%Repositor#J%8(%%))9- trowing)7e9)
public 0oid report(Foin!oint ;p- DataAccess&$ception e) {
mail"er0ice%emailFailure(7&$ception in repositor#9- ;p- e)'
(
"end an email e0er# time a Repositor# class trows an e$ception of
t#pe DataAccess&$ception
=se @AfterThrowing annotation with the
throwing attri&ute
39
After Throwing Advice -
Propagation
5After6rowing(0alue)7e$ecution(8 8%%Repositor#J%8(%%))9- trowing)7e9)
public 0oid report(Foin!oint ;p- DataAccess&$ception e) {
mail"er0ice%emailFailure(7&$ception in repositor#9- ;p- e)'
trow new Rewards&$ception(e)'
(
The LAfterThrowing advice will not stop the
e$ception from propagating
" .owe0er it can trow a different t#pe of e$ception
If #ou wis to stop te e$ception from propagating an# furter- #ou can
use an 5Around ad0ice (see later)
If #ou wis to stop te e$ception from propagating an# furter- #ou can
use an 5Around ad0ice (see later)
40
Advice T,pes8 After
AfterAd0ice !ro$# 6arget
"uccessful return or &$ception
41
After Advice E$ample
=se @After annotation
" Called regardless of whether an e$ception has &een
thrown &, the target or not
5Aspect
public class !ropert#Cange6racker {
pri0ate /ogger logger ) /ogger%get/ogger(getClass())'
5After(7e$ecution(0oid update8(8))9)
public 0oid trackCange() {
logger%info(7An update as been made+9)'
(
(
6rack calls to all update metods
42
Advice T,pes8 Around
AroundAd0ice !ro$# 6arget
proceed()
43
Around Advice E$ample
5Around(7e$ecution(5e$ample%Caceable 8 rewards%ser0ice%%8%8(%%))9)
public Bb;ect cace(!roceedingFoin!oint point) throws 6rowable {
Bb;ect 0alue ) cace"tore%get(caceKe#(point))'
if (0alue )) null) {
0alue ) point%proceed()'
cace"tore%put(caceKe#(point)- 0alue)'
(
return 0alue'
(
Cace 0alues returned b# caceable ser0ices
!roceed onl# if not alread# caced
=se @Around annotation
" ProceedingJoinPoint parameter
" !nherits from JoinPoint and adds the proceed() method
44
Alternative Spring AOP
S,nta$ - M.-
Annotation s,nta$ is :ava <N onl,
M.- s,nta$ wors on :ava 45O
Approach
" Aspect logic defined :ava
" Aspect configuration in M.-
=ses the aop namespace
45
Tracing Propert, Changes -
:ava Code
public class !ropert#Cange6racker {
public 0oid trackCange(Foin!oint point) {
+
(
(
Aspect is a !lain Fa0a Class wit no Fa0a @ annotations
46
Tracing Propert, Changes -
M.- Configuration
1aop:config2
1aop:aspect ref)7propert#Cange6racker92
1aop:before pointcut)7e$ecution(0oid set8(8))9 metod)7trackCange9=2
1=aop:aspect2
1=aop:config2
1bean id)7propert#Cange6racker9 class)7e$ample%!ropert#Cange6racker9 =2
M.- configuration uses the aop namespace
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
-A0
Developing Aspects with Spring AOP
48
Topics in this session
%hat Pro&lem Does AOP Solve'
Core AOP Concepts
Quic Start
Defining Pointcuts
!mplementing Advice
"d$anced topics
" -amed ointcuts
" Conte$t selecting pointcuts
" %oring with annotations
" -imitations of Spring AOP
49
Allow to reuse and com&ine pointcuts
5Aspect
public class !ropert#Cange6racker {
pri0ate /ogger logger ) /ogger%get/ogger(getClass())'
5*efore(7ser0ice,etod() LL repositor#,etod()9)
public 0oid monitor() {
logger%info(7A business metod as been accessed+9)'
(
5!ointcut(7e$ecution(8 rewards%ser0ice%%8"er0ice%8(%%))9)
public 0oid ser0ice,etod() {(
5!ointcut(7e$ecution(8 rewards%repositor#%%8Repositor#%8(%%))9)
public 0oid repositor#,etod() {(
(
#amed pointcuts
50
#amed pointcuts
E$pressions can &e e$ternali*ed
5Aspect
public class "er0ice,etodIn0ocation,onitor {
pri0ate /ogger logger ) /ogger%get/ogger(getClass())'
5*efore(7com%acme%"#stemArcitecture%ser0ice,etods()9 )
public 0oid monitor() {
logger%info(7A ser0ice metod as been accessed+9)'
(
(

public class "#stemArcitecture {
5!ointcut(7e$ecution(8 rewards%ser0ice%%8"er0ice%8(%%))9)
public 0oid ser0ice,etods() {(
(
Full#<Mualified pointcut name
51
+ive the possi&ilit, to &rea one complicated
e$pression into several su&-e$pressions
Allow pointcut e$pression reusa&ilit,
0est practice8 consider e$ternali*ing e$pressions
into one dedicated class
" %hen woring with man, pointcuts
" %hen writing complicated e$pressions
#amed pointcuts - Summar,
52
Topics in this session
%hat Pro&lem Does AOP Solve'
Core AOP Concepts
Quic Start
Defining Pointcuts
!mplementing Advice
"d$anced topics
" #amed Pointcuts
" Context selecting pointcuts
" %oring with annotations
" -imitations of Spring AOP
53
Conte$t Selecting Pointcuts
Pointcuts ma, also select useful >oin point
conte$t
" The currentl, e$ecuting o&>ect (pro$,)
" The target o&>ect
" .ethod arguments
" Annotations associated with the methodD targetD or
arguments
Allows for simple PO:O advice methods
" Alternative to woring with a :oinPoint o&>ect directl,
54
Conte$t Selecting E$ample
Consider this &asic re2uirement
/og a message e0er# time "er0er is about to start /og a message e0er# time "er0er is about to start
public interface "er0er {
public 0oid start(,ap input)'
public 0oid stop()'
(
public interface "er0er {
public 0oid start(,ap input)'
public 0oid stop()'
(
In te ad0ice- ow do we access "er0erN ,apN In te ad0ice- ow do we access "er0erN ,apN
55
%ithout conte$t selection
5*efore(7e$ecution(0oid e$ample%"er0erJ%start(;a0a%util%,ap))9)
public 0oid log"er0er"tartup(Foin!oint ;p) {
"er0er ser0er ) ("er0er) ;p%get6arget()'
Bb;ectHI args) ;p%getArgs()'
,ap map ) (,ap) argsHAI'
+
(
All needed info must &e o&tained from the
JoinPoint o&>ect
56
%ith conte$t selection
5*efore(7e$ecution(0oid e$ample%"er0erJ%start(;a0a%util%,ap))
OO target(ser0er) OO args(input)9)
public 0oid log"er0er"tartup("er0er ser0er- ,ap input) {
+
(
0est practice8 use conte$t selection
" .ethod attri&utes are &ound automaticall,
< target(ser0er) selects te target of te e$ecution (#our ob;ect)
< tis(ser0er) would a0e selected te pro$#
< target(ser0er) selects te target of te e$ecution (#our ob;ect)
< tis(ser0er) would a0e selected te pro$#
57
Conte$t Selection - #amed
Pointcut
5*efore(7ser0er"tart,etod(ser0er- input)9)
public 0oid log"er0er"tartup("er0er ser0er- ,ap input) {
+
(
5!ointcut(7e$ecution(0oid e$ample%"er0erJ%start(;a0a%util%,ap))
OO target(ser0er) OO args(input)9)
public 0oid ser0er"tart,etod ("er0er ser0er- ,ap input) {(
PtargetQ binds te ser0er starting up PargsQ binds te argument 0alue
58
Topics in this session
%hat Pro&lem Does AOP Solve'
Core AOP Concepts
Quic Start
Defining Pointcuts
!mplementing Advice
"d$anced topics
" #amed Pointcuts
" Conte$t selecting pointcuts
" Wor'ing with annotations
" -imitations of Spring AOP
59
Pointcut e$pression e$amples
using annotations
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
60
E$ample
5"ecured(allowedRoles){7teller9-9manager9()
public 0oid wai0eFee () {
+
(
equirements:
Run a securit# ceck before an# 5"ecured ser0ice operation
"ecurit# logic depends on:

annotation attribute 0alue R wat roles to ceckN

metod name R wat metod is protectedN

te PtisQ ob;ect R "pring AB! pro$# being protected


61
AOP and annotations - E$ample
5*efore(7e$ecution(8 ser0ice%%8%8(%%)) OO target(ob;ect) OO
5annotation(secured)9)
public 0oid runCeck(Foin!oint ;p- Bb;ect ob;ect- "ecured secured) {
ceck!ermission(;p- ob;ect- secured%allowedRoles())'
(
5*efore(7e$ecution(8 ser0ice%%8%8(%%)) OO target(ob;ect) OO
5annotation(secured)9)
public 0oid runCeck(Foin!oint ;p- Bb;ect ob;ect- "ecured secured) {
ceck!ermission(;p- ob;ect- secured%allowedRoles())'
(
Run a securit# ceck before an# 5"ecured ser0ice operation Run a securit# ceck before an# 5"ecured ser0ice operation
=se of the annotation() designator
62
AOP and annotations
" #amed pointcuts
5*efore(7secured,etod(ob;ect- secured)9)
public 0oid runCeck(Foin!oint ;p- Bb;ect ob;ect- "ecured secured) {
ceck!ermission(;p- ob;ect- secured%allowedRoles())'
(
5!ointcut(7e$ecution(8 ser0ice%%8%8(%%)) OO target(ob;ect) OO
5annotation(secured)9)
public 0oid secured,etod(Bb;ect ob;ect- "ecured secured) {(
5*efore(7secured,etod(ob;ect- secured)9)
public 0oid runCeck(Foin!oint ;p- Bb;ect ob;ect- "ecured secured) {
ceck!ermission(;p- ob;ect- secured%allowedRoles())'
(
5!ointcut(7e$ecution(8 ser0ice%%8%8(%%)) OO target(ob;ect) OO
5annotation(secured)9)
public 0oid secured,etod(Bb;ect ob;ect- "ecured secured) {(
Run a securit# ceck before an# 5"ecured ser0ice operation Run a securit# ceck before an# 5"ecured ser0ice operation
63
Topics in this session
%hat Pro&lem Does AOP Solve'
Core AOP Concepts
Quic Start
Defining Pointcuts
!mplementing Advice
"d$anced topics
" #amed Pointcuts
" Conte$t selecting pointcuts
" %oring with annotations
" .imitations o* Spring "#
64
-imitations of Spring AOP
Can onl, advise pu&lic :oin Points
Can onl, appl, aspects to Spring &eans
Some limitations of weaving with pro$ies
" Spring will add &ehavior using d,namic pro$ies if a
:oin Point is declared on an interface
" !f a :oin Point is in a class without an interfaceD
Spring will revert to using C+-!0 for weaving
" %hen using pro$iesD if method a() calls method &()
on the same class@interfaceD advice will never &e
e$ecuted for method &()
65
Summar,
Aspect Oriented Programming (AOP)
modulari*es cross-cutting concerns
An aspect is a module containing cross-
cutting &ehavior
" 0ehavior is implemented as IadviceJ
" Pointcuts select where advice applies
" 3ive advice t,pes8 0eforeD AfterThrowingD
After1eturningD After and Around
Aspects are defined in :ava with
annotations or M.- configuration
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Introduction to Data Access
with Spring
Springs role in supporting transactional data
access within an enterprise application
2
Topics in this Session
The role of Spring in enterprise dt ccess
Spring resource management
Spring data access support
Data access in a layered architecture
Common data access configurations
3
The Role of Spring in
Enterprise Data Access
Proide comprehensie data access support
! To ma"e data access easier to do effectiely
Ena#le a layered application architecture
! To isolate an applications #usiness logic from the
comple$ity of data access
4
%a"ing Data Access Easier
Ac&uisition of the connection
Participation in the transaction
E$ecution of the statement
Processing of the result set
'andling any e$ceptions
Release of the connection
int count = jdbcHelper.queryForInt(
"SELECT COUNT(! F"O# CUSTO#E""!$
All handled
by Spring
5
Ena#ling a (ayered
Architecture
%pplic&tion Ser'ice
"epo(itory ) "epo(itory * "epo(itory +
,&t&Source
Tr&n(&ction#&n&-er
Sprin- %pplic&tion Conte.t
Business logic
Data access logic
Data access
infrastructure
6
Topics in this Session
The role of Spring in enterprise data access
Spring resource mngement
Spring data access support
Data access in a layered architecture
Common data access configurations
7
Spring Resource
%anagement
Accessing e$ternal systems li"e a data#ase
re&uires resources
! (imited resources must #e managed properly
Putting the resource management #urden on
the application deeloper is unnecessary
Spring proides a comprehensie resource
management solution
8
The Resource %anagement
Pro#lem
To access a data source an application must
! Esta#lish a connection
To start its wor" the application must
! )egin a transaction
*hen done with its wor" the application must
! Commit or roll#ac" the transaction
! Close the connection
9
Effectie Resource
%anagement
%pplic&tion
in'o/e(input!
Tr&n(&ction
be-in
output
co00it
Connection
(elect d&t&
upd&te d&t&
clo(e
,o bu(ine(( lo-ic
-et
!
%anaging Resources
%anually
In many applications resource management is a
manual process
! The responsi#ility of the application deeloper
This is not an effectie approach
! Copy and pasting code
! Introducing su#tle+ potentially critical #ugs

,ot Effectie - Copy .


Pasting Code
doSo0e1or/(...! 2
try 2
-et connection
be-in tr&n(&ction
e.ecute S3L
proce(( t4e re(ult (et
co00it
5
c&tc4 (S3LE.ception e! 2
rollb&c/
t4ro6 &pplic&tion e.ception
5 7in&lly 2
try 2
clo(e connection
5
c&tc4 25
5
5
Unique
Copied
&round
e'ery64ere
2
,ot Effectie - Classic
%emory (ea"
doSo0e1or/(...! 2
try 2
-et connection
be-in tr&n(&ction
e.ecute S3L
e.ecute 0ore S3L
co00it
clo(e connection
5
c&tc4 (S3LE.ception! 2
rollb&c/
lo- e.ception
5
5
F%ILS
clo(e ne'er c&lled
3
Spring Resource
%anagement
Spring manages resources for you
! Eliminates #oilerplate code
! Reduces li"elihood of #ugs
Spring frees application deelopers from
mundane responsi#ility
! So they can get on with the real wor"
4
/ey Resource %anagement
0eatures
Declaratie transaction management
! Transactional #oundaries declared ia configuration
! Enforced #y a Spring transaction manager
Automatic connection management
! Connections ac&uired1released automatically
! ,o possi#ility of resource lea"
Intelligent e$ception handling
! Root cause failures always reported
! Resources always released properly
5
Spring Resource
%anagement
doSo0e1or/(..! 2
try 2
e(t&bli(4 connection
be-in tr&n(&ction
e.ecute S3L
proce(( t4e re(ult (et
co00it
5
c&tc4 (S3LE.ception! 2
rollb&c/
t4ro6 &pplic&tion e.ception
5 7in&lly 2
try 2
clo(e connection
5
c&tc4 25
5
5
B"#$%"
6
Spring Resource
%anagement
8Tr&n(&ction&l
doSo0e1or/(..! 2
e.ecute S3L
proce(( t4e re(ult (et
5
A#&"%
7
Spring Resource %anagement
*or"s Eerywhere
*or"s consistently with all leading data access
technologies
! 2aa Data#ase Connectiity 32D)C4
! 2)oss 'i#ernate
! 2aa Persistence API 32PA4
! Eclipse(in"
! Apache i)atis
In any enironment
! (ocal 3standalone app+ we# app4
! 0ull-#lown 2EE container
8
Topics in this Session
The role of Spring in enterprise data access
Spring resource management
Spring dt ccess support
Data access in a layered architecture
Common data access configurations
9
Spring Data Access Support
Spring proides support li#raries that simplify
writing data access code
! Promote consistency and code saings
Support is proided for all the ma5or data
access technologies
9 :&'& ,&t&b&(e Connecti'ity (:,;C!
9 %p&c4e i;&ti(
9 :;o(( Hibern&te
9 :&'& <er(i(tence %rc4itecture (:<%!
2!
Spring Data Access Support -
Scope
0or each data access technology+ Springs
support consists of
! A factory to help you configure the technology
! A #ase support class to help you implement DA6s
! A helper called a data access template to help you
use the pu#lic API effectiely
2
2D)C DA6 Support E$ample
public cl&(( :dbcCu(to0er"epo(itory e.tend( Si0ple:dbc,&oSupport
i0ple0ent( Cu(to0er"epo(itory 2

public int -etCountO7Cu(to0er(OlderT4&n(int &-e! 2
Strin- (ql = =(elect count(! 7ro0 cu(to0er 64ere &-e > ?@$
return -etSi0ple:dbcTe0pl&te(!.queryForInt((qlA &-e!$
5
5
public cl&(( :dbcCu(to0er"epo(itory e.tend( Si0ple:dbc,&oSupport
i0ple0ent( Cu(to0er"epo(itory 2

public int -etCountO7Cu(to0er(OlderT4&n(int &-e! 2
Strin- (ql = =(elect count(! 7ro0 cu(to0er 64ere &-e > ?@$
return -etSi0ple:dbcTe0pl&te(!.queryForInt((qlA &-e!$
5
5
Support cl&(( pro'ide(
,%O con7i-ur&tion &((i(t&nce
,&t& &cce(( 4elper (i0pli7ie( u(e o7 %<I
22
Topics in this Session
The role of Spring in enterprise data access
Spring resource management
Spring data access support
!t ccess in lyered rchitecture
Common data access configurations
23
Data Access in a (ayered
Architecture
Spring ena#les layered application architecture
%ost enterprise applications consist of three
logical layers
! Serice layer 3or application layer4
E$poses high-leel application functions
! Data access layer
Defines the interface to the applications data repository 3such as a
relational data#ase4
! Infrastructure layer
E$poses low-leel serices needed #y the other layers
24
(ayered Application
Architecture
Ser'ice L&yer
,&t& %cce(( L&yer
In7r&(tructure L&yer
25
The Serice (ayer 37reen4
Defines the pu#lic functions of the application
! Clients call into the application through this layer
Encapsulates the logic to carry out each
application function
! Delegates to the infrastructure layer to manage
transactions
! Delegates to the data access layer to map persistent
data into a form needed to e$ecute the #usiness logic
26
The Data Access (ayer
3Purple4
8sed #y the serice layer to access data needed
#y the #usiness logic
Encapsulates the comple$ity of data access
! The use of a data access API
2D)C+ 'i#ernate+ etc
! The details of data access statements
S9(+ '9(+ etc
! The mapping of data into a form suita#le for #usiness
logic
A 2D)C ResultSet to a domain o#5ect graph
27
The Infrastructure (ayer
3Red4
E$poses low-leel serices needed #y other
layers
! Infrastructure serices are used #y the application
! Application deelopers typically do not write them
! 6ften proided #y a framewor" li"e Spring
(i"ely to ary #etween enironments
! Production s: test
28
Data Access Infrastructure
Serices - Transaction %anager
Spring proides a transaction manager
a#straction for driing transactions
Includes implementations for all ma5or data
access technologies
! 2D)C
! 2aa Persistence API 32PA4
! 2aa Data 6#5ects 32D64
! 'i#ernate
! Toplin"
And the standard 2aa Transaction API 32TA4
29
Data Access Infrastructure
Serices - Data Source
Spring uses a standard 2D)C data source for
ac&uiring connections
! Proides seeral #asic implementations
! Integrates popular open source implementations
Apache D)CP+ c;p<
! Can integrate 2EE container-managed data sources
3!
Spring Putting the (ayers
Together at Configuration Time
%pplic&tion Ser'ice
"epo(itory ) "epo(itory * "epo(itory +
,&t&Source
Tr&n(&ction#&n&-er
Sprin- %pplic&tion Conte.t
'erfor(s the
functions of the
application
Accesses data
needed by the
application
'ools connections
Dri)es transactions
3
The (ayers *or"ing Together
at 8se Time 3=4
A serice initiates a function of the application
! )y delegating to a transaction manager to #egin a
transaction
! )y delegating to repositories to load data for
processing
All data access calls participate in the transaction
Repositories often return domain o#5ects that encapsulate domain
#ehaiors
32
The (ayers *or"ing Together
at 8se Time 3>4
A serice continues processing
! )y e$ecuting #usiness logic
! 6ften #y coordinating #etween domain o#5ects loaded
#y repositories
And finally+ completes processing
! )y updating changed data and committing the
transaction
! Some technologies apply repository updates for you
36R%s4
33
Application Serice -
Se&uence 3=4
Ser'ice
in'o/e
(input!
Tr&n(&ction
#&n&-er
"epo(itory
7ind,o0&inObject(criteri&!
,&t&Source Connection
(elect d&t&
do0&inObject
0&pObject("e(ultSet!
be-in tr&n(&ction
-et connection
ne6
tr&n(&ction
34
Application Serice -
Se&uence 3>4
,o biB lo-ic
Ser'ice
upd&te(do0&in object!
upd&te d&t&
co00it(tr&n(&ction!
clo(e
,o0&in Object "epo(itory
Tr&n(&ction
#&n&-er
Connection
output
bind(objectA (t&te0ent!
35
Declaratie Transaction
%anagement
Spring adds the transaction management calls
around your serice logic
?ou simply declare the transactional policies and
Spring enforces them
36
Setting Transactional Policies
Declaratiely
public cl&(( Ser'iceI0pl i0ple0ent( Ser'iceInter7&ce 2
8Tr&n(&ction&l
public 'oid in'o/e(C! 2
DD your &pplic&tion lo-ic
5
5
Tell( Sprin- to &l6&y( run t4i(
0et4od in & d&t&b&(e tr&n(&ction
37
Enforcing Declaratie
Transactional Policies
Ser'iceI0pl
in'o/e(input!
Sprin-
Tr&n(&ctionInterceptor
Tr&n(&ction#&n&-er
be-in co00it
Tr&n(&ction
0&n&-e0ent
be4&'ior i( &dded
&round your code
Eou c&n c4&n-e
tr&n(&ction
0&n&-er( 6it4out
&77ectin- your
&pplic&tion code
Sprin- %O< <ro.y
38
Effects on Connection
%anagement
Connections are managed for you
! Drien #y transactional #oundaries
! ,ot the responsi#ility of application code
! ,o possi#ility of connection lea"
Repositories always use the transactional
connection for data access
! Spring proides seeral ways to ensure this
39
Topics in this Session
The role of Spring in enterprise data access
Spring resource management
Spring data access support
Data access in a layered architecture
Common dt ccess configurtions
4!
(ocal 2D)C Configuration
"e6&rdNet6or/I0pl
:dbc%ccount"epo(itory :dbc"e(t&ur&nt"epo(itory :dbc"e6&rd"epo(itory
;&(ic,&t&Source
,&t&Source
Tr&n(&ction#&n&-er
4
2D)C 2aa EE Configuration
"e6&rdNet6or/I0pl
:dbc%ccount"epo(itory :dbc"e(t&ur&nt"epo(itory :dbc"e6&rd"epo(itory
:EE Cont&inerF#&n&-ed
,&t&Source
:T%
Tr&n(&ction#&n&-er
:ndiObject
F&ctory;e&n
retrie'e(
42
(ocal 'i#ernate Configuration
"e6&rdNet6or/I0pl
Hibern&te
%ccount"epo(itory
Hibern&te
"e(t&ur&nt"epo(itory
:dbc"e6&rd"epo(itory
Se((ionF&ctory
Hibern&te
Tr&n(&ction#&n&-er
;&(ic,&t&Source
Loc&lSe((ion
F&ctory;e&n
cre&te(
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Introduction to Spring JDBC
Simplifying JDBC-based data access with Spring
JDBC
2
Topics in this Session
Problems with traditional !"C
esults in redundant! error prone code
"eads to poor e#ception handling
Spring$s JdbcTemplate
Configuration
%uery e#ecution
&or'ing with result sets
(#ception handling
JDBC )amespace
3
edundant! (rror *rone Code
public List findByLastName(String lastName) {
List personList = new ArrayList()
!onnection conn = null
String s"l = #select first$name% age from &'(S)N w*ere last$name=+#
try {
,ataSource dataSource = ,ataSource-tils.get,ataSource()
conn = dataSource.getConnection()
&reparedStatement ps = conn.prepareStatement(s"l)
ps.setString(/% lastName)
(esultSet rs = ps.e0ecute1uery()
w*ile (rs.ne0t()) {
String firstName = rs.getString(2first$name#)
int age = rs.get3nt(#age2)
personList.add(new &erson(firstName% lastName% age))
4
4 catc* (S1L'0ception e) { 56 +++ 65 4
finally {
try {
conn.close()
4 catc* (S1L'0ception e) { 56 +++ 65 4
4
return personList
4
4
edundant! (rror *rone Code
public List findByLastName(String lastName) {
List personList = new rrayList()!
!onnection conn = null
String s"l = #select first$name% age from &'(S)N w*ere last$name=+#!
try {
,ataSource dataSource = ,ataSource-tils.get,ataSource()
conn = dataSource.getConnection()
&reparedStatement ps = conn.prepareStatement(s"l)
ps.setString(/% lastName)
(esultSet rs = ps.e0ecute1uery()
w*ile (rs.ne0t()) {
String firstName = rs,getString(-first$name.)!
int age = rs,get/nt(-age.)!
personList,add(new &erson(firstName% lastName% age))!
4
4 catc* (S1L'0ception e) { 56 +++ 65 4
finally {
try {
conn.close()
4 catc* (S1L'0ception e) { 56 +++ 65 4
4
return personList!
0
T*e bold matters 7 t*e
rest is boilerplate
1
public List findByLastName(String lastName) {
List personList = new ArrayList()
!onnection conn = null
String s"l = 8select first$name% age from &'(S)N w*ere last$name=+8
try {
,ataSource dataSource = ,ataSource-tils.get,ataSource()
conn = dataSource.getConnection()
&reparedStatement ps = conn.prepareStatement(s"l)
ps.setString(/% lastName)
(esultSet rs = ps.e0ecute1uery()
w*ile (rs.ne0t()) {
String firstName = rs.getString(8first$name8)
int age = rs.get3nt(8age8)
personList.add(new &erson(firstName% lastName% age))
4
4 catc* (S1L'0ception e) { 56 +++ 65 4
finally {
try {
conn.close()
4 catc* (S1L'0ception e) { 56 +++ 65 4
4
return personList
4
*oor (#ception +andling
9*at can
you do+
2
Topics in this session
*roblems with traditional JDBC
esults in redundant! error prone code
"eads to poor e#ception handling
Spring#s 3dbc4emplate
Configuration
%uery e#ecution
&or'ing with result sets
(#ception handling
JDBC )amespace
5
Spring$s JdbcTemplate
,reatly simplifies use of the JDBC -*I
(liminates repetiti.e boilerplate code
-lle.iates common causes of bugs
+andles S%"(#ceptions properly
&ithout sacrificing power
*ro.ides full access to the standard JDBC constructs
6
JdbcTemplate in a )utshell
-c/uisition of the connection
*articipation in the transaction
(#ecution of the statement
*rocessing of the result set
+andling any e#ceptions
elease of the connection
int count = :dbcTemplate."uery;or3nt(
#S'L'!T !)-NT(6) ;()< !-ST)<'(2)
int count = :dbcTemplate."uery;or3nt(
#S'L'!T !)-NT(6) ;()< !-ST)<'(2)
ll *andled
by Spring
7
JdbcTemplate -pproach 0.er.iew
List results = :dbcTemplate."uery(someS"l%
new (ow<apper() {
public )b:ect map(ow((esultSet rs% int row) t*rows S1L'0ception {
55 map t*e current row to an ob:ect
4
4)
class JdbcTemplate {
public List "uery(String s"l% (ow<apper row<apper) {
try {
55 ac"uire connection
55 prepare statement
55 e0ecute statement
55 for eac* row in t*e result set
results.add(row<apper.map(ow(rs% rowNumber))
return results
4 catc* (S1L'0ception e) {
55 con=ert to root cause e0ception
4 finally {
55 release connection
4
4
89
Creating a JdbcTemplate
e/uires a ,ataSource
Create a template once and re-use it
Do not create one for each use
Thread safe after construction
JdbcTemplate template = new JdbcTemplate(dataSource)
88
&hen to use JdbcTemplate
1seful standalone
-nytime JDBC is needed
In utility or test code
To clean up messy legacy code
1seful for implementing a repository in
a layered application
-lso 'nown as a data access ob2ect 3D-04
82
Implementing a JDBC-based
epository
public class Jdbc!ustomer(epository implements !ustomer(epository {
pri=ate JdbcTemplate :dbcTemplate
public Jdbc!ustomer(epository(,ataSource dataSource) {
t*is.:dbcTemplate = new JdbcTemplate(dataSource)
4

public int get!ustomer!ount() {
String s"l = #select count(6) from customer2
return :dbcTemplate."uery;or3nt(s"l)
4
4
83
Integrating a epository into an
-pplication
>bean id=#credit(eportingSer=ice2 class=#e0ample.!redit(eportingSer=ice2?
>property name=#order(epository2 ref=#order(epository2 5?
>property name=#customer(epository2 ref=#customer(epository2 5?
>5bean?
>bean id=#order(epository2 class=#e0ample.order.Jdbc)rder(epository2?
>constructor7arg ref=#dataSource25?
>5bean?
>bean id=#customer(epository2
class=#e0ample.customer.Jdbc!ustomer(epository2?
>constructor7arg ref=#dataSource2 5?
>5bean?
>:ee@:ndi7looAup id=#dataSource2 :ndi7name=#:a=a@comp5en=5:dbc5credit2 5?
3n:ect t*e repository into application ser=ices
!onfigure t*e repositoryBs ,ataSource
84
%uerying with JdbcTemplate
C
JdbcTemplate can /uery for
Simple types 3int! long! String4
,eneric 5aps
Domain 0b2ects
81
%uerying for Simple Ja.a
Types 364
%uery with no bind .ariables
public int get&erson!ount() {
String s"l = #select count(6) from &'(S)N2
return :dbcTemplate."uery;or3nt(s"l)
4
82
%uerying &ith JdbcTemplate

1uery wit* a bind =ariable


Note t*e use of a =ariable argument list
pri=ate JdbcTemplate :dbcTemplate
public int get!ount)f&ersons)lderT*an(int age) {
return :dbcTemplate."uery;or3nt(
#select count(6) from &'(S)N w*ere age ? +2% age)
4
85
,eneric %ueries
C
JdbcTemplate can return each row of a (esultSet
as a <ap
&hen e#pecting a single row
1se "uery;or<ap(..)
&hen e#pecting multiple rows
1se "uery;orList(..)
1seful for reporting! testing! and 7window-on-
data$ use cases
86
%uerying for ,eneric 5aps
364
%uery for a single row
returns8
5ap { 3,=/% ;3(ST$NA<'=#Jo*n2% LAST$NA<'=#,oe2 4
public <ap get&erson3nfo(int id) {
String s"l = #select 6 from &'(S)N w*ere id=+2
return :dbcTemplate."uery;or<ap(s"l% id)
4
A <ap of D!olumn Name E ;ield Falue G pairs
87
%uerying for ,eneric 5aps
394
%uery for multiple rows

returns8
List {
H 7 <ap { 3,=/% ;3(ST$NA<'=#Jo*n2% LAST$NA<'=#,oe2 4
/ 7 <ap { 3,=I% ;3(ST$NA<'=#Jane2% LAST$NA<'=#,oe2 4
I 7 <ap { 3,=J% ;3(ST$NA<'=#Junior2% LAST$NA<'=#,oe2 4
4
public List getAll&erson3nfo() {
String s"l = #select 6 from &'(S)N2
return :dbcTemplate."uery;orList(s"l)
4
A List of <aps of D!olumn Name E ;ield Falue G pairs
29
Domain 0b2ect %ueries
0ften it is useful to map relational data into
domain ob2ects
e:g: a (esultSet to an Account
Spring$s JdbcTemplate supports this using a
callback approach
;ou may prefer to use 05 for this
)eed to decide between JdbcTemplate /ueries and
J*- 3or similar4 mappings
28
ow5apper
Spring pro.ides a (ow<apper interface for
mapping a single row of a esultSet to an
ob2ect
Can be used for both single and multiple row /ueries
*arameteri<ed as of Spring =:>
public interface (ow<apper>T? {
T map(ow((esultSet rs% int rowNum)
t*rows S1L'0ception
4
22
%uerying for Domain 0b2ects 364
C
%uery for single row with JdbcTemplate
public &erson get&erson(int id) {
return :dbcTemplate."uery;or)b:ect(
#select first$name% last$name from &'(S)N w*ere id=+2%
new &erson<apper()% id)
4
class &erson<apper implements (ow<apper>&erson? {
public &erson map(ow((esultSet rs% int i) t*rows S1L'0ception {
return new &erson(rs.getString(8first$name8)%
rs.getString(8last$name8))
4
4
&arameteriKes return type
No need to cast
<aps rows to &erson ob:ects
23
%uerying for Domain 0b2ects 394
public List>&erson? getAll&ersons() {
return :dbcTemplate."uery(
8select first$name% last$name from &'(S)N8%
new &erson<apper())
class &erson<apper implements (ow<apper>&erson? {
public &erson map(ow((esultSet rs% int i) t*rows S1L'0ception {
return new &erson(rs.getString(8first$name8)%
rs.getString(8last$name8))
4
4
No need to cast
%uery for multiple rows
Same row mapper can be used
24
owCallbac'+andler
Spring pro.ides a simpler owCallbac'+andler
interface when there is no return ob2ect
Streaming rows to a file
Con.erting rows to ?5"
@iltering rows before adding to a Collection
but filtering in S%" is much more efficient
public interface (ow!allbacALandler {
=oid process(ow((esultSet rs) t*rows S1L'0ception
4
21
1sing a owCallbac'+andler
public class Jdbc)rder(epository {
public =oid generate(eport(9riter out) {
55 select all orders of year IHHM for a full report
:dbcTemplate."uery(#select 6 from order w*ere year=+2%
new )rder(eport9riter(out)% IHHM)
4
4
public class Jdbc)rder(epository {
public =oid generate(eport(9riter out) {
55 select all orders of year IHHM for a full report
:dbcTemplate."uery(#select 6 from order w*ere year=+2%
new )rder(eport9riter(out)% IHHM)
4
4
class )rder(eport9riter implements (ow!allbacALandler {
public =oid process(ow((esultSet rs) t*rows S1L'0ception {
55 parse current row from (esultSet and stream to output
4
56 stateful ob:ect@ may add con=enience met*ods liAe get(esults()% get!ount() etc. 65
4
class )rder(eport9riter implements (ow!allbacALandler {
public =oid process(ow((esultSet rs) t*rows S1L'0ception {
55 parse current row from (esultSet and stream to output
4
56 stateful ob:ect@ may add con=enience met*ods liAe get(esults()% get!ount() etc. 65
4
returns 8=oid8
22
esultSet(#tractor
Spring pro.ides a (esultSet'0tractor interface for
processing an entire esultSet at once
You are responsible for iterating the esultSet
e:g: for mapping entire esultSet to a single ob2ect
public interface (esultSet'0tractor>T? {
T e0tract,ata((esultSet rs) t*rows S1L'0ception%
,ataAccess'0ception
4
25
1sing a esultSet(#tractor
public class Jdbc)rder(epository {
public )rder findBy!onfirmationNumber(String number) {
55 e0ecute an outer :oin between order and item tables
return :dbcTemplate."uery(
#select...from order o% item i...conf$id = +2%
new )rder'0tractor()% number)
4
4
class )rder'0tractor implements (esultSet'0tractor>)rder? {
public )rder e0tract,ata((esultSet rs) t*rows S1L'0ception {
55 create an )rder ob:ect wit* 3tems from multiple rows
4
4
26
Summary of Callbac'
Interfaces
ow5apper
Best choice when each row of a esultSet maps to a
domain ob2ect
owCallbac'+andler
Best choice when no .alue should be returned from
the callbac' method for each row
esultSet(#tractor
Best choice when multiple rows of a esultSet map to
a single ob2ect
27
Inserts and 1pdates 364
Inserting a new row
public int insert&erson(&erson person) {
return :dbcTemplate.update(
#insert into &'(S)N (first$name% last$name% age)2 N
#=alues (+% +% +)2%
person.get;irstName()%
person.getLastName()%
person.getAge())
4
39
Inserts and 1pdates 394
1pdating an e#isting row
public int updateAge(&erson person) {
return :dbcTemplate.update(
#update &'(S)N set age=+ w*ere id=+2%
person.getAge()%
person.get3d())
4
38
S%"(#ception +andling
S%"(#ceptions are not e#plicitly caught in most
cases
But! when they are! they can create a leaky
abstraction
*ortability suffers
Testability does too
1sing the JdbcTemplate ensures that
S%"(#ceptions are handled in a consistent!
portable fashion
32
S%"(#ception +andling
Issues
+ard to determine cause of failure
5ust read a .endor-specific error code
S%"(#ception is a lea'y abstraction
-s a chec'ed e#ception a S1L'0ception must
propagate if it is not caught
"eads to one of two things8
ACatch and wrapB
Being swallowed
33
Spring S%"(#ception
+andling
S%"(#ceptions are handled consistently

esources are always released properly


,eneric S%"(#ceptions are translated to root
cause Data-ccess(#ceptions
*ro.ides consistency across all database .endors
@rees you from your own catch-and-wrap approach
(nables selecti.e handling by type of failure
(#ceptions always propagate if not caught
34
Spring Data-ccess(#ception
+ierarchy 3subset4
:ata(etrie;al<ailure'=ception
:ataccess(esource<ailure'=ception
>leanup<ailure:ataccess'=ception
/n;alid:ataccesspi?sage'=ception
/n;alid:ataccess(esource?sage'=ception
/ncorrect?pdateSemantics:ataccess'=ception
4ype@ismatc*:ataccess'=ception
)ptimisticLocAing<ailure'=ception
)bBect(etrie;al<ailure'=ception
:ataccess'=ception
?ncategoriCed:ataccess'=ception
:ata/ntegrityDiolation'=ception
:eadlocALoser:ataccess'=ception
)bBect)ptimisticLocAing<ailure'=ception
31
Topics in this session
*roblems with traditional JDBC
esults in redundant! error prone code
"eads to poor e#ception handling
Spring$s JdbcTemplate
Configuration
%uery e#ecution
&or'ing with result sets
(#ception handling
!"C $amespace
32
JDBC )amespace
>bean class=#e0ample.order.Jdbc)rder(epository2 ?
>property name=#dataSource2 ref=#dataSource2 5?
>5bean?
>:dbc@embedded7database id=#dataSource2 type=#LI2?
>:dbc@script location=#classpat*@sc*ema.s"l2 5?
>:dbc@script location=#classpat*@test7data.s"l2 5?
>5:dbc@embedded7database?
Introduced with Spring =:>
(specially useful for testing
Supports +9! +S%" and Derby
35
JDBC )amespace
>bean id=#dataSource2 class=#org.apac*e.commons.dbcp.Basic,ataSource2?
>property name=#url2 =alue=#O{dataSource.url42 5?
>property name=#username2 =alue=#O{dataSource.username42 5?
>property name=#password2 =alue=#O{dataSource.password42 5?
>5bean?
>:dbc@initialiKe7database data7source=#dataSource2?
>:dbc@script location=#classpat*@sc*ema.s"l2 5?
>:dbc@script location=#classpat*@test7data.s"l2 5?
>5:dbc@initialiKe7database?
-llows populating other DataSources! too
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
"-B
Introduction to Spring JDBC
Copyright2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Transaction Management
with Spring
An Overview of Springs Consistent Approach to
Managing Transactions
2
Topics in this session
Why use Trnsctions!
Local Transaction Management
Spring Transaction Management
Transaction Propagation
Rollback rles
Testing
A!vance! topics
3
"h# se Transactions$
To %nforce the AC&' Principles(
Atomic
) %ach nit of work is an all*or*nothing operation
Consistent
) 'atabase integrit# constraints are never violate!
&solate!
) &solating transactions from each other
'rable
) Committe! changes are permanent
4
Transactions in the
Rewar!+etwork
The rewardAccountFor(Dining) metho! represents
a nit*of*work that shol! be atomic
5
Rewar!+etwork Atomicit#
The rewardAccountFor(Dining) nit*of*work(
findByCreditCard(String)
findByMerchantNumber(String)
cacuateBenefitFor(Account! Dining)
ma#eContribution(MonetaryAmount)
u$dateBeneficiarie%(Account)
confirm&eward(AccountContribution! Dining)
'ATA,AS%
'( S)*)C+
2( S)*)C+
3( ,-DA+)
4( .NS)&+
&eward
Networ#
Account
&e$o%itory
&e%taurant
&e$o%itory
&eward
&e$o%itory
&e%taurant Account
/
+a-ve Approach(
Connection per 'ata Access Operation
This nit*of*work contains . !ata access
operations
%ach ac/ires0 ses0 an! releases a !istinct
Connection
The nit*of*work is non-transactional
0
Rnning non*Transactionall#
findByCreditCard(String)
findByMerchantNumber(String)
u$dateBeneficiarie%(Account)
confirm&eward(AccountContribution! Dining)
'ATA,AS%
'( S)*)C+
2( S)*)C+
3( ,-DA+)
4( .NS)&+
&eward
Networ#
Account
&e$o%itory
&e%taurant
&e$o%itory
&eward
&e$o%itory
Connection DataSource
getConnection()
co%e()
getConnection()
co%e()
getConnection()
co%e()
getConnection()
co%e()
connection1'
connection12
connection13
connection14
2
Partial 1ailres
Sppose an Accont is being rewar!e!
&f the beneficiaries are p!ate!2
,t the rewar! confirmation fails2
There will be no recor! of the rewar!3
"
The unit-of-work
is not atomic
3
Correct Approach(
Connection per 4nit*of*"ork
More efficient
) Same Connection rese! for each operation
Operations complete as an atomic nit
) %ither all sccee! or all fail
The nit*of*work can rn in a transaction
'4
Rnning in a Transaction
findByCreditCard(String)
findByMerchantNumber(String)
u$dateBeneficiarie%(Account)
confirm&eward(AccountContribution! Dining)
'ATA,AS%
'( S)*)C+
2( S)*)C+
3( ,-DA+)
4( .NS)&+
&eward
Networ#
Account
&e$o%itory
&e%taurant
&e$o%itory
&eward
&e$o%itory
Connection DataSource
getConnection()
co%e()
+5
connection1'
''
Topics in this session
"h# se Transactions$
#ocl Trnsction $ngement
Spring Transaction Management
Transaction Propagation
Rollback rles
Testing
A!vance! topics
'2
Local Transaction
Management
Transactions can be manage! at the level of a
local resorce
) Sch as the !atabase
Re/ires programmatic management of
transactional behavior on the Connection
'3
Local Transaction Management
%5ample
public void updateBeneficiaries(Account account) {
...
try {
conn 6 dataSource(getConnection()7
conn(%etAutoCommit(fa%e)7
ps = conn.prepareStateent(s!l)"
for (Beneficiary b # account.getBeneficiaries()) {
ps.setBigDecial($% b.getSavings().asBigDecial())"
ps.set&ong('% account.get(ntity)d())"
ps.setString(*% b.get+ae())"
ps.e,ecute-pdate()"
.
conn(commit()7
. catc/ ((,ception e) {
conn(robac#()7
t/row new 0untie(,ception(1(rror updating23% e)"
.
'4
Problems with Local
Transactions
Connection management co!e is error*prone
Transaction !emarcation belongs at the service
la#er
) Mltiple !ata access metho!s ma# be calle! within a
transaction
) Connection mst be manage! at a higher level
'5
Topics in this session
"h# se Transactions$
Local Transaction Management
Spring Trnsction $ngement
Transaction Propagation
Rollback rles
Testing
A!vance! topics
'/
Spring Transaction
Management
Provi!es a fle5ible an! powerfl abstraction
la#er for transaction management
Several wa#s 6can be mi5e! an! matche!7
) 8ML
) Annotations
) Programmatic
Optimi9ation for local transactions
) 'atabase connection atomaticall# bon! to the
crrent threa!
'0
PlatformTransactionManager
Springs -atform+ran%actionManager is the base
interface for the abstraction
Several implementations are available
4 DataSource5ransaction6anager
4 7ibernate5ransaction6anager
4 8pa5ransaction6anager
4 8ta5ransaction6anager
4 9eb&ogic8ta5ransaction6anager
4 9ebSp/ere-ow5ransaction6anager
4 and more
Spring allows you to configure w/et/er you use 85A or not. )t does not
/ave any ipact on your 8ava classes
'2
'eplo#ing the Transaction
Manager
Pick the specific implementation
or for :TA0 also possible to se cstom tag(
) Resolves to appropriate impl for environment
OC.::taTransactionManager
"ebLogic:taTransactionManager
"ebSphere4owTransactionManager
:taTransactionManager
:bean id=1transaction6anager3
class=3org.springfraewor;.<dbc.datasource.DataSource5ransaction6anager3=
:property nae=1dataSource3 ref=1dataSource3>=
:>bean=
8t9:;ta1tran%action1manager<=
'3
'eclarative Transactions with
Spring
'eclarative transactions are the recommen!e!
approach
There are onl# ; steps
) 'efine a 5ransaction6anager
) 'eclare the transactional metho!s
Spring spports both Annotation*!riven an!
8ML*base! configration
24
<Transactional configration
&n the co!e(
&n the configration(
public class 0eward+etwor;)pl ipleents 0eward+etwor; {
>+ran%actiona
public 0ewardConfiration rewardAccountFor(Dining d) {
>> atoic unit?of?wor;
.
.
8t9:annotation1dri?en<=
:bean id=1transaction6anager3
class=3org.springfraewor;.<dbc.datasource.DataSource5ransaction6anager3=
:property nae=1dataSource3 ref=1dataSource3>=
:>bean=
2'
Transaction starte! before entering the metho!
Commit at the en! of the metho!
Rollback if metho! throws a Rntime%5ception
) 'efalt behavior
) Can be overri!!en 6see later7
<Transactional( what happens
e5actl#$
22
<Transactional at the class level
>+ran%actiona
public class 0eward+etwor;)pl ipleents 0eward+etwor; {

public 0ewardConfiration rewardAccountFor(Dining d) {
>> atoic unit?of?wor;
.
public 0ewardConfiration updateConfiration(0ewardConfirantion rc) {
>> atoic unit?of?wor;
.
.
Applies to all metho!s !eclare! b# the interface6s7
@Transactional can also be declared at t/e interface>parent class level
23
<Transactional at the class an!
metho! levels
Combining class an! metho! levels
>+ran%actiona(timeout6/4)
public class 0eward+etwor;)pl ipleents 0eward+etwor; {

public 0ewardConfiration rewardAccountFor(Dining d) {
>> atoic unit?of?wor;
.
>+ran%actiona(timeout645)
public 0ewardConfiration updateConfiration(0ewardConfirantion rc) {
>> atoic unit?of?wor;
.
.
default settings
overriding attributes at
t/e et/od level
24
8ML*base! Spring
Transactions
Cannot alwa#s se <Transactional
) Annotation*!riven transactions re/ire :'= >
) Someone else ma# have written the service 6withot
annotations7
Spring also provi!es an option for 8ML
) An AOP pointct !eclares what to a!vise
) Springs tx namespace enables a concise !efinition of
transactional a!vice
) Can a!! transactional behavior to an# class se! as a
Spring ,ean
25
:aop#config=
:aop#pointcut id=1reward+etwor;6et/ods3
e,pression=1e9ecution($ubic @ reward%((&ewardNetwor#A(@((())3>=
:aop#advisor pointcut?ref=1reward+etwor;6et/ods3 advice?ref=1t,Advice3>=
:>aop#config=
:t,#advice id=1t,Advice3=
:t,#attributes=
:t,#et/od name6Bget@B read1ony6BtrueB timeout6B'4B>=
:t,#et/od name6Bfind@B read1ony6BtrueB timeout6B'4B>=
:t,#et/od name6B@B timeout6B34B>=
:>t,#attributes=
:>t,#advice=
:bean id=1transaction6anager3
class=1org.springfraewor;.<dbc.datasource.DataSource5ransaction6anager3=
:property nae=1dataSource3 ref=1dataSource3>=
:>bean=
'eclarative Transactions(
8ML
Aspect8 pointcut e,pression
6et/od?level configuration
for transactional advice
)ncludes rewardsAccountFor(..) and
updateConfiration(..)
2/
Topics in this session
"h# se Transactions$
Local Transaction Management
Spring Transaction Management
%soltion le&els
Transaction Propagation
Rollback rles
Testing
A!vance! topics
20
&solation levels
. isolation levels can be se!(
) R%A'?4+COMM&TT%'
) R%A'?COMM&TT%'
) R%P%ATA,L%?R%A'
) S%R&AL&@A,L%
Some ',MSs !o not spport all isolation levels
&solation is a complicate! sbAect
) ',MS all have !ifferences in the wa# their isolation
policies have been implemente!
) "e Ast provi!e general gi!elines
22
'irt# Rea!s
Transactions
should be
isolated unable
to see the results
of another
uncommitted
unit-of-work
"
rollback
23
R%A'?4+COMM&TT%'
Lowest isolation level
Allows dirty reads
Crrent transaction can see the reslts of
another ncommitte! nit*of*work
public class 0eward+etwor;)pl ipleents 0eward+etwor; {
>+ran%actiona (i%oation6.%oation(&)ADC,NCDMM.++)D)
public 0ewardConfiration rewardAccountFor(Dining d) {
>> atoic unit?of?wor;
.
.
34
R%A'?COMM&TT%'
'oes not allow !irt# rea!s
) Onl# committe! information can be accesse!
'efalt strateg# for most !atabases
public class 0eward+etwor;)pl ipleents 0eward+etwor; {
>+ran%actiona (i%oation6.%oation(&)ADCCDMM.++)D)
public 0ewardConfiration rewardAccountFor(Dining d) {
>> atoic unit?of?wor;
.
.
3'
Bighest isolation levels
R%P%ATA,L%?R%A'
) 'oes not allow !irt# rea!s
) +on*repeatable rea!s are prevente!
&f a row is rea! twice in the same transaction0 reslt will
alwa#s be the same
) Might reslt in locking !epen!ing on the ',MS
S%R&AL&@A,L%
) Prevents non*repeatable rea!s an! !irt#*rea!s
) Also prevents phantom rea!s
32
Topics in this session
"h# se Transactions$
Local Transaction Management
Spring Transaction Management
&solation levels
Trnsction 'ropgtion
Rollback rles
Testing
A!vance! topics
33
Consi!er the sample belowC "hat shol! happen
if ClientService&mpl calls AccontService&mpl$
) Shol! ever#thing rn into a single transaction$
) Shol! each service have its own transaction$
public class ClientService)pl
ipleents ClientService {
>Autowired
$ri?ate AccountService accountService"

>+ran%actiona
public void updateClient(Client c)
{ >> @
t/is.accountService.update(c.getAccounts())"
.
.
public class ClientService)pl
ipleents ClientService {
>Autowired
$ri?ate AccountService accountService"

>+ran%actiona
public void updateClient(Client c)
{ >> @
t/is.accountService.update(c.getAccounts())"
.
.
public class AccountService)pl
ipleents AccountService
{
>+ran%actiona
public void update(&ist :Account= l)
{ >> @ .
.
public class AccountService)pl
ipleents AccountService
{
>+ran%actiona
public void update(&ist :Account= l)
{ >> @ .
.
4n!erstan!ing Transaction
Propagation( %5ample
34
4n!erstan!ing Transaction
Propagation
Caller
+ran%action created!
committed or roed
bac# a% needed
5ransactional et/od '
.% there an e9i%ting tran%actionE Shoud
method 2 e9ecute in that tran%action (A)
Single Trnsction
(
Beha?ior dri?en by metadata for the method
or %houd a new tran%action be created (B)!
with outer tran%action %u%$endedE
5ransactional et/od $
Trnsction 2
Trnsction )
*
35
Transaction propagation with
Spring
D levels of propagation
The following e5amples show REQUIRED an!
REQUIRES_NEW
) Check the documentation for other levels
Can be se! as follows(
>+ran%actiona( $ro$agation6-ro$agation(REQUIRES_NEW ) >+ran%actiona( $ro$agation6-ro$agation(REQUIRES_NEW )
3/
R%E4&R%'
R%E4&R%'
) 'efalt vale
) %5ecte within a crrent transaction0 create a new one if
none e5ists
>+ran%actiona($ro$agation6-ro$agation(REQUIRED) >+ran%actiona($ro$agation6-ro$agation(REQUIRED)
t,$ t,$
t,$
no t,
30
R%E4&R%S?+%"
R%E4&R%S?+%"
) Create a new transaction0 sspen!ing the crrent transaction
if one e5ists
t,$ t,'
t,$
no t,
>+ran%actiona($ro$agation6-ro$agation(REQUIRES_NEW) >+ran%actiona($ro$agation6-ro$agation(REQUIRES_NEW)
32
Topics in this session
"h# se Transactions$
Local Transaction Management
Spring Transaction Management
Transaction Propagation
+ollbc, rules
Testing
A!vance! topics
33
'efalt behavior
,# !efalt0 a transaction is rolle! back if a
Rntime%5ception has been thrown
) Col! be an# kin! of Rntime%5ception(
'ataAccess%5ception0 Bibernate%5ception etcC
public class 0eward+etwor;)pl ipleents 0eward+etwor; {
>+ran%actiona
public 0ewardConfiration rewardAccountFor(Dining d) {
>> ...
t/row new 0untie(,ception()"

.
.
public class 0eward+etwor;)pl ipleents 0eward+etwor; {
>+ran%actiona
public 0ewardConfiration rewardAccountFor(Dining d) {
>> ...
t/row new 0untie(,ception()"

.
.
5riggers a rollbac;
44
rollback1or an! noRollback1or
'efalt settings can be overri!!en with
rollbackorFnoRollbackor attribtes
public class 0eward+etwor;)pl ipleents 0eward+etwor; {

>+ran%actiona(robac#For6F&emote)9ce$tion(ca%%!MyDwn)9ce$tion(ca%%G)
public 0ewardConfiration rewardAccountFor(Dining d) t/rows SA&(,ception {
>> ...
.
>+ran%actiona(no&obac#For6&untime)9ce$tion(ca%%)
public 0ewardConfiration rewardAccountFor(Dining d) {
>> ...
.
.
public class 0eward+etwor;)pl ipleents 0eward+etwor; {

>+ran%actiona(robac#For6F&emote)9ce$tion(ca%%!MyDwn)9ce$tion(ca%%G)
public 0ewardConfiration rewardAccountFor(Dining d) t/rows SA&(,ception {
>> ...
.
>+ran%actiona(no&obac#For6&untime)9ce$tion(ca%%)
public 0ewardConfiration rewardAccountFor(Dining d) {
>> ...
.
.
Bverrides default settings# t/ere s/ould not be a
rollbac; in case of t/is specific (,ception
not 0untie(,ception(s)
4'
Topics in this session
"h# se Transactions$
Local Transaction Management
Spring Transaction Management
Transaction Propagation
Rollback rles
Testing
A!vance! topics
42
<Transactional in an
&ntegration Test
Annotate test metho! 6or t#pe7 with
<Transactional to rn test metho!s in a
transaction that will be rolle! back afterwar!s
) +o nee! to clean p #or !atabase after testing3
>Conte9tConfiguration(locations={C>rewards?config.,lC.)
>&unHith(Spring8-nitDClass0unner.ca%%)
$ubic ca%% 0eward+etwor;5est {
>+e%t >+ran%actiona
public void test0ewardAccountFor() {
...
.
.
>Conte9tConfiguration(locations={C>rewards?config.,lC.)
>&unHith(Spring8-nitDClass0unner.ca%%)
$ubic ca%% 0eward+etwor;5est {
>+e%t >+ran%actiona
public void test0ewardAccountFor() {
...
.
.
43
A!vance! se of
<Transactional in a 4nit Test
>Conte9tConfiguration(locations={C>rewards?config.,lC.)
>&unHith(Spring8-nitDClass0unner.ca%%)
>+ran%actionConfiguration(default0ollbac;=false% transaction6anager=Ct,6grC)
>+ran%actiona
$ubic ca%% 0eward+etwor;5est {
>+e%t
>&obac#(true)
public void test0ewardAccountFor() {
...
.
.
>Conte9tConfiguration(locations={C>rewards?config.,lC.)
>&unHith(Spring8-nitDClass0unner.ca%%)
>+ran%actionConfiguration(default0ollbac;=false% transaction6anager=Ct,6grC)
>+ran%actiona
$ubic ca%% 0eward+etwor;5est {
>+e%t
>&obac#(true)
public void test0ewardAccountFor() {
...
.
.
5ransactions does a commit at t/e
end by default
Bverrides default rollback settings
)nside @TransactionConfiguration% no need to specify t/e
transactionManager attribute if t/e bean id is 1transaction6anager3
44
<,efore vs <,eforeTransaction
<,efore rns in the transaction
<,eforeTransaction rns before the transaction
starts
>Conte9tConfiguration(locations={C>rewards?config.,lC.)
>&unHith(Spring8-nitDClass0unner.ca%%)
$ubic ca%% 0eward+etwor;5est {
>Before+ran%action
public void verify)nitialDatabaseState() {@.
>Before
public void set-p5estData)n5ransaction() {@.
>+e%t >+ran%actiona
public void test0ewardAccountFor() {
...
.
.
>Conte9tConfiguration(locations={C>rewards?config.,lC.)
>&unHith(Spring8-nitDClass0unner.ca%%)
$ubic ca%% 0eward+etwor;5est {
>Before+ran%action
public void verify)nitialDatabaseState() {@.
>Before
public void set-p5estData)n5ransaction() {@.
>+e%t >+ran%actiona
public void test0ewardAccountFor() {
...
.
.
0un before transaction is started
9it/in t/e transaction
@After and @AfterTransaction wor; in t/e sae way as @Before and
@BeforeTransaction
Copyright2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
LA,
Managing Transactions 'eclarativel# with Spring
Annotations
4/
Topics in this session
"h# se Transactions$
Local Transaction Management
Spring Transaction Management
Transaction Propagation
Rollback rles
Testing
(d&nced topics
) Programmatic transactions
) Rea!*onl# transactions
) Mltiple transaction managers
) 'istribte! transactions
40
Programmatic Transactions with
Spring
'eclarative transaction management is highl#
recommen!e!
) Clean co!e
) 1le5ible configration
Spring !oes enable programmatic transaction
4 "orks with local or :TA transaction manager
Can be useful inside a tec/nical fraewor; t/at would not rely on
e,ternal configuration
42
Programmatic Transactions(
e5ample
public 0ewardConfiration rewardAccountFor(Dining dining) {
...
t,5eplate = new 5ransaction5eplate(t,6anager)"
return t,5eplate.e,ecute(new 5ransactionCallbac;() {
public Bb<ect do)n5ransaction(5ransactionStatus status) {
try {
...
account0epository.updateBeneficiaries(account)"
confiration = reward0epository.confir0eward(contribution% dining)"
.
catc/ (0eward(,ception e) {
%tatu%(%et&obac#Dny()7
.
return confiration"
.
.)"
.
43
Rea!*onl# transactions 6G7
"h# se transactions if #oHre onl# planning to
rea! !ata$
) Performance( allows Spring to optimi9e the
transactional resorce for rea!*onl# !ata access
public void rewardAccount$() {
<dbc5eplate.!ueryForBb<ect(@)"
<dbc5eplate.!ueryFor)nt(@)"
.
E5ransactional(readBnly=true)
public void rewardAccount'() {
<dbc5eplate.!ueryForBb<ect(@)"
<dbc5eplate.!ueryFor)nt(@)"
.

$ single connection
' connections
54
Rea!*onl# transactions 6;7
"h# se transactions if #oHre onl# planning to
rea! !ata$
) &solation( with a high isolation level0 a rea!Onl#
transaction prevents !ata from being mo!ifie! ntil the
transaction commits
5'
Mltiple Transaction Managers
<Transactional can !eclare the i! of the
transactionManager that shol! be se!
E5ransactional(CyBt/er5ransaction6anagerC)
public void rewardAccount$() {
<dbc5eplate.!ueryForBb<ect(@)"
<dbc5eplate.!ueryFor)nt(@)"
.
E5ransactional
public void rewardAccount'() {
<dbc5eplate.!ueryForBb<ect(@)"
<dbc5eplate.!ueryFor)nt(@)"
.

-ses t/e bean id
Ctransaction6anagerC by default
-ses t/e bean id
CyBt/er5ransaction6anagerC
52
'istribte! transactions
A transaction might involve several !ata sorces
) ; !ifferent !atabases
) G !atabase an! G :MS /ee
) 2
'istribte! transactions often re/ire specific
!rivers 68A !rivers7
&n :ava0 'istribte! transactions often rel# on
:TA
) :ava Transaction AP&
53
'istribte! transactions )
Spring integration
Man# possible strategies
Spring allows #o to switch easil# from a non*:TA
to a :TA transaction polic#
Reference( 'istribte! transactions with Spring0
with an! withot 8A 6'rC 'ave S#er7
) http(FFwwwCAavaworl!CcomFAavaworl!FAw*IG*;IIJFAw*
IG*spring*transactionsChtml
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Object/Relational Mapping
Fundamental Concepts and Concerns When
Using O/R Mapping in Enterprise Applications
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 2
Topics in this session
The Object/el!tion!l mism!tch
ORM in contet
!ene"its o" O/R Mapping
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 3
The Object/Relational
Mismatch #$%
A domain object model is designed to ser&e the
needs o" the application
' Organi(e data into abstract concepts that pro&e
use"ul to sol&ing the domain problem
' Encapsulate beha&ior speci"ic to the application
' Under the control o" the application de&eloper
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 4
The Object/Relational
Mismatch #)%
Relational models relate business data and are
t*picall* dri&en b* other "actors+
' ,er"ormance
' -pace
Furthermore. a relational database schema
o"ten+
' ,redates the application
' /s shared 0ith other applications
' /s managed b* a separate 1!A group
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 5
Object/Relational Mapping
Object/Relational Mapping #ORM% engines eist
to mitigate the mismatch
-pring supports all o" the major ones+
' 2ibernate
' Eclipse3in4
' Other 5,A #5a&a ,ersistence A,/% implementations.
such as Open5,A
This session 0ill "ocus on 2ibernate
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 6
Topics in this session
The Object/Relational Mismatch
O" in context
!ene"its o" modern6da* ORM engines
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 7
ORM in contet
For the ew!rd #ining domain
' The database schema alread* eists
' -e&eral applications share the data
Database
Reward
Network
Account Management
Portal
Merchant
Reporting
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 8
The integration database
schema
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 9
The Re0ard7et0or4
application
Re0ards an account "or dining
' !* as4ing the est!ur!nt 0here the dining occurred
to calculate the bene"it amount
' Then. b* ma4ing a contribution to the $ccount that
initiated the dining
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 10
The Re0ard7et0or4 application
RewardNetworkImpl Restaurant
Account
calculateBenefitFor
(Account Dining!
rewardAccountFor
(Dining!
make"ontribution(Monetar#Amount!
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 11
Restaurant bene"it calculations are based on a+
' !ene"it percentage
e8g8 9: o" the dining bill
' !ene"it a&ailabilit* polic*
e8g8 some Restaurants onl* re0ard bene"it on certain da*s
The Restaurant module
BenefitA$ailabilit#Polic#
%% interface &&
Restaurant
calculateBenefitFor(Account Dining!
benefitPercentage
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 12
The Account module
Account contributions are distributed among the
account;s bene"iciaries
' Each bene"iciar* has an allocation percentage
' The total bene"iciar* allocation must add up to $<<:
Account
'(()
make"ontribution(amount!
is*alid(!
Beneficiar#
allocationPercentage
sa$ings
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 13
Account and Restaurant data
All account and restaurant data is stored in the
database
' 1ata is needed b* se&eral applications
What are the major challenges in mapping this
object model to the relational model=
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 14
O/R Mismatch+ >ranularit* #$%
/n an object6oriented language. cohesi&e "ine6
grained classes pro&ide encapsulation and
epress the domain naturall*
/n a database schema. granularit* is t*picall*
dri&en b* normali(ation and per"ormance
considerations
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 15
O/R Mismatch+ >ranularit* #)%
"+,-.M/R
"+,-0ID %%P1&&
FIR,-0NAM/
2A,-0NAM/
/MAI2
P3.N/
,-R//-0N+MB/R
,-R//-0NAM/
"I-4
,-A-/
5IP0".D/
"ustomer
6 customerId
6 firstName
6 lastName
Address
6 streetNumber
6 streetName
6 cit#
6 state
6 7ip"ode
/mailAddress
PhoneNumber
Domain Model in Java Table in Database
just one example
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 16
O/R Mismatch+ /dentit* #$%
/n 5a&a. there is a di""erence bet0een Object
identit* and Object e?ui&alence+
' @@ * identity #same memor* address%
' 8e?uals#*% equivalence
/n a database. identit* is based solel* on
primar* 4e*s+
' 8getEntit*/d#%8e?uals#*8getEntit*/d#%%
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 17
O/R Mismatch+ /dentit* #)%
When 0or4ing 0ith persistent Objects. the
identit* problem leads to di""icult challenges
) Objects ma* be logicall* e?ui&alent. but onl*
one has a &alue set "or its primar* 4e* "ield
-ome o" the challenges+
' /mplement e?uals to accommodate this scenario
' 1etermine 0hen to update and 0hen to insert
' A&oid duplication 0hen adding to a Collection
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 18
O/R Mismatch+
/nheritance and Associations #$%
/n an object6oriented language+
' IS-A relations are modeled 0ith inheritance
' HAS-A relations are modeled 0ith composition
/n a database schema. relations are limited to
0hat can be epressed b* foreign keys
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 19
O/R Mismatch+
/nheritance and Associations #)%
!i6directional associations are common in a
domain model #e8g8 ,arent6Child%
' This can be modeled naturall* in each Object
/n a database+
' One side #parent% pro&ides a primar*64e*
' Other side #child% pro&ides a "oreign64e* re"erence
For man*6to6man* associations. the database
schema re?uires a join table
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 20
Topics in this session
The Object/Relational Mismatch
ORM in Contet
%ene&its o& O/ "!pping
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 21
!ene"its o" ORM
Object Auer* 3anguage
Automatic Change 1etection
,ersistence b* Reachabilit*
Caching
' ,er6Transaction #$
st
3e&el%
' ,er61ata-ource #)
nd
3e&el%
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 22
Object Auer* 3anguage
When 0or4ing 0ith domain objects. it is more
natural to ?uer* based on objects8
' Auer* 0ith -A3+
' Auer* 0ith object properties and associations+
SELECT c.first_name, c.last_name, a.city, ...
FROM customer c, customer_address ca, address a
WHERE ca.customer_id = c.id
!" ca.address_id = a.id
!" a.#i$_code = %&'()
*from Customer c +,ere c.address.#i$Code = %&'()-
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 23
Automatic Change 1etection
When a unit6o"60or4 completes. all modi"ied
state 0ill be s*nchroni(ed 0ith the database8
,er$ice
in$oke(input!
find
output
Repositor#'
find
commi
t
modif#
+nit.f8ork
begin
Database
flush
Repositor#9
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 24
,ersistence b* Reachabilit* #$%
When a persistent object is being managed.
other associated objects ma* become managed
transparentl*+
.rder order : orderRepositor#(findB#"onfirmationId(cid!;
// order is now a managed object retrieved via OR
2ineItem item : new 2ineItem(((!;
order(add2ineItem(item!;
// item is now a managed object reac!ab"e #rom order
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 25
,ersistence b* Reachabilit* #)%
The same concept applies "or deletion+
.rder order : orderRepositor#(findB#"onfirmationId(cid!;
// order is now a managed object retrieved via OR
2ist%2ineItem& items : order(get2ineItems(!;
#or (2ineItem item < items! =
i# (item(is"ancelled(!! = order(remo$eItem(item!; >
// t!e database row #or t!is item wi"" be de"eted
>
i# (order(is"ancelled(!! =
orderRepositor#(remo$e(order!;
// a"" item rows #or t!e order wi"" be de"eted
>
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 26
Caching
The "irst6le&el cache #$3C% is scoped at the le&el
o" a unit6o"60or4
' When an object is "irst loaded "rom the database
0ithin a unit6o"60or4 it is stored in this cache
' -ubse?uent re?uests to load that same entit* "rom
the database 0ill hit this cache "irst
The second6le&el cache #)3C% is scoped at the
le&el o" the ,essionFactor#
' Reduce trips to database "or read6hea&* data
' Especiall* use"ul 0hen a single application has
eclusi&e access to the database
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Object/Relational Mapping with
Spring and Hibernate
2
Topics in this session
Introduction to Hibernte
!pping
"uerying
Configuring a Hibernate SessionFactor
!"ple"enting #ati$e Hibernate %&Os
Spring's HibernateTe"plate
3
!ntroduction to Hibernate
Hibernate's Session is a stateful object
representing a unit(of(wor)
Corresponds at a higher(le$el to a Connection
Manages persistent objects within the unit(of(wor)
&cts as a transaction(scoped cache *+,C-
& SessionFactory is a thread(safe. shareable
object that represents a single data source
/ro$ides access to a transactional Session
Manages the globall(scoped cache *0,C-
4
Hibernate Mapping
Hibernate re1uires "etadata for "apping
classes and their properties to database tables
and their colu"ns
Metadata can be pro$ided as 2M, or
annotations
This session will present both approaches
Carefull consider pros and cons of each
approach. as well as hbrid approach
5
&nnotations support in
Hibernate
Hibernate supports two sets of annotations
ja$a34persistence45 *standard. defined b 6/&-
#ati$e Hibernate annotations *e3tensions to 6/&
annotations-
7est practice8
9se ja$a34persistence45 annotations for tpical
features
9se Hibernate annotations for e3tensions
For beha$ior not supported b 6/&
/erfor"ance enhance"ents specific to Hibernate
%e$elopers can still base their applications on the
Hibernate &/! and H:, *it;s not a 6/& application-
6
<hat can ou annotate=
Classes
Metadata which applies to the entire class *e4g4 table-
>ither fields or properties
Metadata which applies to a single field or propert
*e4g4 "apped colu"n-
%efines the access "ode *one default per class-. "ost
tpicall field. but not necessar
7ased on default. all fields or properties will be treated
as persistent *"appings will be defaulted-
Can be annotated with ?Transient *non(persistent-
!n Hibernate ou can o$erride the default access "ode
b using ?org4hibernate4annotations4&ccessTpe
7
Mapping si"ple properties
with annotations
@Entity
@Table(name= T_CUSTOMER)
public class Customer
@!"
@Column (name=cust_i")
pri#ate $on% i"&
@Column (name='irst_name)
@or%()ibernate(annotations(*ccessType (property)
pri#ate Strin% 'irst+ame&
public #oi" set,irst+ame(Strin% 'irst+ame)
t)is('irst+ame = 'irst+ame&
-
(((
@Entity
@Table(name= T_CUSTOMER)
public class Customer
@!"
@Column (name=cust_i")
pri#ate $on% i"&
@Column (name='irst_name)
@or%()ibernate(annotations(*ccessType (property)
pri#ate Strin% 'irst+ame&
public #oi" set,irst+ame(Strin% 'irst+ame)
t)is('irst+ame = 'irst+ame&
-
(((
"e'ines 'iel" as entity i". "e'ault access mo"e is /'iel"/
0property1 access uses setter
8
Mapping si"ple properties
with 2M,
public class Customer
pri#ate $on% i"&
pri#ate Strin% 'irst+ame&
public #oi" set,irst+ame(Strin% 'irst+ame)
t)is('irst+ame = 'irst+ame&
-
(((
2)ibernate3mappin% pac4a%e=or%(5y6(customer7
2class name=Customer table= T_CUSTOMER7
2i" name=i" column=cust_i" access='iel"87
2property name='irst+ame column='irst_name87
28class7
28)ibernate3mappin%7
0property1 access ("e'ault) uses setter
0'iel"1 access
9
Mapping collections with
annotations
@Entity
@Table(name= T_CUSTOMER)
public class Customer
@!"
@Column (name=cust_i")
pri#ate $on% i"&
@OneToMany(casca"e=Casca"eType(*$$)
@9oinColumn (name=cust_i")
pri#ate Set2*""ress7 a""resses&
:
@Entity
@Table(name= T_CUSTOMER)
public class Customer
@!"
@Column (name=cust_i")
pri#ate $on% i"&
@OneToMany(casca"e=Casca"eType(*$$)
@9oinColumn (name=cust_i")
pri#ate Set2*""ress7 a""resses&
:
;ropa%ate all operations to t)e un"erlyin%
ob<ects
10
Mapping collections with 2M,
public class Customer
pri#ate $on% i"&
pri#ate Set a""resses&
:
2class name=Customer table=T_CUSTOMER7
(((
2set name=a""resses casca"e=all access='iel"7
24ey column=CUST_!=87
2one3to3many class=*""ress87
28set7
28class7
11
Hibernate :uering
Hibernate pro$ides se$eral options for accessing
data
Retrie$e an object b pri"ar )e
:uer for objects with the Hibernate :uer ,anguage
*H:,-
:uer for objects using Criteria :ueries
>3ecute standard S:,
12
Hibernate :uering8 b
pri"ar )e
To retrie$e an object b its database identifier
si"pl call %et((() on the Session
This will first chec) the transactional cache
$on% cust!" = ne> $on%(?@A)&
Customer customer = (Customer) session(%et(Customer(class. cust!")&
returns null i' no ob<ect e5ists 'or t)e i"enti'ier
13
Hibernate :uering8 H:,
To 1uer for objects based on properties or
associations use H:,
Strin% city = C)ica%o&
Buery Cuery = session(createBuery(
'rom Customer c >)ere c(a""ress(city = Dcity)&
Cuery(setStrin%(city. city)&
$ist customers = Cuery(list()&
88 or i' e5pectin% a sin%le result
Customer customer = (Customer) Cuery(uniCueResult()&
14
Topics in this session
!ntroduction to Hibernate
Mapping
:uering
Con#iguring Hibernte Session$ctory
Spring's HibernateTe"plate
!"ple"enting #ati$e Hibernate %&Os
15
Configuring a SessionFactor
*+-
Hibernate i"ple"entations of data access code
re1uire access to the Session,actory
The Session,actory re1uires
E =ataSource *local or container("anaged-
Mapping "etadata
Spring pro$ides a ,actoryFean for configuring a
shareable Session,actory
16
Configuring a SessionFactor
*0-
Or"erSer#ice!mpl
Gibernate
Or"erRepository
Session,actory =ataSource
$ocalSession
,actoryFean
creates
Mappin%
Meta"ata
17
SessionFactor and
annotated classes
2bean i"=or"erRepository
class=e5ample(GibernateOr"erRepository7
<property name=sessionFactory re=sessionFactory!"
28bean7
2bean i"=session,actory
class=o(s(orm()ibernateA(annotation(*nnotationSession,actoryFean7
<property name=#ataSource re=#ataSource!"
2property name=annotate"Classes7
2list7
2#alue7e5ample(Customer28#alue7
2#alue7e5ample(*""ress28#alue7
28list7
28property7
28bean7
2<eeD<n"i3loo4up i"="ataSource <n"i3name=<a#aDcomp8en#8<"bc8or"ers87
Hil"car"s are not supporte" )ere
annotatedClasses attribute
>ntit classes should be listed one b one
18
SessionFactor and scanned
pac)ages
2bean i"=session,actory class=or%(sprin%'rame>or4(orm()ibernateA(
annotation(*nnotationSession,actoryFean7
<property name=#ataSource re=#ataSource!"
2property name=pac4a%esToScan7
2list7
2#alue7com8sprin%source8I8entity28#alue7
28list7
28property7
28bean7
2<eeD<n"i3loo4up i"="ataSource <n"i3name=<a#aDcomp8en#8<"bc8or"ers87
pac)agesToScan attribute
<ildcards are supported
&lso scans all subpac)ages
19
Configuring a SessionFactor
with 2M, "etadata
2bean i"=or"erSer#ice class=e5ample(Or"erSer#ice!mpl7
2constructor3ar% re'=or"erRepository87
28bean7
2bean i"=or"erRepository
class=e5ample(GibernateOr"erRepository7
2property name=session,actory re'=session,actory87
28bean7
2bean i"=session,actory
class=or%(sprin%'rame>or4(orm()ibernateA($ocalSession,actoryFean7
2property name="ataSource re'="ataSource87
2property name=mappin%$ocations7
2list7
2#alue7classpat)De5ample8Customer()bm(5ml28#alue7
2#alue7classpat)De5ample8*""ress()bm(5ml28#alue7
28list7
28property7
28bean7
2<eeD<n"i3loo4up i"="ataSource <n"i3name=<a#aDcomp8en#8<"bc8or"ers87
Hil"car"s are supporte"
20
Topics in this session
!ntroduction to Hibernate
Mapping
:uering
Configuring a Hibernate SessionFactor
Implementing %ti&e Hibernte '()s
Spring's HibernateTe"plate
21
!"ple"enting #ati$e Hibernate
%&Os *+-
For Hibernate @4+A
Hibernate pro$ides hoo)s so Spring can "anage
transactions and Sessions in a transparent fashion
9se &O/ for transparent e3ception translation to
Spring's %ata&ccess>3ception hierarch
!t is now possible to re"o$e an dependenc
on Spring in our %&O i"ple"entations
22
Spring("anaged Transactions
and Sessions *+-
To transparentl participate in Spring(dri$en
transactions. si"pl use one of Spring's
,actoryFeans for building the Session,actory
/ro$ide it to the data access code $ia
dependenc injection
&$oiding static access is a good thing anwa
%efine a transaction "anager
E GibernateTransactionMana%er
E 9taTransactionMana%er
23
Spring("anaged Transactions
and Sessions *0-
The code with no Spring dependencies
public class GibernateOr"erRepository implements Or"erRepository
pri#ate Session,actory session,actory&
public #oi" setSessionFactory(Session,actory session,actory)
t)is(session,actory = session,actory&
-
(((
public Or"er 'in"Fy!"(lon% or"er!")
88 use t)e Sprin%3mana%e" Session
Session session = t)is(session,actory(%etCurrentSession()&
return (Or"er) session(%et(Or"er(class. or"er!")&
-
-
24
Spring("anaged
Transactions *@-
The configuration
2beans7
2bean i"=session,actory
class=or%(sprin%'rame>or4(orm()ibernateA($ocalSession,actoryFean7
(((
28bean7
2bean i"=or"erRepository class=GibernateOr"erRepository7
<property name=sessionFactory re=sessionFactory!"
28bean7
2bean i"= transactionMana%er
class=or%(s'>4(orm()ibernateA(GibernateTransactionMana%er7
<property name=sessionFactory re=sessionFactory !"
28bean7
28beans7
coul" use 9taTransactionMana%er i' nee"e"
25
Spring("anaged
Transactions *B-
7est practice 8 use read(onl transactions when
ou don;t write anthing to the database
/re$ents Hibernate fro" flushing its session
possibl dra"atic perfor"ance i"pro$e"ent
&lso "ar)s 6%7C Connection as read(onl
pro$ides additional safeguards with so"e databases8
e4g4 Oracle will onl accept S>,>CT state"ents
2beans7
2bean i"=session,actory
class=or%(sprin%'rame>or4(orm()ibernateA($ocalSession,actoryFean7
(((
28bean7
2bean i"=or"erRepository class=GibernateOr"erRepository7
<property name=sessionFactory re=sessionFactory!"
28bean7
2bean i"= transactionMana%er
class=or%(s'>4(orm()ibernateA(GibernateTransactionMana%er7
<property name=sessionFactory re=sessionFactory !"
28bean7
28beans7
$%ransactional&rea#'nly=true(
public $ist2Re>ar"Con'irmation7 listRe>ar"s,rom(=ate ")
88 rea"3only. atomic unit3o'3>or4
-
$%ransactional&rea#'nly=true(
public $ist2Re>ar"Con'irmation7 listRe>ar"s,rom(=ate ")
88 rea"3only. atomic unit3o'3>or4
-
26
Transparent >3ception
Translation *+-
9sed as(is. the pre$ious %&O i"ple"entation
will throw nati$e. $endor(specific
)i*ernate+,ceptions
#ot desirable to let these propagate up to the ser$ice
laer or other users of the %&Os
!ntroduces dependenc on specific persistence solution
where it should not e3ist
&O/ allows translation to Spring's rich. $endor(
neutral -ata.ccess+,ception hierarch
27
Transparent >3ception
Translation *0-
Spring pro$ides this capabilit out of the bo3
6a$a CA
&nnotate with *+epository or our own custo"
annotation
%efine a Spring(pro$ided Fean;ost;rocessor
6a$a +4BA
9se pointcut "atching our own *base or "ar)er-
repositor interface to appl Spring(pro$ided
/ersistence+,ception%ranslation0nterceptor
28
Transparent >3ception Translation *@-8
6a$a CA >n$iron"ent
the code
the configuration
$1epository
public class GibernateOr"erRepository implements Or"erRepository
(((
-
2bean class=or%(sprin%'rame>or4("ao(annotation(
;ersistenceE5ceptionTranslation;ost;rocessor87
29
Transparent >3ception Translation *B-8
6a$a +4BA >n$iron"ent
the code
the configuration
public class GibernateOr"erRepository implements MyRepository
(((
-
2bean i"=persistenceE5ception!nterceptor
class=or%(sprin%'rame>or4("ao(support(
;ersistenceE5ceptionTranslation!nterceptor87
2aopDcon'i%7
2aopDa"#isor pointcut=e5ecution(I I((MyRepositoryJ(I((())
a"#ice3re'=persistenceE5ception!nterceptor 87
28aopDcon'i%7
30
Topics in this session
!ntroduction to Hibernate
Mapping
:uering
Configuring a Hibernate SessionFactor
!"ple"enting #ati$e Hibernate %&Os
Spring,s Hibernte-emplte
31
HibernateTe"plate
Consistent with Spring's general %&O support
Manages resources *ac1uiring/releasing Sessions-
Translates >3ceptions to the =ata*ccessE5ception
hierarch
/articipates in Spring("anaged transactions
auto"aticall
/ro$ides con$enience "ethods
Most prefer nati$e approach. instead of
HibernateTe"plate usage. for Hibernate @4+A
32
Configuring
HibernateTe"plate
Si"pl pro$ide a reference to the Session,actory
GibernateTemplate )ibernateTemplate =
ne2 GibernateTemplate(session,actory)&
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
,&7
9sing Hibernate with Spring
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Overview of Spring Web
Developing modern web applications
with Spring
2
Topics in this Session
Introduction
Using Spring in Web Applications
Overview of Spring Web
Spring and other Web frameworks
3
Web layer integration
SpringSource provides support in the Web layer
Spring !"#$ Spring Web%low&&&
'owever$ you are free to use Spring with any
(ava web framework
)ntegration might be provided by Spring or by the
other framework itself
4
JVM
Java EE Servlet Container
*ffective Web Application
Architecture
Application Layer
(Spring)
Web Layer
Local Java Business Interfaces
e!ote "##$ Interfaces
Clients
5
Topics in this Session
)ntroduction
Using Spring in eb !pplic"tions
Overview of Spring Web
Spring and other Web frameworks
6
Spring Application #onte+t
,ifecycle in Webapps
Spring can be initiali-ed within a webapp
start up business services$ repositories$ etc&
Uses a standard servlet listener
initiali-ation occurs before any servlets e+ecute
application ready for user re.uests
Application#onte+t&close/0 is called when the
application is stopped
7
#onfiguration in web&+ml
(ust add a Spring1provided servlet listener
%conte&t'para!(
%para!'na!e(conte&tConfigLocation%)para!'na!e(
%para!'value(
)WEB'I*+)!erc,ant'reporting'-ebapp'config.&!l
%)para!'value(
%)conte&t'para!(
%listener(
%listener'class(
org.springfra!e-or/.-eb.conte&t.Conte&tLoa0erListener
%)listener'class(
%)listener(
#,e application conte&t1s configuration file(s)
Loa0s t,e ApplicationConte&t into t,e ServletConte&t
before any Servlets are initiali2e0
8
Servlet #ontainer After
Starting Up
Servlet
Conte&t
JVM
Java EE Servlet Container
Application Layer
(Spring)
*o- accessible to
any Servlet or
ot,er
-eb'layer artifact
oot ApplicationConte&t
Boun0 in ServletConte&t
un0er a -ell'/no-n na!e
9
WebApplication#onte+tUtils
Static helper class
2rovides access to the Spring Application#onte+t
Spring retrieves the Application#onte+t from the
Servlet#onte+t
ServletConte&t servletConte&t 3 ...4
ApplicationConte&t conte&t 3 WebApplicationConte&t5tils.
getRequiredWebApplicationContext(servletConte&t)4

6nly necessary -,en 0epen0encies are not 0irectly in7ecte0 (eg. in a
Servlet)
10
WebApplication#onte+tUtils /30
public class #opSpen0erseport8enerator e&ten0s "ttpServlet 9
private ClientService clientService4
public voi0 init() 9
ApplicationConte&t conte&t 3 WebApplicationConte&t5tils.
getRequiredWebApplicationContext(getServletConte&t())4
clientService 3 (ClientService) conte&t.getBean(:clientService;)4
<
=
<
Saves t,e reference to t,e application entry'point for invocation
0uring re>uest ,an0ling
*+ample using a plain (ava servlet
11
Dependency in4ection
?Controller
public class #opSpen0erseportController 9
private Merc,anteportingService reportingService4
?Auto-ire0
public #opSpen0erseportController(Merc,anteportingService service) 9
t,is.reportingService 3 service4
<
=
<
?Controller
public class #opSpen0erseportController 9
private Merc,anteportingService reportingService4
?Auto-ire0
public #opSpen0erseportController(Merc,anteportingService service) 9
t,is.reportingService 3 service4
<
=
<
@epen0ency is auto!atically in7ecte0 by type
*+ample using Spring !"#
*o nee0 for WebApplicationContextUtils any!ore
12
Topics in this Session
)ntroduction
Using Spring in Web Applications
#$er$iew o% Spring eb
Spring and other Web frameworks
13
Spring Web
Spring !"#
Web framework bundled with Spring
Spring Web%low
2lugs into Spring !"#
)mplements navigation flows
Spring 5la-eDS )ntegration
)ntegration between Adobe %le+ clients and Spring
applications
14
Spring Web !"#
Spring6s web framework
Uses Spring for its own configuration
#ontrollers are Spring beans
testable artifacts
Annotation1based model since Spring 3&7
5uilds on the (ava Servlet A2)
A parallel 2ortlet version is also provided
The core platform for developing web
applications with Spring
All higher1level modules such as Web%low build on it
15
Spring Web %low
2lugs into Spring Web !"# as a #ontroller
technology for implementing stateful 8flows8
#hecks that users follow the right navigation path
!anages back button and multiple windows issues
2rovides scopes beyond re.uest and session
such as the conversation scope
Addresses the double1submit problem elegantly
16
*+ample %low Definition
%flo- ...(
%vie-'state i03"enterPassengerInfo"(
%transition on3"findItinerary to=revieItinerary" )(
%)vie-'state(
%vie-'state i03"revieItinerary"(
%transition on3"vie!eat" to3"c"oose!eat" )(
%transition on3"accept" to3"finis"" )(
%)vie-'state(
%vie-'state i03"c"oose!eat"(
%transition on3"find!eat" to3"finis"" )(
%)vie-'state(
%en0'state i03"finis"")(
%)flo-(
%lows are declared in 9ml
enterPassengerInfo
revieItinerary
c"oose!eat
finis"
findItinerary
accept
vie!eat
find!eat
17
!ore about Web%low
Online sample application is available here:
http:;;richweb&springframework&org;swf1booking1faces;spring;intro
Sample applications can be downloaded here:
http:;;www&springsource&org;webflow1samples
18
Spring %aces and Spring (S
Web%low also comes with a set of sub1pro4ects
Spring %aces
Allows to use Web%low with (S% on the view layer
2rovides enhancements to standard (S% facilities
scoped state management
Spring (avascript
<raceful degradation for clients without (avascript
2artial page rendering
#lient1side validation
A =esourceServlet for serving > caching static web resource
#,ere -ill be so!e i!portant c,anges on Spring JS an0 Spring +aces
in Web+lo- A.&. Stay tune0B
19
Topics in this Session
)ntroduction
Using Spring in Web Applications
Overview of Spring Web
Spring "nd other eb %r"mewor&s
20
Spring Struts ? integration
)ntegration provided by the Spring framework
)nherit from ActionSupport instead of Action
public class 5serAction extends ActionSupport 9
public Action+or-ar0 e&ecute(ActionMapping !appingC
Action+or! for!C...) throws E&ception 9

WebApplicationConte&t ct& 3 getWebApplicationConte&t()4
5serManager !gr 3 (5serManager) ct&.getBean(DuserManagerD)4
return !apping.fin0+or-ar0(DsuccessD)4
<
<
#,is is one of t,e E -ays to integrate Spring an0 Struts F toget,er. More
info in t,e reference 0ocu!entation
$rovi0e0 by t,e
Spring fra!e-or/
21
Spring (S% integration
Two options
Spring1centric integration
2rovided by Spring %aces
(S%1centric integration
Spring plugs in as as a (S% managed bean provider
%!anage0'bean(
%!anage0'bean'na!e(userList%)!anage0'bean'na!e(
%!anage0'bean'class(co!.springsource.-eb.ClientController%)!anage0'bean'class(
%!anage0'bean'scope(re>uest%)!anage0'bean'scope(
%!anage0'property(
%property'na!e(userManager%)property'na!e(
%value(G9userManager<%)value(
%)!anage0'property(
%)!anage0'bean(
JSF-centric integration
22
)ntegration provided by other
frameworks
Struts 3
provides a Spring plugin
http:;;struts&apache&org;3&@&A;docs;spring1plugin&html
Wicket
#omes with an integration to Spring
http:;;cwiki&apache&org;W)#B*T;spring&html
Tapestry 7
#omes with an integration to Spring
http:;;tapestry&apache&org;tapestry7;tapestry1spring;
23
Summary
Spring can be used with any web framework
Spring provides the #onte+t,oader,istener that can be
declared in web&+ml
Spring !"# is a lightweight web framework
where controllers are Spring beans
!ore about Spring !"# in the ne+t module
Web%low plugs into Spring !"# as a #ontroller
technology for implementing stateful 8flows8
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Spring Web MVC Essentials
Getting started with Spring Web MVC
2
Topics in this Session
Request rocessing !i"ecycle
Key Artifacts
ispatcherSer!let
"andlers
Views
#$ic% Start
3
Web &e'$est "andling
(!er!iew
Web re'$est handling is rather si)ple
*ased on an inco)ing +&,---
---we need to call a )ethod---
---after which the ret$rn !al$e .if any/---
---needs to be rendered $sing a !iew
4
&e'$est 0rocessing ,ifecycle
Dispatcher
Servlet
Handler
View
request (URL)
dispatch request
result
view
render
5
Topics in this Session
&e'$est 0rocessing ,ifecycle
#ey $rti"%cts
ispatcherSer!let
"andlers
Views
#$ic% Start
6
ispatcherSer!let1
The "eart of Spring Web MVC
A 2front controller3
coordinates all re'$est handling acti!ities
analogo$s to Str$ts ActionServlet / JSF FacesServlet
elegates to Web infrastr$ct$re beans
4n!o%es $ser Web co)ponents
5$lly c$sto)i6able
interfaces for all infrastr$ct$re beans
)any e7tension points
7
ispatcherSer!let
Config$ration
efined in web-7)l
+ses Spring for its config$ration
progra))ing to interfaces 8 dependency in9ection
easy to swap parts in and o$t
Creates separate 2ser!let3 application conte7t
config$ration is pri!ate to ispatcherSer!let
5$ll access to the parent 2root3 conte7t
instantiated !ia Conte7t,oader,istener
shared across ser!lets
8
Ser!let Container After
Starting +p
Root Application onte!t
DispatcherServlet Application
onte!t "e# La$er onte!t%
ontrollers& Views&
Resolvers& etc'
Application La$er
onte!t%
(usiness Services&
Repositories& etc'
parent
child
9
Topics in this Session
&e'$est 0rocessing ,ifecycle
Key Artifacts
ispatcherSer!let
&%ndlers
Views
#$ic% Start
10
Dispatcher
Servlet
Handler
)appin*
Handler
Adapter
getHandler(
HttpServletRequest)
handle(HttpServletRequest, HttpServletResponse ...)
Handler
&e'$est 0rocessing
11
Spring :MVC
Spring ;-< introd$ces a si)plified= annotation>
based )odel for de!eloping Spring MVC
applications
4nfor)ally referred to as 2Spring :MVC3
Earlier !ersions rely )ore hea!ily on ?M, for
config$ration
2Spring @MVCAB3
Controller class hierarchy deprecated in Spring C-D
This training will foc$s on Spring :MVC
12
Controllers as &e'$est
"andlers
+ontroller
public class ,!a-pleontroller .
+Request)appin*(//listAccounts'ht-/)
public Strin* list()odel -odel) .
'''
0
0
"andlers yo$ define are typically called
controllers and are $s$ally annotated by
:Controller
:&e'$estMapping tells Spring what )ethod to
e7ec$te when processing a partic$lar re'$est
Literall$& 1e!ecute this -ethod to
process requests 2or /listAccounts'ht-3
13
+&,>*ased Mapping &$les
Mapping r$les typically +&,>based= optionally
$sing wild cards1
Alogin
AeditAcco$nt
ArewardAEAEE
Mapping r$les in Spring ;-<81 defined $sing
annotations or ?M,1
:&e'$estMapping.2Alogin3/
Mapping r$les in Spring @ ;-<1 defined in ?M,
+sing the nor)al @beansAB config lang$age
14
"andler Method 0ara)eters
"andler )ethods will li%ely need conte7t abo$t
the c$rrent re'$est
Spring MVC will Ffill inF declared para)eters
allows for !ery fle7ible )ethod signat$res
+ontroller
pu#lic class ,!a-pleontroller .
+Request)appin*(//listAccounts/)
pu#lic Strin* list()odel -odel) .
'''
0
0
15
E7tracting &e'$est
0ara)eters
+se :&e'$est0ara) annotation
E7tracts para)eter fro) the re'$est
0erfor)s type con!ersion
+ontroller
pu#lic class ,!a-pleontroller .
+Request)appin*(//listAccounts/)
pu#lic Strin* show(+Request4ara-(/entit$5d/) lon* id) .
'''
0
0
See JavaDoc o2 +Request)appin*
2or all possi#le ar*u-ent t$pes
16
+&4 Te)plates
Val$es can also be e7tracted fro) re'$est +&,s
since Spring C-D
+sing so>called URI Templates
not Spring>specific concept= $sed in )any fra)ewor%s
+se .60 placeholders and +4athVaria#le
Allows clean +&,s witho$t re'$est para)eters
+ontroller
pu#lic class ,!a-pleontroller .
+Request)appin*(//accounts/.account5d0/)
pu#lic Strin* show(+4athVaria#le(/account5d/) lon* id) .
'''
0
0
17
E7a)ple Controllers
An Acco$ntController
creates= shows= $pdates= and deletes Acco$nts
A ,oginController
logs $sers in
A Top0erfor)ingAcco$ntsController
generates an E7cel spreadsheet with top ;D acco$nts
18
Topics in this Session
&e'$est 0rocessing ,ifecycle
Key Artifacts
ispatcherSer!let
"andlers
'iews
#$ic% Start
19
Selecting a View
Controllers typically ret$rn a !iew na)e
*y defa$lt !iew na)e is interpreted as path to GS0
page
Controllers )ay ret$rn n$ll .or !oid/
ispatcherSer!let then selects a defa$lt !iew based on the
re'$est +&,
Controllers )ay also ret$rn a concrete View
new GstlView.2AWE*>4H5ArewardAlist-9sp3/
new &eward,isting0df./
7ot ver$ co--on8
20
View &esol!ers
The ispatcherSer!let delegates to a
View&esol!er to )ap ret$rned !iew na)es to
View i)ple)entations
The defa$lt View&esol!er treats the !iew na)e
as a Web Application>relati!e file path
(!erride this defa$lt by registering a
View&esol!er bean with the ispatcherSer!let
4nternal reso$rce .defa$lt/
*ean na)e
21
C$sto) 4nternal &eso$rce
View &esol!er E7a)ple
Rewardontroller
handle 9,:
/reward/list
rewardList
-odel;.rewards0
DispatcherServlet
usto-
5nternalResource
ViewResolver
rewardList
/",(<57F/views/rewardList'=sp
>
?
Lo*ical view na-e
Resolved ph$sical path
@#ean class;1or*'sprin*2ra-eworA'we#'servlet'view'
5nternalResourceViewResolver3B
@propert$ na-e;1pre2i!3 value;1/",(<57F/views/3 /B
@propert$ na-e;1su22i!3 value;1'=sp3 /B
@/#eanB
22
Topics in this Session
&e'$est 0rocessing ,ifecycle
Key Artifacts
ispatcherSer!let
"andlers
Views
(uic) St%rt
23
#$ic% Start
Steps to de!eloping a Spring MVC application
I- eploy a ispatcher Ser!let .one>ti)e only/
;- 4)ple)ent a re'$est handler .controller/
C- 4)ple)ent the View.s/
J- &egister the Controller with the ispatcherSer!let
<- eploy and test
&epeat steps ;>< to de!elop new f$nctionality
24
I-a eploy ispatcherSer!let
efine inside @webappB within web-7)l
@servletB
@servlet<na-eBrewardsad-in@/servlet<na-eB
@servlet<classB
or*'sprin*2ra-eworA'we#'servlet'DispatcherServlet
@/servlet<classB
@init<para-B
@para-<na-eBconte!ton2i*Location@/para-<na-eB
@para-<valueB
/",(<57F/-vc<con2i*'!-l
@/para-<valueB
@/init<para-B
@/servletB
ontains the ServletCs con2i*uration
25
I-b eploy ispatcher Ser!let
Map the Ser!let to a +&, pattern
Will now be able to in!o%e the Ser!let li%e
@servlet<-appin*B
@servlet<na-eBrewardsad-in@/servlet<na-eB
@url<patternB/rewardsad-in/D@/url<patternB
@/servlet<-appin*B
http%//localhost%EFEF/rewardsad-in/reward/list
http%//localhost%EFEF/rewardsad-in/reward/new
http%//localhost%EFEF/rewardsad-in/reward/showGid;>
26
4nitial ispatcherSer!let
Config$ration
@#eansB
@#ean class;1or*'sprin*2ra-eworA'we#'''5nternalResourceViewResolver3B
@propert$ na-e;1pre2i!3 value;1/",(<57F/views/3 /B
@propert$ na-e;1su22i!3 value;1'=sp3 /B
@/#eanB
@/#eansB
/",(<57F/-vc<con2i*'!-l
27
+ontroller
public class Rewardontroller .
private RewardLooAupService looAupServiceH
public Rewardontroller(RewardLooAupService svc) .
this'looAupService ; svcH
0

+Request)appin*(//reward/show/)
public Strin* show(+Request4ara-(/id/) long id& )odel -odel) .
Reward reward ; looAupService'looAupReward(id)H
-odel'addAttri#ute(1reward3& reward)H
return 1rewardView3H
0
0
;- 4)ple)ent the Controller
Selects the 1rewardView3 to
to render the reward
Depends on
application service
Auto-aticall$ 2illed
in #$ Sprin*
28
C- 4)ple)ent the View
@ht-lB
@headB@titleBIour Reward@/titleB@/headB
@#od$B
A-ount;J.reward'a-ount0
Date;J.reward'date0
Account 7u-#er;J.reward'account0
)erchant 7u-#er;J.reward'-erchant0
@/#od$B
@/ht-lB
/",(<57F/views/rewardView'=sp
Re2erences result -odel o#=ect #$ na-e
29
J- &egister the Controller
@#ean id;1rewardontroller3 class;1rewardsad-in'Rewardontroller3B
@constructor<ar* re2;1rewardLooAupService3 /B
@/#eanB
/",(<57F/-vc<con2i*'!-l
30
<- eploy and Test
http%//localhost%EFEF/rewardsad-in/reward/showGid;>
Iour Reward
A-ount ; J>FF'FF
Date ; ?FFK/>?/?L
Account 7u-#er ; >?MNOKPEL
)erchant 7u-#er ; >?MNOKPELF
31
(ptionally1
Enable Co)ponent Scanning
@conte!t%co-ponent<scan #ase<pacAa*e;1rewardsad-in3/B
Sprin* )V ontrollers can #e auto<detected
+ontroller
public class Rewardontroller .
private RewardLooAupService looAupServiceH
+Autowired
public Rewardontroller(RewardLooAupService svc) .
this'looAupService ; svcH
0

+Request)appin*(//reward/show/)
public Strin* show(long id& )odel -odel) . ''' 0
0
32
MVC Additions in Spring C-D
:MVC )odel is enabled by defa$lt
Appropriate "andlerMapping and KAdapter registered
witho$t any additional config$ration
"owe!er= Spring C-D introd$ces new feat$res not
enabled by defa$lt
Stateless con!erter fra)ewor% for binding and
for)atting
S$pport for GS&>CDC declarati!e !alidation
"ttpMessageCon!erters .for &ESTf$l web ser!ices/
"ow do yo$ $se these feat$resL
33
MVC Ha)espace
+se new MVC na)espace to easily enable these1
@#eans !-lns;/http%//www'sprin*2ra-eworA'or*/sche-a/#eans/
!-lns%!si;/http%//www'wM'or*/?FF>/Q)LSche-a<instance/
!-lns%-vc;/http%//www'sprin*2ra-eworA'or*/sche-a/-vc/
!si%sche-aLocation;/'''/B
@8<< provides de2ault conversion service& validator and
Http)essa*eonverters <<B
<mvc:annotation-riven!"
&egisters "andlerMapping and KAdapter for :MVC
Means yo$ lose the other defa$lt )appings and adaptersM
Allows c$sto) con!ersion ser!ice and !alidator
and defining "andler4nterceptors applicable to all
"andlerMappings or specific +&4 paths
Goes beyond the scope of this co$rse
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
,A*
Spring Web MVC Essentials
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Practical REST services
with Spring MVC
Using Spring MVC to build RESTful web
services
2
Topics in this Session
RES introduction
REST and Java
Spring MVC support for RESTful applications
Re!uest"Response Processing
Using MessageConverters
Content #egotiation
Putting it all together
RESTful clients with the RestTe$plate
Conclusion
3
REST %ntroduction
&eb apps not 'ust usable b( browser clients
Progra$$atic clients can also connect via )TTP
REST is an architectural st(le that describes best
practices to e*pose web services over )TTP
REpresentational State Transfer+ ter$ b( Ro( ,ielding
)TTP as application protocol+ not 'ust transport
E$phasi-es scalabilit(
4
REST Principles ./0
E*pose resources through UR%s
Model nouns+ not verbs
Resources support li$ited set of operations
1ET+ PUT+ P2ST+ 3E4ETE in case of )TTP
5ll have well6defined se$antics

to update an e*isting order+ PUT to /orders/123+


don7t P2ST to /order/edit?id=123
5
REST Principles .80
Clients can re!uest particular representation
Resources can support $ultiple representations
)TM4+ 9M4+ JS2#+ :
Representations can lin; to other resources
5llows for e*tensions and discover(+ li;e with web sites
4ooser coupling between client and server
Ma;es clients ;eep trac; of state
M%ME t(pes contract for interacting with a resource
6
REST Principles .<0
Stateless architecture
#o )ttpSession usage
1ETs can be cached on UR4
Part of what $a;es it scalable
)TTP headers and status codes co$$unicate
result to clients
5ll well6defined in )TTP Specification
7
REST Clients
2ne benefit of REST= ever( platfor$"language
supports )TTP
Unli;e for e*a$ple S25P > &S6? specs
Eas( to support $an( different clients
8
Topics in this Session
REST introduction
RES !nd "!#!
Spring MVC support for RESTful applications
Re!uest"Response Processing
Using MessageConverters
Content #egotiation
Putting it all together
RESTful clients with the RestTe$plate
Conclusion
9
REST and Java= J596RS
J596RS is a Java EE @ standard for building
RESTful applications
,ocuses on progra$$atic clients+ not browsers
Various i$ple$entations
Jerse( .R%0+ RESTEas(+ Restlet+ C9,
5ll i$ple$entations provide Spring support
1ood option for full REST support using a
standard
#o support for building clients in standard
5lthough so$e i$ple$entations do offer it
10
REST and Java= Spring6MVC
Spring6MVC provides REST support as well
Since version <AB
Using fa$iliar and consistent progra$$ing $odel
Spring MVC does not i$ple$ent J596RS
2ffers both progra$$atic client support .)TTP6
based web services0 and browser support
.RESTful web applications0
%ncludes RestTe$plate for building progra$$atic
clients in Java
11
Topics in this Session
REST introduction
REST and Java
Spring $%C support &or RES&ul !pplic!tions
Re!uest"Response Processing
Using MessageConverters
Content #egotiation
Putting it all together
RESTful clients with the RestTe$plate
Conclusion
12
Spring6MVC REST Support
So$e features have been covered alread(
UR% te$plates to parse 7RESTful7 UR4s
Views for $ultiple resource representations
5ppl( to all web clients+ inclA browsers
This $odule covers additional features for
building web services for progra$$atic clients
Support for RESTful web applications targeting
browser6based clients is also offered
but is outside of this course7s scope
13
Topics in this Session
REST introduction
REST and Java
Spring MVC support for RESTful applications
Re'uest(Response )rocessing
Using MessageConverters
Content #egotiation
Putting it all together
RESTful clients with the RestTe$plate
Conclusion
14
Re!uest $apping based on
)TTP $ethod
Can $ap )TTP re!uests based on $ethod
5llows sa$e UR4 to be $apped to $ultiple $ethods
2ften used for for$6based controllers .1ET C P2ST0
Essential to support RESTful resource UR4s
inclA PUT and 3E4ETE
@RequestMapping(value="/orders", method=RequestMethod.POST)
public void createOrder(ttp!ervletRequest request, Model "odel) #
// process t$e order data %ro" t$e request
&
@RequestMapping(value="/orders", method=RequestMethod.GET)
public void listOrders(Model "odel) #
// %ind all Orders and add t$e" to t$e "odel
&
15
)TTP Status Code Support
&eb apps 'ust use a handful of status codes
8BB 2D+ EBE #ot ,ound+ <B8"<B< for redirects and FBB
%nternal Server Error for unhandled E*ceptions
RESTful applications use $an( additional codes to
co$$unicate with their clients
Use @Response!tatus on controller $ethod so (ou
don7t have to set this on ttp!ervletResponse
(ourself
16
Co$$on Response Codes
So$e co$$on )TTP response codes=
8BB= after a successful 1ET where content is returned
8B/= when new resource was created on P2ST or PUT
4ocation header should contain UR% of new resource
8BE= when the response is e$pt(
eAgA after successful update with PUT or 3E4ETE
EBE= when re!uested resource was not found
EBF= when )TTP $ethod is not supported b( resource
EBG= when a conflict occurs while $a;ing changes
eAgA when P2STing uni!ue data that alread( e*ists
FBB= internal server error
17
HResponseStatus
&hen using HResponseStatus+ void $ethods no
longer i$pl( a default view na$eI
There will be no View at all
E*a$ple gives a response with an e$pt( bod(
@RequestMapping(value="/orders", "et$od=RequestMet$od'POST)
@Responset!tus"#ttpt!tus.CREATED$ && 201
public void createOrder(ttp!ervletRequest request,
ttp!ervletResponse response) #
Order order = createOrder(request)(
// deter"ine %ull )R* %or ne+l, created Order -ased on request
response'addeader(".ocation",
get.ocation/or0$ildResource(request, order'get*d()))(
&
18
3eter$ining 4ocation )eader
4ocation header value $ust be full UR4
3eter$ine based on re!uest UR4
Controller shouldn7t ;now host na$e or servlet path
UR4 of created child resource usuall( a sub6path
P2ST to $ttp1//+++'",s$op'co"/store/orders
gives $ttp1//+++'",s$op'co"/store/orders/123
0an use !pring2s )ri3e"plate %or encoding +$ere needed
p'iv!te !tring get.ocation/or0$ildResource(ttp!ervletRequest request,
O-4ect c$ild*denti%ier) #
!tring5u%%er url = request'getRequest)R.()(
)ri3e"plate te"plate = ne( )ri3e"plate(url'append("/#c$ild*d&")'to!tring())(
'etu'n te"plate'e6pand(c$ild*denti%ier)'to7!0**!tring()(
&
19
HResponseStatus C E*ceptions
Can also annotate e*ception classes with this
1iven status code used when e*ception is thrown fro$
controller $ethod
@Responset!tus"#ttpt!tus.NOT_FOUND$ && 404
public cl!ss Order8ot/ound96ception e)tends Runti"e96ception #
:
&
@RequestMapping(value="/orders/#id&", "et$od=GET)
public !tring s$o+Order(@;at$<aria-le("id") lon* id, Model "odel) #
Order order = orderRepositor,'%indOrder5,*d(id)(
i+ (order == null) th'o( ne( Order8ot/ound96ception(id)(
"odel'add7ttri-ute(order)(
return "order=etail"(
&
20
HE*ception)andler
,or e*isting e*ceptions (ou cannot annotate+ use
HE*ception)andler $ethod in controller
Method signature si$ilar to re!uest handling
$ethod
5lso supports HResponseStatus
@Response!tatus(ttp!tatus'CONFLICT) // >?@
@96ceptionandler(#=ata*ntegrit,<iolation96ception'cl!ss&)
public void con%lict() #
// could add t$e e6ception, response, etc' as "et$od para"s
&
21
Topics in this Session
REST introduction
REST and Java
Spring MVC support for RESTful applications
Re!uest"Response Processing
*sing $ess!geCon#erters
Content #egotiation
Putting it all together
RESTful clients with the RestTe$plate
Conclusion
22
)ttpMessageConverter
Converts between )TTP re!uest"response and ob'ect
Various i$ple$entations registered b( default when
using A"vc1annotationBdriven/C
9M4 .using J59P Source or J59J8 $apped ob'ect?0
,eed data?+ iAeA 5to$"RSS
,or$6based data
JS2#?
J(teKL+ String+ Juffered%$age
3efine )andler5dapter e*plicitl( to register other
)ttpMessageConverters
D1 requires 3
rd
part, li-raries on t$e classpat$
23
&h( Use )ttpMessageConverters
.%nput0
&eb service applications often process re!uest
content differentl( than regular web applications
#ot 'ust binding re!uest para$eters
eAgA a PUT or P2ST containing 9M4 or JS2# docu$ent
Still preferable to not process )ttpServletRe!uest
directl( in controller
#eed so$ething else to $ap re!uest to $ethod
para$eter
24
&h( Use )ttpMessageConverters
.2utput0
&riting to response often different fro$ web
application as well
Controller $ethods $ight not want to use separate
View to render result
nor write representation to )ttpServletResponse
directl(
#eed so$ething else to $ap return value to response
25
HRe!uestJod(
Use converters for re!uest data b( annotating
$ethod para$eter with @Request5od,
@RequestMapping(value="/orders/#id&", "et$od=RequestMet$od'PUT)
@Response!tatus(ttp!tatus'NO_CONTENT) // 2?>
public void updateOrder(@Request,od- .'de' upd!ted.'de',
@;at$<aria-le("id") lon* id) #
// process updated order data and return e"pt, response
orderManager'updateOrder(id, updatedOrder)(
&
Right converter chosen auto$aticall(
Jased on content t(pe of re!uest
2rder could be $apped fro$ 9M4 with J59J8 or fro$
JS2# with Jac;son+ for e*a$ple
26
HResponseJod(
Use converters for response data b( annotating
$ethod with @Response5od,
@RequestMapping(value="/orders/#id&", "et$od=RequestMet$od'GET)
@Response!tatus(ttp!tatus'OK) // 2??
public @Response,od- .'de' getOrder(@;at$<aria-le("id") long id) #
// Order class is annotated +it$ E7F522s @F"lRoot9le"ent
Order order= orderRepositor,'%indOrder5,*d(id)(
// results in FM. response containing "ars$alled order1
'etu'n order(
&
Converter handles rendering to response
#o ViewResolver and View involved an($oreI
27
Topics in this Session
REST introduction
REST and Java
Spring MVC support for RESTful applications
Re!uest"Response Processing
Using MessageConverters
Content +egoti!tion
Putting it all together
RESTful clients with the RestTe$plate
Conclusion
28
Content #egotiation
)TTP clients can re!uest a particular resource
representation through $edia " M%ME t(pes
Using 5ccept header in )TTP Re!uest

7ccept1 te6t/$t"l,application/6$t"lG6"l,application/6"l(q=?'@,D/D(q=?'H
Jest available representation will be returned
Java ob'ect bac;ing resource t(picall( the sa$e
Single $odel+ onl( representation change
29
Content #egotiation C
HResponseJod(
HResponseJod( $ethod returns 'ust the $odel
)ow to choose correct )ttpMessageConverter for
re!uested representationM
#ot controller7s responsibilit(
#o ViewResolver involved either
Remember to use <mvc:annotation-driven! or to register custom
converters to have HttpMessageConverters defined at all!
30
5uto$atic Content
#egotiation
)ttpMessageConverter selected auto$aticall( for
HResponseJod(6annotated $ethods
Jased on 5ccept header in re!uest
Each converter has list of supported $edia t(pes
5llows $ultiple representations for a single
controller $ethod
&ithout affecting controller i$ple$entation
5lternative for content6based View selection as used
without HResponseJod(
31
Content #egotiation Sa$ple
@RequestMapping(value="/orders/#id&", "et$od=RequestMet$od'GET)
@Response!tatus(ttp!tatus'OK) // 2??
public @Response,od- .'de' getOrder(@;at$<aria-le("id") long id) #
'etu'n orderRepositor,'%indOrder5,*d(id)(
&
33;/1'1 2?? OI
=ate1 :
0ontentB.engt$1 1>JK
/ontent01-pe2 !pplic!tion&)ml
Aorder id=L123LC
:
A/orderC
M93 /store/orders/123
ost1 +++'",s$op'co"
3ccept2 !pplic!tion&)ml, '''
:
33;/1'1 2?? OI
=ate1 :
0ontentB.engt$1 NJK
/ontent01-pe2 !pplic!tion&4son
#
"order"1 #"id"1 123, "ite"s"1 O : P, : &
&
M93 /store/orders/123
ost1 +++'",s$op'co"
3ccept2 !pplic!tion&4son, '''
:
32
Topics in this Session
REST introduction
REST and Java
Spring MVC support for RESTful applications
Re!uest"Response Processing
Using MessageConverters
Content #egotiation
)utting it !ll together
RESTful clients with the RestTe$plate
Conclusion
33
Retrieving a Representation=
1ET
M93 /store/orders/123
ost1 +++'",s$op'co"
7ccept1 application/6"l, '''
:
@RequestMapping(value="/orders/#id&", "et$od=RequestMet$od'GET)
@Response!tatus(ttp!tatus'OK) // 2??1 t$is is t$e de%ault
public @Response,od- .'de' getOrder(@;at$<aria-le("id") long id) #
'etu'n orderRepositor,'%indOrder5,*d(id)(
&
33;/1'1 2?? OI
=ate1 :
0ontentB.engt$1 1>JK
0ontentB3,pe1 application/6"l
Aorder id=L123LC
:
A/orderC
34
Creating a new Resource=
P2ST
;O!3 /store/orders/123/ite"s
ost1 +++'",s$op'co"
0ontentB3,pe1 application/6"l
Aite"C
:
A/ite"C
@RequestMapping(value="/orders/#id&/ite"s", "et$od=RequestMet$od'POST)
@Response!tatus(ttp!tatus'CRE"TE#) // 2?1
public void create*te"(@;at$<aria-le("id") long id,
@Request5od, *te" ne+*te",
ttp!ervletRequest request,
ttp!ervletResponse response) #
orderRepositor,'%indOrder5,*d(id)'add*te"(ne+*te")( // adds id to *te"
response'addeader(".ocation",
get.ocation/or0$ildResource(request, ne+*te"'get*d()))(
&
33;/1'1 2?1 0reated
=ate1 :
0ontentB.engt$1 ?
.ocation1
$ttp1//+++'",s$op'co"/store/orders/123/ite"s/a-c
35
Updating e*isting Resource=
PUT
;)3 /store/orders/123/ite"s/a-c
ost1 +++'",s$op'co"
0ontentB3,pe1 application/6"l
Aite"C
:
A/ite"C
@RequestMapping(value="/orders/#order*d&/ite"s/#ite"*d&",
"et$od=RequestMet$od'PUT)
@Response!tatus(ttp!tatus'NO_CONTENT) // 2?>
public void update*te"(@;at$<aria-le("order*d") long order*d,
@;at$<aria-le("ite"*d") !tring ite"*d
@Request5od, *te" ite") #
orderRepositor,'%indOrder5,*d(order*d)'update*te"(ite"*d, ite")(
&
33;/1'1 2?> 8o 0ontent
=ate1 :
0ontentB.engt$1 ?
36
3eleting a Resource=
3E4ETE
=9.939 /store/orders/123/ite"s/a-c
ost1 +++'",s$op'co"
'''
@RequestMapping(value="/orders/#order*d&/ite"s/#ite"*d&",
"et$od=RequestMet$od'#ELETE)
@Response!tatus(ttp!tatus'NO_CONTENT) // 2?>
public void delete*te"(@;at$<aria-le("order*d") long order*d,
@;at$<aria-le("ite"*d") !tring ite"*d) #
orderRepositor,'%indOrder5,*d(order*d)'delete*te"(ite"*d)(
&
33;/1'1 2?> 8o 0ontent
=ate1 :
0ontentB.engt$1 ?
37
Topics in this Session
REST introduction
REST and Java
Spring MVC support for RESTful applications
Re!uest"Response Processing
Using MessageConverters
Content #egotiation
Putting it all together
RES&ul clients with the Restempl!te
Conclusion
38
Provides access to RESTful services
Supports UR% te$plates+ )ttpMessageConverters
and custo$ e*ecute.0 with callbac;s
Map or !tring''' for vars+ 4ava'net')R* or !tring for UR4
RestTe$plate %ntroduction
#115 Method Rest1empl!te Method
=9.939 delete(!tring url, !tring: url<aria-les)
M93 get/orO-4ect(!tring url, 0lassA3C response3,pe, !tring: url<aria-les)
97= $ead/oreaders(!tring url, !tring: url<aria-les)
O;3*O8! options/or7llo+(!tring url, !tring: url<aria-les)
;O!3 post/or.ocation(!tring url, O-4ect request, !tring: url<aria-les)
post/orO-4ect(!tring url, O-4ect request, 0lassA3C response3,pe,
!tring: uri<aria-les)
;)3 put(!tring url, O-4ect request, !tring:url<aria-les)
39
3efining a RestTe$plate
Just call constructor in (our code
Rest3e"plate te"plate = ne( Rest3e"plate()(
)as default )ttpMessageConverters
Sa$e as on the server+ depending on classpath
2r use e*ternal configuration
To use 5pache Co$$ons )TTP Client+ for e*a$ple
A-ean id="4sonRest3e"plate" class="org's%+'+e-'client'Rest3e"plate"C
Apropert, na"e="request/actor,"C
A-ean class="org's%+'$ttp'client'0o""ons0lientttpRequest/actor,"/C
A/propert,C
A/-eanC
40
RestTe$plate Usage E*a$ples
Rest3e"plate te"plate = ne( Rest3e"plate()(
!tring uri = "$ttp1//e6a"ple'co"/store/orders/#id&/ite"s"(
// M93 all order ite"s %or an e6isting order +it$ *= 11
Order*te"OP ite"s = te"plate'get/orO-4ect(uri, Order*te"OP'cl!ss, "1")(
// ;O!3 to create a ne+ ite"
Order*te" ite" = // create ite" o-4ect
)R* ite".ocation = te"plate'post/or.ocation(uri, ite", "1")(
// ;)3 to update t$e ite"
ite"'set7"ount(2)(
te"plate'put(ite".ocation, ite")(
// =9.939 to re"ove t$at ite" again
te"plate'delete(ite".ocation)(
S$rin% &'(') introd*ce+ ,tt$Entit-. /0ic0 ma1e+ addin% 0eader+ to t0e
,TTP re2*e+t ver- ea+- a+ /e33
41
Topics in this Session
REST introduction
REST and Java
Spring MVC support for RESTful applications
Re!uest"Response Processing
Using MessageConverters
Content #egotiation
Putting it all together
RESTful clients with the RestTe$plate
Conclusion
42
Conclusion
REST is an architectural st(le that can be applied
to )TTP6based applications
Useful for supporting diverse clients and building
highl( scalable s(ste$s
Java provides J596RS as standard specification
Spring6MVC adds REST support using a fa$iliar
progra$$ing $odel
E*tended b( HRe!uest6"HResponseJod(
Use RestTe$plate for accessing RESTful apps
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
45J
RESTful applications with Spring MVC
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Web Application Security with
Spring
Addressing Common Web Application
Security Requirements
2
Topics in this Session
High-Leel Security !eriew
Motivations of Spring Security
Spring Security in a Web nvironment
Configuring Web Authentication
!sing Spring Security"s Tag #ibraries
Method security
Advanced security$ wor%ing with filters
3
Security Concepts
&rincipal
' !ser( device or system that performs an action
Authentication
' stablishing that a principal)s credentials are valid
Authori*ation
' +eciding if a principal is allowed to perform an action
Secured item
' Resource that is being secured
4
Authentication
There are many authentication mechanisms
' e,g, basic( digest( form( -,./0
There are many storage options for credential
and authority information
' e,g, +atabase( #+A&( in1memory 2development3
5
Authori*ation
Authori*ation depends on authentication
' 4efore deciding if a user can perform an action( user
identity must be established
The decision process is often based on roles
' A+M56 can cancel orders
' MM4R can place orders
' 7!ST can browse the catalog
6
Topics in this Session
8igh1#evel Security 9verview
"oti#tions o$ Spring Security
Spring Security in a Web nvironment
Configuring Web Authentication
!sing Spring Security"s Tag #ibraries
Method security
Advanced security$ wor%ing with filters
7
Motivations$ &ortability
Servlet1Spec security is not portable
' Requires container specific adapters and role
mappings
Spring Security is portable across containers
' Secured archive 2e,g, WAR3 can be deployed as1is
' Also runs in standalone environments
8
Motivations$ :le;ibility
Supports all common authentication
mechanisms
' 4asic( :orm( -,./0( Coo%ies( Single1Sign19n( etc,
&rovides configurable storage options for user
details 2credentials and authorities3
' R+4MS( #+A&( &roperties file( custom +A9s( etc,
!ses Spring for configuration
9
Motivations$ ;tensibility
Security requirements often require
customi*ation
With Spring Security( all of the following are
e;tensible
' 8ow a principal is defined
' Where authentication information is stored
' 8ow authori*ation decisions are made
' Where security constraints are stored
10
Motivations$ Separation of
Concerns
4usiness logic is decoupled from security
concerns
' #everages Servlet :ilters and Spring A9& for an
interceptor1based approach
Authentication and Authori*ation are decoupled
' Changes to the authentication process have no
impact on authori*ation
11
Motivations$ Consistency
The goal of authentication is always the same
regardless of the mechanism
' stablish a security conte;t with the authenticated
principal)s information
The process of authori*ation is always the same
regardless of resource type
' Consult the attributes of the secured resource
' 9btain principal information from security conte;t
' 7rant or deny access
12
Spring Security$ the 4ig
&icture
Security Context
Authentication
(Principal + Authorities)
Secured
Resource
Authentication
Manager
populates
thread of
execution
obtains
AccessDecision
Manager
delegates
Config
Attributes
describes
consults protects
Security Interceptor
oters
polls
13
Topics in this Session
8igh1#evel Security 9verview
Motivations of Spring Security
Spring Security in # %eb &nironment
Configuring Web Authentication
!sing Spring Security"s Tag #ibraries
Method security
Advanced security$ wor%ing with filters
14
Configuration in the
Application Context
Spring configuration
!sing Spring Security"s <Security< namespace
!beans """#
!security$http#

!security$intercept%url pattern&'(accounts())'
access&'IS*A+,-./,ICA,.D*0+112' (#
!security$for3%login login%page&'(login"ht3'(#

!security$logout (#
!(security$http#
!(beans#
Match all +R1s starting 4ith
(accounts( (A/,%style path)
15
Configuration in 4eb"x3l
+efine the single pro;y filter
' springSecurity:ilterChain is a mandatory name
' 5t refers to an e;isting Spring bean with the same
name
!filter#
!filter%na3e#springSecurity0ilterChain!(filter%na3e#
!filter%class#
org"springfra3e4or5"4eb"filter"Delegating0ilterProxy
!(filter%class#
!(filter#
!filter%3apping#
!filter%na3e#springSecurity0ilterChain!(filter%na3e#
!url%pattern#()!(url%pattern#
!(filter%3apping#
16
intercept1url
intercept1urls are evaluated in the order listed
' The first match will be used
' specific matches should be put on top
!security$intercept%url pattern&'(accounts(login"ht3' filters&'none' (#

!security$intercept%url pattern&'(accounts(edit)'
access&'R61.*+S.R7 R61.*ADMI/' (#

!security$intercept%url pattern&'(accounts(account)' access&'R61.*+S.R' (#

!security$intercept%url pattern&'(accounts())'
access&'IS*A+,-./,ICA,.D*0+112' (#
17
Topics in this Session
8igh1#evel Security 9verview
Motivations of Spring Security
Spring Security in a Web nvironment
Con$iguring %eb 'uthentic#tion
!sing Spring Security"s Tag #ibraries
Method security
Advanced security$ wor%ing with filters
18
An ;ample #ogin &age
!for3 action&8!c$url 9alue&:;*spring*security*chec5:(#< 3ethod&8P6S,<#
!input type&8text< na3e&8;*userna3e<(#
!br(#
!input type&8pass4ord< na3e&8;*pass4ord<(#
!br(#
!input type&8sub3it< na3e&8sub3it< 9alue&816=I/<(#
!(for3#
,he expected 5eys
for generation of
an authentication
re>uest to5en
+R1 that indicates an
authentication re>uest
19
Configure Authentication
+A9 Authentication provider is default
&lug1in specific !ser+etailsService
implementation to provide credentials and
authorities
' 4uilt1in$ =+4C( in1memory
' Custom
!security$authentication%3anager#
!security$authentication%pro9ider#
"""
!(security$authentication%pro9ider#
!security$authentication%3anager#
20
The 5n1Memory user ser9ice (?(@)
!seful for development and testing
' Without encoding
' With encoding
!security$authentication%3anager#
!security$authentication%pro9ider#
!security:user-service properties&'(A.B%I/0(users"properties' (#
!(security$authentication%pro9ider#
!security$authentication%3anager#
!security$authentication%3anager#
!security$authentication%pro9ider#
!security:password-encoder hash&'3dC' (#
!security:user-service properties&'(A.B%I/0(users"properties' (#
!(security$authentication%pro9ider#
!security$authentication%3anager#
admin=secret,ROLE_ADMIN
testuser1=pass,ROLE_MEMBER
21
The 5n1Memory +serDetailsSer9ice
(@(@)
The properties file
admin=secret,ROLE_ADMIN,ROLE_MEMBER
testuser1=pass,ROLE_MEMBER
testuser2=pass,ROLE_MEMBER
guest=guest,ROLE_GUEST,ROLE_MEMBER
login pass4ord 1ist of roles separated by co33as
22
The =+4C user service 2>?@3
Aueries R+4MS for users and their authorities
&rovides default queries
' S#CT username( password( enabled :R9M users
W8R username B C
' S#CT username( authority :R9M authorities
W8R username B C
23
The =+4C user service 2@?@3
Configuration$
!security$authentication%3anager#
!security$authentication%pro9ider#
!security$;dbc%user%ser9ice data%source%ref&'3yDatasource' (#
!(security$authentication%pro9ider#
!security$authentication%3anager#
possibility to custo3iDe >ueries using
attributes such as
authorities%by%userna3e%>uery
24
9ther Authentication 9ptions
5mplement a custom +serDetailsSer9ice
' +elegate to an e;isting !ser repository or +A9
#+A&
-,./0 Certificates
=AAS #ogin Module
Single1Sign19n
' SiteMinder
' Derberos
' =A1S57 Central Authentication Service
AuthoriDation is not affected by changes to AuthenticationE
25
Topics in this Session
8igh1#evel Security 9verview
Motivations of Spring Security
Spring Security in a Web nvironment
Configuring Web Authentication
(sing Spring Security)s *#g Libr#ries
Method security
Advanced security$ wor%ing with filters
26
Tag library declaration
The Spring Security tag library can be declared
as follows
!FG taglib prefix&'security'
uri&'http$((444"springfra3e4or5"org(security(tags' F#
!FG taglib prefix&'security'
uri&'http$((444"springfra3e4or5"org(security(tags' F#
a9ailable since Spring Security @"H
27
Spring Security)s Tag #ibrary
+isplay properties of the Authentication obEect
8ide sections of output based on R9#
2ou are logged in as$
!security$authentication property&8principal"userna3e<(#
!security$authoriDe ifAny=ranted&8R61.*ADMI/<#
,6P%S.CR., I/06RMA,I6/
Clic5 !a href&8(ad3in(deleteAll<#-.R.!(a# to delete all records"
!(security$authoriDe#
,his +R1 should be protected by
the intercept%url tag alsoE
28
Topics in this Session
8igh1#evel Security 9verview
Motivations of Spring Security
Spring Security in a Web nvironment
Configuring Web Authentication
!sing Spring Security"s Tag #ibraries
"ethod security
Advanced security$ wor%ing with filters
29
Method security
Spring Security uses A9& for security at the
method level
' ;ml configuration with the Spring Security
namespace
' annotations based on Spring annotations or =SR1@./
annotations
30
Method security with
-M# config
Allows to apply security to many beans with
only a simple declaration
!security$global%3ethod%security#
!security$protect%pointcut
expression&'execution() co3"springsource"")Ser9ice")(""))'
access&'R61.*+S.R' (#
!(security$global%3ethod%security#
31
Method security with Spring
annotations
Spring Security annotations should be enabled
!security$global%3ethod%security secured%annotations&'enabled' (#

on the =ava level$
import org.springramewor!.security.annotation."ecured#
pu$%ic c%ass Ite3Manager I
GSecured('R61.*M.MB.R')
pu$%ic Ite3 findIte3(long ite3/u3ber) I
"""
J
J
32
Method security with =SR @./
annotations
=SR1@./ annotations should be enabled
!security$global%3ethod%security ;sr@CH%annotations&'enabled' (#

!security$global%3ethod%security ;sr@CH%annotations&'enabled' (#

on the =ava level$
import &ava'.annotation.security.(o%es)%%owed#
pu$%ic c%ass Ite3Manager I
GRolesAllo4ed('R61.*M.MB.R')
pu$%ic Ite3 findIte3(long ite3/u3ber) I
"""
J
J
import &ava'.annotation.security.(o%es)%%owed#
pu$%ic c%ass Ite3Manager I
GRolesAllo4ed('R61.*M.MB.R')
pu$%ic Ite3 findIte3(long ite3/u3ber) I
"""
J
J
33
Topics in this Session
8igh1#evel Security 9verview
Motivations of Spring Security
Spring Security in a Web nvironment
Configuring Web Authentication
!sing Spring Security"s Tag #ibraries
Method security
'd#nced security+ wor,ing with $ilters
34
Spring Security in a Web
nvironment
springSecurity:ilterChain is declared in web,;ml
This single pro;y filter delegates to a chain of
Spring1managed filters
' +rive authentication
' nforce authori*ation
' Manage logout
' Maintain SecurityContext in -ttpSession
' and more
35
Web Security :ilter
Configuration
*e$
+ser
Ser9let
Ser9let Container
Spring ApplicationContext
0ilter
@ K
0ilter
/
Delegating0ilterProxy
spring"ecurity,i%ter-.ain
0ilter
?
36
The :ilter chain
With AC75 Security >,;
' :ilters were manually configured as individual
FbeanG elements
' #ed to verbose and error1prone -M#
Since Spring Security @,/
' :ilters are initiali*ed with correct values by default
' Manual configuration is not required unless you
w#nt to customi-e Spring Security)s beh#ior
' 5t is still important to understand how they wor%
underneath
37
Access !nsecured Resource &rior
to #ogin
Aeb Bro4ser
+nsecuredResource
0ilterSecurityInterceptor
.xception,ranslation0ilter
AuthenticationProcessing0ilter
-ttpSessionContextIntegration0ilter
1ogout0ilter
/o context in session
/sta$%is.es empty
security conte't
/ot a logout re>uest
does nothing
/ot an authentication
re>uest does nothing
Does nothing on
re>uest side
Resource has no
security attributes
does nothing
Resource has no
security attributes
does nothing
/o exceptions thro4n
does nothing
Does nothing on
response side
Does nothing on
response side
Context did not
change so no need to
store in session
-%ears conte't
38
Access Secured Resource &rior to
#ogin
Aeb Bro4ser
SecuredResource
0ilterSecurityInterceptor
.xception,ranslation0ilter
AuthenticationProcessing0ilter
-ttpSessionContextIntegration0ilter
1ogout0ilter
/o context in session
/sta$%is.es empty
security conte't
Does nothing
Does nothing
Does nothing
Resource is secured
01(2*" 320
)+01/304-)0/5
/6-/70423
Authentication
exceptionE
L "aves current
re8uest in session
L-%ears conte't
L(edirects to
aut.entication entry
point
'
1ogin 0or3
39
Submit #ogin Request
Aeb Bro4ser
SecuredResource
0ilterSecurityInterceptor
.xception,ranslation0ilter
AuthenticationProcessing0ilter
-ttpSessionContextIntegration0ilter
1ogout0ilter
/o context in session
/sta$%is.es empty
security conte't
Does nothing
Creates re>uest and
delegates to the
Authentication
Manager
L"+--/""
populates context
redirects to target url
L,)49+(/
redirects to failure url
40
Access Resource With
Required Role
Aeb Bro4ser
SecuredResource
0ilterSecurityInterceptor
.xception,ranslation0ilter
AuthenticationProcessing0ilter
-ttpSessionContextIntegration0ilter
1ogout0ilter
,inds conte't in
session and sets
or current t.read
Does nothing
Does nothing
Does nothing
Consults attributes7
obtains context7 and
delegates to access
decision 3anager
Does nothing
Does nothing
"tores conte't $ac!
into session
Does nothing
Does nothing
41
Access Resource Without
Required Role
Aeb Bro4ser
SecuredResource
0ilterSecurityInterceptor
.xception,ranslation0ilter
AuthenticationProcessing0ilter
-ttpSessionContextIntegration0ilter
1ogout0ilter
,inds conte't in
session and sets
or current t.read
Does nothing
Does nothing
Does nothing
0.rows )--/"" 5/34/5 /6-/70423
'
Consults attributes7
obtains context7 and
delegates to access
decision 3anager
Access Denied
.xceptionE
L 7uts e'ception in
re8uest scope
L ,orwards to t.e
error page
.rror Page
42
Submit #ogout Request
Aeb Bro4ser
SecuredResource
0ilterSecurityInterceptor
.xception,ranslation0ilter
AuthenticationProcessing0ilter
-ttpSessionContextIntegration0ilter
1ogout0ilter
,inds conte't in
session and sets
or current t.read
L -%ears conte't
L (edirects to
%ogout success ur%
1ogout Success
43
The :ilter Chain$ Summary
. /ilter 0#me "#in 1urpose
>
8ttpSessionConte;t
5ntegration:ilter
stablishes SecurityConte;t and
maintains between 8TT& requests
@ #ogout:ilter
Clears SecurityConte;t8older when
logout requested
H
Authentication
&rocessing :ilter
&uts Authentication into the
SecurityConte;t on login request
I
;ception
Translation:ilter
Converts SpringSecurity e;ceptions
into 8TT& response or redirect
.
:ilterSecurity
5nterceptor
Authori*es web requests based on
on config attributes and authorities
44
Custom :ilter Chain
9ne filter on the stac% may be repl#ced by a
custom filter
!security$http#
!custo3%filter position&'06RM*16=I/*0I1,.R' ref&'3y0ilter< (#
!(security$http#
!bean id&'3y0ilter' class&'co3"3yco3pany"MySpecialAuthentication0ilter'(#
!security$http#
!custo3%filter after&'06RM*16=I/*0I1,.R' ref&'3y0ilter< (#
!(security$http#
!bean id&'3y0ilter' class&'co3"3yco3pany"MySpecial0ilter'(#
9ne filter can be #dded to the chain
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
#A4
Applying Security to a Web Application
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Introduction to Spring Remoting
Simplifying Distributed Applications
2
Topics in this Session
Goals o Spring !emoting
Spring Remoting Overview
Supported Protocols
R!I
"ttpInvo#er
"essian$%urlap
3
&oals of Spring Remoting
"ide 'plumbing( code
)onfigure and e*pose services declaratively
Support multiple protocols in a consistent way
4
The Problem with Plumbing )ode
Remoting mechanisms provide an abstraction
over transport details
These abstractions are often lea#y
The code must conform to a particular model
+or e*ample, with R!I-
Service interface e*tends Remote
Service class e*tends UnicastRemoteObject
)lient must catch RemoteExceptions
"iolates a separation o concerns
Couples business logic to remoting
inrastructure
5
"iding the Plumbing with Spring
Spring provides exporters to handle server.
side re/uirements
%inding to registry or e*posing an endpoint
)onforming to a programming model if necessary
Spring provides FactoryBeans that generate
proxies to handle client.side re/uirements
)ommunicate with the server.side endpoint
)onvert remote e*ceptions to a runtime hierarchy
6
The Declarative Approach
Spring0s abstraction uses a configuration.based
approach
On the server side
1*pose e*isting services with 2O code changes
On the client side
Invo#e remote methods from e*isting code
Ta#e advantage of polymorphism by using
dependency in3ection
7
)onsistency across Protocols
Spring0s e*porters and pro*y FactoryBeans bring
the same approach to multiple protocols
Provides fle*ibility
Promotes ease of adoption
On the server side
1*pose a single service over multiple protocols
On the client side
Switch easily between protocols
!igrate between remote vs4 local deployments
8
Topics in this Session
&oals of Spring Remoting
Spring !emoting #$er$iew
Supported Protocols
R!I
"ttpInvo#er
"essian$%urlap
9
Service 1*porters
Spring provides service e*porters to enable
declarative e*posing of e*isting services
transfer(..)
transfer(..)
Spring
ServiceExporter
<<interface>>
TransferService
TransferServiceImpl
Teller
Controller
Accessile from remote clients
10
)lient Pro*ies
Dynamic pro*ies generated by Spring
communicate with the service e*porter
Spring
ServiceExporter
Server !rocess
TransferServiceImpl
"enerate# y a Spring FactoryBean
<<interface>>
TransferService
transfer(..)
Spring
!roxy
Client !rocess
<<interface>>
TransferService
Teller
$es%top
&I
11
Topics in this Session
&oals of Spring Remoting
Spring Remoting Overview
Supported %rotocols
R!I
"ttpInvo#er
"essian$%urlap
12
The R!I Protocol
Standard 5ava remoting protocol
Server.side e*poses a skeleton
)lient.side invo#es methods on a stub 6pro*y7
5ava seriali8ation is used for marshalling
13
Traditional R!I
The R!I model is invasive . server and client
code is coupled to the framewor#
transfer(..)
S%eleton
Server !rocess
TransferServiceImpl
St'
Client !rocess
(emote &nicast(emote)*ect
<<interface>>
TransferService
Teller
$es%top
&I
Client m'st catc+
RemoteExceptions
(e,'ire# to exten# (-I
interface.class
14
Spring0s R!I Service 1*porter
Transparently e*pose an e*isting PO5O service
to the R!I registry
2o need to write the binding code
Avoid traditional R!I re/uirements
Service interface does not e*tend Remote
Service class is a PO5O
15
)onfiguring the R!I Service 1*porter
Start with an e*isting PO5O service
Define a bean to e*port it
<ean i#/0transferService1 class/0foo.TransferServiceImpl1>
<property name/0acco'nt(epository1 ref/0acco'nt(epository1.>
<.ean>
<ean i#/0transferService1 class/0foo.TransferServiceImpl1>
<property name/0acco'nt(epository1 ref/0acco'nt(epository1.>
<.ean>
<ean class/0org.springframe2or%.remoting.rmi.(miServiceExporter1>
<property name/0service3ame1 val'e/0transferService1.>
<property name/0serviceInterface1 val'e/0foo.TransferService1.>
<property name/0service1 ref/0transferService1.>
<.ean>
Can also specify 4registry!ort5 (#efa'lt is 6788)
<property name/0registry!ort1 val'e/067891.>
Bin#s to rmi(egistry as 0transferService1
16
Spring0s R!I Pro*y &enerator
Spring provides a FactoryBean implementation
that generates an R!I client.side pro*y
It is simpler to use than a traditional R!I stub
)onverts chec#ed (emoteExceptions into Spring0s
runtime hierarchy of (emoteAccessExceptions
Dynamically implements the business interface
Proxy is a rop!in rep"acement #or a "oca" imp"ementation
$especia""y con%enient &it' epenency injection(
17
)onfiguring the R!I Pro*y
Define a factory bean to generate the pro*y
In3ect it into the client
<ean i#/0transferService1
class/0org.springframe2or%.remoting.rmi.(mi!roxyFactoryBean1>
<property name/0serviceInterface1 val'e/0foo.TransferService1.>
<property name/0service&rl1 val'e/0rmi:..foo:6788.transferService1.>
<.ean>
<ean i#/0teller$es%top&I1 class/0foo.Teller$es%top&I1>
<property name/0transferService1 ref/0transferService1.>
<.ean>
Teller$es%top&I only #epen#s on t+e TransferService
interface
18
Spring0s "ttpInvo#er
A lightweight "TTP.based remoting protocol
!ethod invocation is converted to an "TTP POST
!ethod result is returned as an "TTP response
!ethod parameters and return values are marshalled
with standard 5ava seriali8ation
;TT! !)ST re,'est
;ttpInvo%er
ServiceExporter
Server !rocess
;ttpInvo%er
!roxy
Client !rocess
;TT! response
<ava seriali=ation
19
)onfiguring the "ttpInvo#er
Service 1*porter
Start with an e*isting PO5O service
Define a bean to e*port it
<ean i#/0transferService1 class/0foo.TransferServiceImpl1>
<property name/0acco'nt(epository1 ref/0acco'nt(epository1.>
<.ean>
<ean name /0.transfer1
class/0org.springframe2or%.remoting.+ttpinvo%er.
;ttpInvo%erServiceExporter1>
<property name/0serviceInterface1 val'e/0foo.TransferService1.>
<property name/0service1 ref/0transferService1.>
<.ean>
en#point for ;TT! re,'est
+an#ling
20
)onfiguring the "ttpInvo#er
Pro*y
Define a factory bean to generate the pro*y
In3ect it into the client
<ean i#/0transferService1
class/0org.springframe2or%.remoting.+ttpinvo%er.
;ttpInvo%er!roxyFactoryBean1>
<property name/0serviceInterface1 val'e/0foo.TransferService1.>
<property name/0service&rl1 val'e/0+ttp:..foo:>7>7.services.transfer1.>
<.ean>
<ean i#/0teller$es%top&I1 class/0foo.Teller$es%top&I1>
<property name/0transferService1 ref/0transferService1.>
<.ean>
;TT! !)ST re,'ests 2ill e sent to t+is
&(?
21
"essian and %urlap
)aucho created these two lightweight protocols
for sending 9!: over "TTP
"essian uses binary 9!: 6more efficient7
Implementations for many languages
%urlap uses te*tual 9!: 6human readable7
The Ob3ect$9!: seriali8ation$deseriali8ation
relies on a proprietary mechanism
%etter performance than 5ava seriali8ation
:ess predictable when wor#ing with comple* types
22
"essian and %urlap
)onfiguration
Service e*porter configuration is identical to
;ttpInvo%erServiceExporter e*cept class names
@ org.springframe2or%.remoting.ca'c+o.;essianServiceExporter
@ org.springframe2or%.remoting.ca'c+o.B'rlapServiceExporter
Pro*y configuration is identical to
;ttpInvo%er!roxyFactoryBean e*cept class names
@ org.springframe2or%.remoting.ca'c+o.;essian!roxyFactoryBean
@ org.springframe2or%.remoting.ca'c+o.B'rlap!roxyFactoryBean
23
)hoosing a Remoting
Protocol 6;7
Spring on server and client<
"ttpInvo#er
5ava environment but no web server<
R!I
Interop with other languages using "TTP<
"essian 6wor#able, but not ideal7
Interop with other languages without "TTP<
R!I.IIOP 6)OR%A7
24
)hoosing a Remoting
Protocol 6=7
Also consider the relationship between server and client
All of the protocols discussed here are based upon
Remote Procedure )alls 6RP)7
)lients need to #now details of method invocation
2ame, parameters, and return value
>hen using 5ava seriali8ation
)lasses$interfaces must be available on client
?ersions must match
If serving public clients beyond your control, >eb
Services are usually a better option
Document.based messaging promotes loose coupling
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
:A%
Simplifying Distributed Applications with Spring
Remoting
Copyright 2006-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Spring JMS
Simplifying Messaging Applications
2
Topics in this Session
Introduction to JS
Apache ActiveMQ
Configuring JMS Resources with Spring
Springs JmsTemplate
Sending Messages
Receiving Messages
3
Java Message Service JMS!
The JMS A"# provides an a$straction for
accessing Message %riented Middleware
& Avoid vendor loc'(in
& #ncrease porta$ility
4
JMS Core Components
Message
)estination
Connection
Session
Message"roducer
MessageConsumer
5
JMS Message Types
#mplementations of the Message interface
TextMessage
ObjectMessage
MapMessage
BytesMessage
StreamMessage
6
JMS )estination Types
#mplementations of the Destination interface
Queue
"oint(to(point messaging
Topic
"u$lish*su$scri$e messaging
7
The JMS Connection
A JMS Connection is o$tained from a factory
#n a typical enterprise application+ the
Connection,actory is a managed resource and
$ound to J-)#
Connection conn = connectionFactorycreateConnection!"#
$roperties en% = new $roperties!"#
&& pro%i'e J(D) en%ironment properties
Context ctx = new )nitialContext!en%"#
ConnectionFactory connectionFactory =
!ConnectionFactory" ctxloo*up!+connFactory+"#
8
The JMS Session
A Session is created from the Connection
& Represents a unit(of(wor'
& "rovides transactional capa$ility
Session session = conncreateSession!
boolean transacte', int ac*no-le'geMo'e"#
&& use session
if !e%eryt.ingO*ay" /
session.commit();
0 else /
session.rollback();
0
9
Creating Messages
The Session is responsi$le for the creation of
various JMS Message types
sessioncreateTextMessage!+Some Message Content+"#
sessioncreateObjectMessage!someSeriali1ableObject"#
MapMessage message = sessioncreateMapMessage!"#
messageset)nt!+some2ey+, 345"#
BytesMessage message = sessioncreateBytesMessage!"#
message-riteBytes!someByte6rray"#
10
"roducers and Consumers
The Session is also responsi$le for creating
instances of Message$ro'ucer and
MessageConsumer
pro'ucer = sessioncreate$ro'ucer!someDestination"#
consumer = sessioncreateConsumer!someDestination"#
11
Topics in this Session
#ntroduction to JMS
!p"che !cti#e$
Configuring JMS Resources with Spring
Springs JmsTemplate
Sending Messages
Receiving Messages
12
JMS "roviders
Most providers of Message %riented Middleware
MoM! support JMS
& .e$Sphere MQ+ Ti$co /MS+ %racle /MS+ J$oss A"+
SwiftMQ+ etc0
& Some are %pen Source+ some commercial
& Some are implemented in Java themselves
The la$ for this module uses Apache ActiveMQ
13
Apache ActiveMQ
%pen source message $ro'er written in Java
Supports JMS and many other A"#s
& #ncluding non(Java clients1
Can $e used stand(alone in production
environment
& 2activem32 script in download starts with default config
& SpringSource provides support
Can also $e used em$edded in an application
& Configured through ActiveMQ or Spring 4ml files
& .hat we use in the la$s
14
Apache ActiveMQ ,eatures
Support for5
Many cross language clients 6 transport protocols
& #ncl0 /4cellent Spring integration
,le4i$le 6 powerful deployment configuration
& Clustering incl0 load($alancing 6 failover+ 000
Advanced messaging features
& Message groups+ virtual 6 composite destinations+
wildcards+ etc0
/nterprise #ntegration "atterns when com$ined with
Spring #ntegration or Apache Camel
& from the $oo' $y 7regor 8ohpe 6 9o$$y .oolf
15
Topics in this Session
#ntroduction to JMS
Apache ActiveMQ
Con%iguring JS &esources with Spring
Springs JmsTemplate
Sending Messages
Receiving Messages
16
Configuring JMS Resources with
Spring
Spring ena$les decoupling of your application
code from the underlying infrastructure
& The container provides the resources
& The application is simply coded against the A"#
This provides deployment fle4i$ility
& use a standalone JMS provider
& use an ApplicationServer to manage JMS resources
17
Configuring a
ConnectionFactory
The ConnectionFactory may $e standalone
%r it may $e retrieved from J-)#
7bean i'=+connectionFactory+
class=+orgapac.eacti%em86cti%eMQConnectionFactory+9
7property name=+bro*er:;<+ %alue=+tcp=&&local.ost=>3>3>+&9
7&bean9
7jee=jn'i?loo*up i'=+connectionFactory+
jn'i?name=+jms&ConnectionFactory+&9
18
Configuring Destinations
The Destinations may $e standalone
%r they may $e retrieved from J-)#
7bean i'=@or'erQueueA
class=@orgapac.eacti%em8comman'6cti%eMQQueueA9
7constructor?arg %alue=@8ueueor'erA&9
7&bean9
7jee=jn'i?loo*up i'=@or'erQueueA
jn'i?name=@jms&Or'erQueueA&9
19
Topics in this Session
#ntroduction to JMS
Apache ActiveMQ
Configuring JMS Resources with Spring
Spring's JmsTemlate
Sending Messages
Receiving Messages
20
Springs JmsTemplate
The template simplifies usage of the A"#
& Reduces $oilerplate code
& Manages resources transparently
& 8andles e4ceptions properly
& Converts chec'ed e4ceptions to runtime e3uivalents
& "rovides convenience methods and call$ac's
21
JmsTemplate Strategies
The JmsTemplate delegates to colla$orators to
handle some of the wor'
& MessageConverter
& )estinationResolver
22
MessageConverter
The JmsTemplate uses a MessageCon%erter to
convert $etween o$:ects and messages
The default SimpleMessageConverter handles
$asic types
String to TextMessage
Seriali1able to ObjectMessage
Map to MapMessage
byteBC to BytesMessage
23
#mplementing
MessageConverter
#t is sometimes desira$le to provide your own
conversion strategy
& Reuse e4isting code
& )elegate to an o$:ect(to(;M< translator
#mplement the two necessary methods
"rovide the implementation to JmsTemplate via
dependency in:ection
Message toMessage!Object o, Session session"
Object DromMessage!Message message"
24
)estinationResolver
#t is often necessary to resolve destination
names at runtime
JmsTemplate uses DynamicDestination;esol%er as
a default
The Jn'iDestination;esol%er is also availa$le
The interface only re3uires one method
Destination resol%eDestination(ame!Session session,
String 'estination(ame,
boolean pubSubDomain"
t!rows JMSException#
25
)efining a JmsTemplate 9ean
"rovide a reference to the ConnectionFactory
%ptionally provide other references
& MessageConverter
& )estinationResolver
& )efault )estination or default )estination name!
7bean i'=@jmsTemplateA
class=@orgspringDrame-or*jmscoreJmsTemplateA9
7property name=@connectionFactoryA reD=@connectionFactoryA&9
7property name=@'eDaultDestinationA reD=@or'erQueueA&9
7&bean9
26
CachingConnection,actory
JmsTemplate aggressively closes and reopens
JMS resources li'e Sessions and Connections
& Assumes these are cached $y Connection,actory
.ithout caching this causes lots of overhead
& Resulting in poor performance
=se CachingConnection,actory to add caching
within the application if needed
7bean i'=+connectionFactory+
class=+or".srin"framework.#ms.connection.$ac!in"$onnection%actor&+9
7property name=+tar"et$onnection%actor&+9
7bean class=+orgapac.eacti%em86cti%eMQConnectionFactory+9
7property name=+bro*er:;<+ %alue=+%m=&&embe''e'Fbro*erpersistent=Dalse+&9
7&bean9
7&property9
7&bean9
27
Topics in this Session
#ntroduction to JMS
Apache ActiveMQ
Configuring JMS Resources with Spring
Springs JmsTemplate
Sending ess"ges
Receiving Messages
28
Sending Messages
The template provides options
& %ne line methods that leverage the templates
MessageConverter
& Call$ac'(accepting methods that reveal more of the
JMS A"#
=se the simplest option for the tas' at hand
29
Sending Messages with
Conversion
<everaging the templates MessageConverter
'blic (oi) con%ert6n'Sen'!Object message"#
'blic (oi) con%ert6n'Sen'!Destination 'estination,
Object message"#
'blic (oi) con%ert6n'Sen'!String 'estination(ame
Object message"#
30
Sending Messages with
Call$ac's
.hen more control is needed+ use call$ac's
'blic (oi) sen'!MessageCreator messageCreator"#
'blic Object execute!$ro'ucerCallbac*7T9 action"#
'blic Object execute!SessionCallbac*7T9 action"#
Message createMessage!Session session" /G0
31
Creating the 3ueue reference
yourself using a call$ac'
jmsTemplateexecute!new SessionCallbac*7Object9!" /
'blic Object 'o)nJms!Session session" t!rows JMSException /
Queue 8ueue = sessioncreateQueue!+someQueue+"#
Message$ro'ucer pro'ucer =
sessioncreate$ro'ucer!8ueue"#
Message message =
sessioncreateTextMessage!+Hello QueueI+"#
pro'ucersen'!message"#
ret'rn n'll#
0
0"#
32
Topics in this Session
#ntroduction to JMS
Apache ActiveMQ
Configuring JMS Resources with Spring
Springs JmsTemplate
Sending Messages
&ecei#ing ess"ges
33
Synchronous Message
Reception
JmsTemplate can also receive messages+ $ut
methods are $loc'ing with optional timeout!
recei%e!"
recei%e!Destination 'estination"
recei%e!String 'estination(ame"
The MessageCon%erter can $e leveraged for
message reception as well
Object someSeriali1able =
jmsTemplaterecei%e6n'Con%ert!someDestination"#
34
The JMS Message<istener
The JMS A"# defines this interface for
asynchronous reception of messages
public %oi' onMessage!Message" /
&& .an'le t.e message
0
35
Springs Message<istener
Containers
Traditionally+ use of Message<istener
implementations re3uired an /J9 container
Spring provides lightweight alternatives
& SimpleMessage<istenerContainer
=ses plain JMS client A"#
Creates a fi4ed num$er of Sessions
& )efaultMessage<istenerContainer
Adds transactional capa$ility
Advanced scheduling and endpoint management
options availa$le for each container option
36
)efining a plain
JMS Message <istener
)efine listeners using :ms5listener elements
<istener needs to implement Message<istener or
SessionAwareMessage<istener
:ms5listener(container allows for twea'ing of
tas' e4ecution strategy+ concurrency+ container
type+ transaction manager and more
7jms=listener?container connection?Dactory=+myConnectionFactory+9
7jms=listener 'estination=+8ueueor'er+ reD=+myOr'er<istener+&9
7jms=listener 'estination=+8ueueconD+ reD=+myConD<istener+&9
7&jms=listener?container9
37
Spring2s message(driven o$:ects
Spring also allows you to specify a plain Java
o$:ect that can serve as a listener
"arameter automatically converted using a
MessageConverter
Return value sent to response(destination
7jms=listener reD=+mySimpleObject+
met.o'=+or'er+
'estination=+8ueueor'ers+
response?'estination=+8ueueconDirmation+&9
'blic class Or'erSer%ice /
'blic Or'erConDirmation or'er!Or'er o" /0
0
1
1
2
2
3
3
Copyright 2006-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
<A9
Sending and Receiving Messages in a Spring
/nvironment
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Performance and Operations with
Spring
Management and Monitoring of Java
Applications
2
Topics in this Session
Introduction
JMX
Introducing Spring JMX
Eplicitl! eporting "eans with Spring
Automaticall! eporting eisting M#eans
Spring Insight
3
Overall $oals
$ather information a"out application during
runtime
%!namicall! reconfigure app to align to eternal
occasions
Trigger operations inside the application
Even adapt to "usiness changes in smaller
scope
4
Topics in this Session
Introduction
J!
Introducing Spring JMX
Eplicitl! eporting "eans with Spring
Automaticall! eporting eisting M#eans
Spring Insight
5
&hat is JMX'
The Java Management Etensions specification
aims to create a standard API for adding
management and monitoring to Java
applications
Management
( )hanging configuration properties at runtime
Monitoring
( *eporting cache hit+miss ratios at runtime
6
,ow JMX &or-s
To add this management and monitoring
capa"ilit!. JMX instruments application
components
JMX introduces the concept of the M#ean
( An o"/ect with management metadata
7
JMX Architecture
MBeanServer
MBean MBean MBean
JSR-160
Connector
JSR-160
Connector
8
JMX Architecture
An M#eanServer acts as a "ro-er for
communication "etween
( Multiple local M#eans
( *emote clients and M#eans
An M#eanServer maintains a -e!ed reference to
all M#eans registered with it
Man! generic clients availa"le
( /console. /visualvm. ,!peric
9
JMX Architecture
An M#ean is an o"/ect with additional
management metadata
( Attri"utes 0 properties1
( Operations 0 methods1
The management metadata can "e defined
staticall! with a Java interface or defined
d!namicall! at runtime
( Simple M#ean or %!namic M#ean respectivel!
10
Plain JMX ( Part I
public class JmxCounter implements JmxCounterMBean {
public int getCount() {}
public void increment() {}
}
public interface JmxCounterMBean {
int getCount(); becomes !ttribute named "Count"
void increment(); becomes #peration named "increment"
}
11
Plain JMX ( Part II
MBean$erver server % Management&actor'(get)latformMBean$erver();
JmxCounter bean % ne* JmxCounter();
tr' {
#b+ect,ame name % ne* #b+ect,ame(-ourapp.name%counter-);
server(registerMBean(bean/ name);
} catc0 (1xception e) {
e(print$tac23race();
}
12
Topics in this Session
Introduction
JMX
Introducing Spring J!
Eplicitl! eporting "eans with Spring
Automaticall! eporting eisting M#eans
Spring Insight
13
$oals of Spring JMX
2sing the raw JMX API is difficult and comple
The goal of Spring3s JMX support is to simplif!
the use of JMX while hiding the compleit! of
the API
14
$oals of Spring JMX
)onfiguring JMX infrastructure
( %eclarativel! using contet namespace or
4actor!#eans
Eposing Spring "eans as M#eans
( Annotation "ased metadata
( %eclarativel! using Spring "ean definitions
)onsuming JMX managed "eans
( Transparentl! using a pro!5"ased mechanism
15
)reating an M#eanServer
To locate or create an M#eanServer
declarativel!. use the contet namespace
6 or declare it eplicitl!
4context.mbean5server 6
4bean id%-mbean$erver-
class%-org(springframe*or2(+mx(support(
MBean$erver&actor'Bean-6
4propert' name%-locate1xisting$erver7f)ossible- value%-true-6
4bean6
16
Topics in this session
Introduction
JMX
Introducing Spring JMX
"xplicitly exporting be#ns with Spring
Automaticall! eporting eisting M#eans
Spring Insight
17
Eport "ean as JMX M#ean
using Annotations
8Managed9esource(description%:! simple JM; counter<)
public class JmxCounter7mpl implements JmxCounter {
8Managed!ttribute(description%:30e counter value<)
public int getCount() {}
8Managed#peration(description%:7ncrements t0e counter value<)
public void increment() {}
}
4context.mbean5export6
Annotate !our class and methods to "e eposed
Activate eporter
O"/ect7ame derived from full! 8ualified class name
( or passed as attri"ute to 9Managed*esource
18
Spring3s M#eanEporter
Transparentl! epose an eisting POJO "ean to
the M#eanServer
( 7o need to write the registration code
#! default avoids the need to create an eplicit
management interface or create an O"/ect7ame
instance
( 2ses reflection to manage all properties and methods
( 2ses map -e! as the O"/ect7ame
19
Eporting a "ean as an
M#ean
Start with an eisting POJO "ean
2se the M#eanEporter to eport it
4bean id%-message$ervice- class%-example(Message$ervice-6
4bean class%-org(springframe*or2(+mx(export(MBean1xporter-6
4propert' name%-beans-6
4map6
4entr' 2e'%-service.name%message$ervice-
value5ref%-message$ervice-6
4map6
4propert'6
4bean6
20
Spring in the JMX architecture
$pring
MBean1xporter
$erver )rocess
JmxCounter7mpl
$pring
)rox'
Client )rocess
Client
MBean
$erver
9egistration
at startup
44interface66
JmxCounter
44interface66
JmxCounter
44interface66
JmxCounter
MBean
=enerated
at startup
21
Topics in this session
Introduction
JMX
Introducing Spring JMX
Eplicitl! eporting "eans with Spring
$utom#tic#lly exporting existing %e#ns
Spring Insight
22
Automaticall! eporting
pre5eisting M#eans
Some "eans are M#eans themselves
( e:g: ,i"ernate StatisticsService
Spring can easil! autodetect those and eport
them for !ou
4context.mbean5export6
4bean id%-statistics$ervice-
class%-org(0ibernate(+mx($tatistics$ervice-6
4propert' name%-session&actor'- ref%-session&actor'-6
4bean6
23
Automaticall! eporting
pre5eisting M#eans
;og</ 5 ;ogger%!namicM#ean
4context.mbean5export6
4bean class%-org(apac0e(log>+(+mx(?ogger@'namicMBean-6
4constructor5arg6
4bean class%-org(apac0e(log>+(?ogger-
factor'5met0od%-get?ogger-6
4constructor5arg value%-org(springframe*or2(+mx- 6
4bean6
4constructor5arg6
4bean6
24
Summar!
Spring JMX allows !ou to easil! eport
Spring5managed "eans to a JMX M#eanServer
( Simple value5add now that !our "eans are managed
2se =contet>m"ean5server? to create M#ean
server
2se Spring annotations to declare JMX metadata
2se =contet>m"ean5eport? to automaticall!
eport pre5eisting M#eans
25
Topics in this session
Introduction
JMX
Introducing Spring JMX
Eplicitl! eporting "eans with Spring
Automaticall! eporting eisting M#eans
Spring Insight
26
Spring Insight Overview
Part of tc Server %eveloper Edition
Monitors we" applications deplo!ed into
tc Server
4ocuses on what3s relevant
( esp: performance related parts of the application
%etects performance issues during development
27
Spring Insight Overview
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
What's next?
Certification
Other courses
Resources
Evaluation
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 2
Certification
Computer-based exam
5 multiple-choice !uestions
" minutes
#assin$ score% &'( )*+ !uestions ans,ered
successfull-.
Where?
/n an- #earson 01E 2est Center
2here are some in most bi$ or medium-si3ed cities
4ee http%55,,,6pearsonvue6com5vtclocator5
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 3
Certification )7.
8o, to prepare for the exam?
4ee the Core 4prin$ *6x certification $uide here%
http%55,,,6sprin$source6com5trainin$5certification5sprin$professional

Revie, all the slides
Redo the labs
8o, to re$ister?
9t the end of the class: -ou ,ill receive a voucher b-
email
;or an- further in!uir-: -ou can ,rite to
sprin$sourceuniversit-<vm,are6com
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 4
Other courses
=an- courses available
Rich Web 9pplications ,ith 4prin$
Enterprise /nte$ration ,ith 4prin$
8ibernate ,ith 4prin$
>roov- and >rails
tc 4erver: 2omcat: 8-peric
?
=ore details here%
http%55,,,6sprin$source6com5trainin$5curriculum
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 5
Rich Web 9pplications ,ith 4prin$
@-da- ,orAshop
=aAin$ the most of 4prin$ in the ,eb la-er
4prin$ =0C and 4prin$ Web ;lo,
Rich 1ser /nterfaces: 4prin$ Bava4cript: CoDo
B4; ,ith 4prin$ ;aces
;lex clients ,ith 4prin$ Ela3eC4
#roductivit- ,ith Roo and >rails
4prin$ Web 9pplication Ceveloper certification
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 6
Enterprise /nte$ration ,ith 4prin$
@ da- course that ,ill $ive -ou the opportunit- to%
Ciscover 4prin$ Eatch
Ciscover 4prin$ /nte$ration
WorA ,ith advanced transaction mana$ement
Fearn ho, to ,orA ,ith concurrenc-
Fearn Web 4ervices best practices
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 7
8ibernate ,ith 4prin$
* da- course that ,ill $ive -ou the opportunit- to%
Confi$ure 8ibernate applications ,ith 4prin$ and
4prin$ 2ransactions )overlaps this course.
/mplement inheritance and relationships ,ith B#9
and 8ibernate
Ciscover ho, 8ibernate mana$es obDects
>o more in depth on locAin$ ,ith 8ibernate
9dvanced features such as interceptors: cachin$
and batch updates
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 8
Consultin$ Offerin$s
GuicA 4can
Expert revie,s proDect or architecture and sho,s ho,
to improve
8-peric Bump 4tart
8elps -ou startin$ ,ith 8-peric to monitor -our
environment
Bava EE to tc 4erver =i$ration
2omcat to tc 4erver =i$ration
=i$rate -our application and production environment
to tc 4erver
9nd custom consultin$ en$a$ements that fits
-our specific needs
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 9
Resources
2he 4prin$ reference documentation
http%55,,,6sprin$source6or$5documentation
9lread- +H pa$esI
2he official technical blo$
http%55blo$6sprin$source6com5
2he 4prin$ communit- forums
http%55forum6sprin$frame,orA6or$5
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 10
Resources )7.
Jou can re$ister issues on our Bira repositor-
http%55Dira6sprin$frame,orA6or$5
2he source code is available here
https%55src6sprin$source6or$5svn5sprin$-frame,orA
=ore information on ho, to build 4prin$%
http%55blo$6sprin$source6com57"5*5*5buildin$-sprin$-*5
;ollo, 4prin$ development via R44
https%55fishe-e6sprin$source6or$5bro,se5sprin$-frame,orA5trunA
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 11
2hanA JouI
We hope -ou enDo-ed the course
#lease fill out the evaluation form at
http://www.springsource.com/training/evaluation
Copyright2006-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Object/Relational Mapping with
Spring and Java Persistence API
2
Topics in this session
Introduction to J!
eneral !oncepts
Mapping
"#er$ing
!on%ig#ring an &ntit$Manager in Spring
I'ple'enting JPA (AOs
3
JPA eneral !oncepts
The "ntity#$n$ger represents a #nit o% wor)
Also )nown as PersistenceContext
!orresponds at a higher*level to a !onnection
Manages persistent objects within the #nit*o%*wor)
4
JPA eneral !oncepts +,-
An "ntity#$n$ger%$ctory is a thread*sa%e.
shareable object that represents a single data
so#rce
Provides access to a transactional &ntit$Manager
A ersistence&nit describes a gro#p o%
persistent classes
(e%ines providers
(e%ines transactional t$pes +local vs JTA-
M#ltiple /nits per application are allowed
5
Persistence !onte0t and
&ntit$Manager
6
The &ntit$Manager API
!reate a JP"1 2#er$
flush()
persist(Object o)
Adds the entit$ to the Persistence
!onte0t3
SQL: insert into table
remove(Object o)
Re'oves the entit$ %ro' the Persistence
!onte0t3
SQL: delete from table
find(Class entity, Object primaryKey)
4ind b$ pri'ar$ )e$3
SQL: select * from table where id = ?
Query createQuery(String jpqlString)
4orce entit$ state to be written to
database i''ediatel$
lus other methods !!!
7
JPA Providers

Several major implementations of "# spec


$ %clipse&in'()oplin' (*+)
$ #pache Open"#
$ ,ibernate %ntity-anager
8
5ibernate JPA
5ibernate i'ple'ents the JPA Standard thro#gh
an additional librar$
The Hibernate Entityana!er
5ibernate still #sed behind the JPA inter%aces
!#sto' Annotations available %or 5ibernate speci%ic
e0tensions not covered b$ JPA
9
JPA Mapping
JPA re2#ires 'etadata %or 'apping
classes/properties to database tables/col#'ns
/s#all$ provided as annotations
!an also be provided as 6M1 "not recommended#
JPA 'etadata relies on de%a#lts
7o need to provide 'etadata %or the obvio#s
10
8hat can $o# annotate9
!lasses
Metadata which applies to the entire class +e:g: table-
&ither %ields or properties
Metadata which applies to a single %ield or propert$
+e:g: 'apped col#'n-
;ased on de%a#lt. all %ields or properties will be treated
as persistent +'appings will be de%a#lted-
!an be annotated with <Transient +non*persistent-
11
Mapping si'ple properties
with annotations
.%ntity
.)able(name/ 0)1C2S)O-%*3)
public class Customer 4
.+d
.Column (name/0cust1id3)
private &ong id5
.Column (name/0first1name3)
private String first6ame5
!!!
7efines field as entity +7
12
Relationships
!o''on relationship 'appings s#pported
Single entities and collections o% entities both
s#pported
.%ntity
.)able(name/ 0)1C2S)O-%*3)
public class Customer 4
.+d
.Column (name/0cust1id3)
private &ong id5
.One)o-any(cascade/Cascade)ype!#&&)
."oinColumn (name/0cust1id3)
private Set8#ddress9 addresses5
:
ropagate all operations
to the child objects
13
JPA "#er$ing
JPA provides several options %or 2#er$ing entities
Retrieve an object b$ pri'ar$ )e$
Retrieve objects with the Java Persistence "#er$
1ang#age +JP"1-
Retrieve objects #sing the #nderl$ing =native> 2#er$
lang#age +t$picall$ S"1-
14
JPA "#er$ing3 ;$ Pri'ar$ ?e$
To retrieve an object b$ its database identi%ier
si'pl$ call find on the %ntity-anager
&ong customer+d / ;<=&5
Customer customer / entity-anager!find(Customer!class, customer+d)5
*eturns null if entity does not e>ist
15
JPA "#er$ing3 JP"1
To 2#er$ %or objects based on properties or
associations #se JP"1
Method calls 'a$ be chained +as in 5ibernate-
public Customer find?y&ast6ame(String last6ame) 4
return (Customer) entity-anager!createQuery(
@select c from Customer c Ahere c!name / Blast6ame@)
!setarameter(@last6ame@, last6ame)
!getSingle*esult()5
C
+f multiple customers are e>pected, use get*esult&ist()
16
Topics in this session
Introd#ction to JPA
eneral !oncepts
Mapping
"#er$ing
Con'iguring $n "ntity#$n$ger in Spring
I'ple'enting JPA (AOs
17
Setting #p an
&ntit$Manager4actor$
Three wa$s to set #p an &ntit$Manager4actor$3
1ocal&ntit$Manager4actor$;ean
1ocal!ontainer&ntit$Manager4actor$;ean
/se a J7(I loo)#p
All approaches re2#ire a persistence:0'l %or
con%ig#ration
18
persistence.xml
Alwa$s stored in M&TA*I74
Speci%ies3
persistence #nit
vendor*dependent in%or'ation:
8persistence version/@;!D@
>mlns/@httpB((java!sun!com(>ml(ns(persistence@
>mlnsB>si/@httpB((AAA!A=!org(<DD;(E-&SchemaFinstance@
>siBschema&ocation/@httpB((java!sun!com(>ml(ns(persistence
httpB((java!sun!com(>ml(ns(persistence(persistence1;1D!>sd@9
8persistenceFunit name/@reAard6etAor'@(9
8(persistence9
19
1ocal&ntit$Manager4actor$;ean
/se%#l %or standalone apps. integration tests
!annot speci%$ a (ataSo#rce
/se%#l when onl$ data access is via JPA
/ses standard JPA service location 'echanis'
/M&TA*I74/services/java0:persistence:spi:PersistenceProvider
8bean id/@entity-anagerGactory@
class/@o!s!orm!jpa!&ocal%ntity-anagerGactory?ean@9
8property name/@persistence2nit6ame@
value/@reAard6etAor'@(9
8(bean9
20
1ocal!ontainer
&ntit$Manager4actor$;ean +@-
Provides %#ll JPA capabilities
Integrates with e0isting (ataSo#rces
/se%#l when %ine*grained c#sto'iAation needed
!an speci%$ vendor*speci%ic con%ig#ration
21
1ocal!ontainer
&ntit$Manager4actor$;ean +,-
8bean id/@entity-anagerGactory@
class/@org!springsource!orm!jpa!&ocalContainer%ntity-anagerGactory?ean@9
8property name/@dataSource@ ref/@dataSource@(9
8property name/@persistence2nit6ame@ value/0reAard6etAor'@(9
8property name/@jpaHendor#dapter@9
8bean class/@o!s!orm!jpa!vendor!,ibernate"paHendor#dapter@9
8property name/@shoASql@ value/@true@(9
8property name/@generate7dl@ value/@true@(9
8property name/@database@ value/@,SQ&@(9
8(bean9
8(property9
8property name/@jparoperties"9
8value9
hibernate!format1sql=true
8(value9
8(property9
8(bean9
22
&ntit$Manager4actor$;eans
OrderService+mpl
"#
Order*epository
%ntity-anager
7ataSource
&ocalContainer
%ntity-anager
Gactory?ean
creates
persistence!>ml
%ntity -anager
Gactory
creates
)his is hidden inside Spring
23
J7(I 1oo)#ps
A $ee:$ndi%loo&'( can be #sed to retrieve
&ntit$Manager4actor$ %ro' application server
/se%#l when deplo$ing to J&& Application
Servers +8ebSphere. 8eb1ogic. etc:-
8jeeBjndiFloo'up id/"entityManagerFactory"
jndiFname/"persistence/rewardNetwork"(9
24
Topics in this session
Introd#ction to JPA
eneral !oncepts
Mapping
"#er$ing
!on%ig#ring an &ntit$Manager in Spring
Implementing J! (!)s
25
I'ple'enting JPA (AOs
JPA provides con%ig#ration options so Spring can
'anage transactions and the &ntit$Manager
/se AOP %or transparent e0ception translation to
SpringBs (ataAccess&0ception hierarch$
There are no Spring dependencies in $o#r (AO
i'ple'entations
26
Spring*'anaged Transactions
and &ntit$Manager +@-
To transparentl$ participate in Spring*driven
transactions
Si'pl$ #se one o% SpringBs Gactory?eans %or b#ilding
the %ntity-anagerGactory
Inject an &ntit$Manager re%erence with
<Persistence!onte0t
(e%ine a transaction 'anager
$ "pa)ransaction-anager
$ "ta)ransaction-anager
27
Spring*'anaged Transactions
and &ntit$Manager +,-
The code with no Spring dependencies
public class "paOrder*epository implements Order*epository 4
@PersistenceContext
private %ntity-anager entity-anager5
!!!
public void some7aoOperation() 4
!!! (( noA use the already prepared entity-anager
C
C
Setter +njection also possible
28
Spring*'anaged Transactions
and &ntit$Manager +C-
The con%ig#ration
8beans9
<bean id=entityana!er"actory#

c$ass=or!%s&rin!fra'e(or)%or'%*&a%+oca$Container,ntityana!er"actory-ean#.
%%%
</bean.
8bean id/0order*epository3 class/0"paOrder*epository3(9
8bean id/ 0transaction-anager3
class/0org!springframeAor'!orm!jpa!"pa)ransaction-anager39
<&ro&erty na'e=entityana!er"actory# ref=entityana!er"actory# /.
8(bean9
<context0annotation1confi!/.

8(beans9
rovides injection for .ersistenceConte>t
29
Transparent &0ception Translation
+@-
/sed as*is. the previo#s (AO i'ple'entation
will throw #nchec)ed Persistence,xce&tions
7ot desirable to let these propagate #p to the service
la$er or other #sers o% the (AOs
Introd#ces dependenc$ on the speci%ic persistence
sol#tion that sho#ld not e0ist
AOP allows translation to SpringBs rich. vendor*
ne#tral 2ata3ccess,xce&tion hierarch$
!an change persistence provider transparentl$
30
Transparent &0ception Translation
+,-
Spring provides this capabilit$ o#t o% the bo0
Annotate with *+epository
(e%ine a Spring*provided ?eanostrocessor
@4e&ository
public class "paOrder*epository implements Order*epository 4
!!!
C
8bean class/0org!springframeAor'!dao!annotation!
ersistence%>ception)ranslationostrocessor3(9
31
Transparent &0ception Translation
+C-
!anDt alwa$s #se annotations
4or e0a'ple third*part$ code
/se 6M1 to con%ig#re instead
public class "paOrder*epository implements -y*epository 4
!!!
C
public class "paOrder*epository implements -y*epository 4
!!!
C
8bean id/0persistence%>ception+nterceptor3
class/0org!springframeAor'!dao!support!
ersistence%>ception)ranslation+nterceptor3(9
8aopBconfig9
8aopBadvisor pointcut/0e>ecution(I I!!-y*epositoryJ!I(!!))3
adviceFref/0persistence%>ception+nterceptor3 (9
8(aopBconfig9
8bean id/0persistence%>ception+nterceptor3
class/0org!springframeAor'!dao!support!
ersistence%>ception)ranslation+nterceptor3(9
8aopBconfig9
8aopBadvisor pointcut/0e>ecution(I I!!-y*epositoryJ!I(!!))3
adviceFref/0persistence%>ception+nterceptor3 (9
8(aopBconfig9
6o annotations
Copyright2006-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
1A;
/sing JPA with Spring
Copyright 2007-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Spring Web Services
Implementing Loosely Coupled Communication
with Spring Web Services
2
Topics in this Session
Introduction to Web Serices
Why use or build a web service?
Best practices or implementing a web service
Spring Web Services
Client access
3
Web Services enable Loose
Coupling
Loosely coupled systems are considered useful
when either the source or the destination
computer systems are subject to frequent
changes
Wikipedia (July !!"#
!oose coupling incre"ses toler"nce#
ch"nges should not c"use incomp"tibility
4
Web Services enable
$nteroperability
!"L is the lingua ranca in the world o
interoperability
!"L is understood by all ma#or platorms
%&'$ %t&' or ()* in %ava
%ystem+'*L or +,-. '*L /arser in &'(T
0-'*L or 'ml%imple in )uby
/erl1'*L or '*L22%imple in *erl
5
Best practices or implementing
web services
)emember+
web services ,- S./*
web services ,- )*C
0esign contract independently rom service interace
)erain rom using stubs and s1eletons
0on2t use validation or incoming re3uests
4se !*ath
Postels law:
Be conservative in what you do;
be liberal in what you accept from others.
Postels law:
Be conservative in what you do;
be liberal in what you accept from others.
6
Web 54I on top o your
services
The Web $%I l"yer
provides comp"tibility
between &'(!-b"sed
world o the user 6the
browser7 and the ))-
b"sed world o your
service
7
Web Service on top o your
services
Web Serice l"yer
provides comp"tibility
between *(!-b"sed
world o the user and
the ))-b"sed world o
your service
8
Topics in this Session
Introduction to Web Services
Why use or build a web service?
Best practices or implementing a web service
Spring Web Serices
Client access
9
0eine the contract
Spring8WS uses Contract8irst
Start with !S09WS0L
Widely considered a Best *ractice
Solves many interoperability issues
/lso considered diicult
But isn2t
10
Contract8irst in : simple
steps
Create sample messages
Iner a contract
Trang
"icrosot !"L to Schema
!"L Spy
Twea1 resulting contract
11
Sample "essage
<transferReuest !mlns"http://mybank.com/schemas/tr
amount"1205.15#
<credit#$%&'<(credit#
<debit#)*+,<(debit#
<(transferReuest#
-amespace for this messa.e
12
0eine a schema or
the web service message
<!s:schema
!mlns:!s""http://www.w3.org/2001/XMLSchema"
!mlns:tr""http://mybank.com/schemas/tr"
element/orm0efault""qa!"#"e$"
tar.et-amespace""http://mybank.com/schemas/tr"#
<!s:element name""trans#er%eqest"#
<!s:comple!1ype#
<!s:seuence#
<!s:element name""cre$"t" type""&s:str"ng"(#
<!s:element name""$eb"t" type""&s:str"ng"(#
<(!s:seuence#
<!s:attribute name""amont" type""&s:$ec"ma!"(#
<(!s:comple!1ype#
<(!s:element#
<(!s:schema#
<transferReuest
amount"1205.15#
<credit#$%&'<(credit#
<debit#)*+,<(debit#
<(transferReuest#
13
Type constraints
<!s:element name""cre$"t" #
<!s:simple1ype#
<!s:restriction base""&s:str"ng"#
<!s:pattern value""'w'$(3)"(#
<(!s:restriction#
<(!s:simple1ype#
<(!s:element#
% )haracter 2 ' 0i.its
14
S./* "essage
3nvelope
Body
1ransferReuest
4eader
$ecurity
Routin.
15
Simple S./* ;&; "essage
(<ample
<$56P73-8:3nvelope !mlns:$56P7
3-8"9http:((schemas.!mlsoap.or.(soap(envelope(9#
<$56P73-8:Body#
<tr:transferReuest !mlns:tr"9http:((myban:.com(schemas(tr9
tr:amount"1205.15#
<tr:credit#$%&'<(tr:credit#
<tr:debit#)*+,<(tr:debit#
<(tr:transferReuest#
<($56P73-8:Body#
<($56P73-8:3nvelope#
16
Spring Web Services
;
<
=

P
r
o
c
e
s
s
i
n
.
$
5
6
P

/
r
a
m
e
w
o
r
:
;<= $56P
;<=
$
5
6
P

/
r
a
m
e
w
o
r
:
;
<
=

P
r
o
c
e
s
s
i
n
.
>$
1emplate
3ndpoint
Client *rocess
Server *rocess
17
<essa.e
0ispatcher
3ndpoint
<appin.
3ndpoint
6dapter
.et3ndpoint?
<essa.e)onte!t@
invo:e?<essa.e)onte!tA selected3ndpoint@
3ndpoint
)e3uest *rocessing
18
Bootstrap the application tier
Inside =webapp9> within web&<ml
<conte!t7param#
<param7name#conte!t)onfi.=ocation<(param7name#
<param7value#
(>3B7B-/(transfer7app7cf..!ml
<(param7value#
<(conte!t7param#
<listener#
<listener7class#
or..sprin.framewor:.web.conte!t.)onte!t=oader=istener
<(listener7class#
<(listener#
1he application conte!ts confi.uration file?s@
=oads the 6pplication)onte!t into the $ervlet)onte!t
be#ore any $ervlets are initialiCed
19
Wire up the ?ront Controller
6"essage0ispatcher7
Inside =webapp9> within web&<ml
<servlet#
<servlet7name#transfer7ws<(servlet7name#
<servlet7class#..ws..<essa.e0ispatcher$ervlet<(servlet7class#
<init7param#
<param7name#conte!t)onfi.=ocation<(param7name#
<param7value#(>3B7B-/(ws7confi..!ml<(param7value#
<(init7param#
<(servlet#
1he application conte!ts confi.uration file?s@
containin. the web service infrastructure beans
20
"ap the ?ront Controller
Inside =webapp9> within web&<ml
<servlet7mappin.#
<servlet7name#transfer7ws<(servlet7name#
<url7pattern#(services(D<(url7pattern#
<(servlet7mappin.#
1here mi.ht also be a web interface ?EFB@ that is
mapped to another path
21
(ndpoint
(ndpoints handle S./* messages
Similar to "@C Controllers
Aandle input message
Call method on business service
Create response message
With Spring8WS you can ocus on the *ayload
Switching rom S./* to *.! without code
change
22
!"L Aandling techni3ues
Low8level techni3ues
0." 6%0."$ domB#$ !."7
S/!
St/!
"arshalling
%/!B 6; and C7
Castor
!"LBeans
!*ath argument binding
23
%/!B C
%/!B C is part o %ava (( D and %0E F
4ses annotations
5enerates classes rom a schema
!#c
/lso generates schema rom classes
<bean id""marsha!!er" class"...*a&b2Marsha!!er"#
<property name""conte&t+ath" value""trans#er.ws.types"(#
<(bean#
<bean class""...,ener"cMarsha!!"ngMetho$-n$po"nt.$apter"#
<constructor7ar. ref""marsha!!er" (#
<(bean#
24
G3ndpoint
public class 1ransfer$ervice3ndpoint H
private 1ransfer$ervice transfer$ervice;
public 1ransfer$ervice3ndpoint?1ransfer$ervice transfer$ervice@ H
this.transfer$ervice " transfer$ervice;
I
GPayloadRoot?localPart"9transferReuest9A
namespace"9http:((myban:.com(schemas(tr9@
public 1ransferResponse new1ransfer?1ransferReuest reuest@ H
(( e!tract necessary info from reuest and invo:e service
I
I
Implement the (ndpoint
$prin. >$ 3ndpoint
<appin.
)onverted with J6;B&
25
Conigure the (ndpoint
<bean id"transfer3ndpoint
class"e!ample.ws.1ransfer$ervice3ndpoint#
<constructor7ar. ref"transfer$ervice(#
<(bean#
<bean class""...+ay!oa$%oot.nnotat"onMetho$-n$po"ntMapp"ng" (#
Ktransfer$ervice is defined in the application tier
$earchin. for G3ndpoint
26
J8<
Java 33 $ervlet )ontainer
/rchitecture o our application
e<posed using a a web service
6pplication =ayer
?application conte!t@
>eb $ervice =ayer
?application conte!t@
=ocal Java Business Bnterfaces
>eb $ervice Bnterface
)lients
27
?urther "appings
Gou can also map your (ndpoints in !"L by
"essage *ayload
S./* /ction Aeader
WS8/dressing
!*ath
28
Topics in this Session
Introduction to Web Services
Why use or build a web service?
Best practices or implementing a web service
Spring Web Services
Client "ccess
29
Spring Web Services on the
Client
L >eb$ervice1emplate
Simpliies web service access
Wor1s directly with the !"L payload
(<tracts body o a S./* message
/lso wor1s with *.! 6*lain .ld !"L7
Can use marshallers9unmarshallers
*rovides convenience methods or sending and
receiving web service messages
*rovides callbac1s or more sophisticated usage
30
"arshalling with
WebServiceTemplate
>eb$ervice1emplate template "
?>eb$ervice1emplate@ conte!t..etBean?web$ervice1emplate@;
1ransferReuest reuest " new 1ransferReuest?$%&'A )*+,A M+.NN@;
Receipt receipt " ?Receipt@ template.marshal$end6ndReceive?reuest@;
<bean id"web$ervice1emplate
class"or..sprin.framewor:.ws.client.core.>eb$ervice1emplate#
<property name"defaultFri value"http:((myban:.com(transfer(#
<property name"marshaller ref"marshaller(#
<property name"unmarshaller ref"marshaller(#
<(bean#
<bean id"marshaller class"or..sprin.framewor:.o!m.castor.)astor<arshaller#
<property name"mappin.=ocation value"classpath:castor7mappin..!ml(#
<(bean#
Copyright 2007-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
L/B
(<posing S./* (ndpoints using
Spring Web Services

You might also like