Anda di halaman 1dari 729

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
-aluation and other
+uestions
We alue your input
% http.//www0springsource0com/training/ealuation
Send any additional !eedback or +uestions to
% training1springsource0com
5
Course Agenda. 2ay 3
Introduction to Spring
4sing Spring to con!igure an application
4nderstanding the bean li!e-cycle
Simpli!ying application con!iguration
Annotation-based dependency in5ection
&esting a Spring-based application
6
Course Agenda. 2ay 6
Adding behaior to an application using
aspects
Introducing data access with Spring
Simpli!ying 728C-based data access
2riing database transactions in a Spring
enironment
7
Course Agenda. 2ay 9
Introducing ob5ect-to-relational mapping
:*;(<
=etting started with )ibernate in a Spring
enironment
-!!ectie web application architecture
=etting started with Spring (>C
Securing web applications with Spring Security
8
Course Agenda. 2ay 4
4nderstanding Spring?s remoting !ramework
=etting started with Spring Web Serices
Simpli!ying message applications with Spring
7(S
Adding manageability to an application with
Spring 7(@
9
SpringSource *eriew
Center o! thought leadership !or 7aa, Spring, Apache,
=rooy/=rails, )yperic
% ;od 7ohnson, C-* A !ather o! SpringB deelop CC$D o! Spring
% &omcat leaders. E#$ o! code commits, C"$ o! bug !iFes
% =rooy/=rails leaders. ac+uired =6*ne Go 6##E
% )yperic app management leaders. ac+uired )yperic (ay 6##C
Forge open source innoation into enterprise
products
% 'eading enterprise adoption o! lean in!rastructure
Customers include most o! the =lobal 6###
*!!ices worldwide
% 4S-based, 4H, Getherlands, =ermany, Australia, France,
Canada
10
SpringSource. *pen Source
'eader in -nterprise 7aa
SpringSource = Spring
% I3 enterprise 7aa programming model
% *er J million downloads
SpringSource = Tomct
% I3 7aa application serer
SpringSource = !nterprise "S#i
% GeFt-generation o! serer modularity
SpringSource = #roo$y % #rils
% 7aaKs answer to ;uby on ;ails
% I3 dynamic language !or 7>(
SpringSource = &pche 'TT(
% I3 Web serer
SpringSource = 'yperic
% 'eader in open source management
11
SpringSource Solution
)igh Lroductiity &ools
Spring -nterprise
=rooy and =rails
SpringSource &ool Suite
'ean Lower!ul ;untimes
SpringSource tc Serer
SpringSource dm Serer
SpringSource -;S
Application In!rastructure (anagement
SpringSource )yperic )M
SpringSource )yperic IM
4ni!ying the Application 'i!ecycle.
!rom 2eeloper to 2atacenter
12
)uild N ;un N (anage
2eelopment solutions
users loe
% 2e !acto standard
component model :Spring<
% SpringSource &ool Suite
:S&S<
% =rooy/=rails
% Spring ;oo
Lroductiity
(anagement Integration
13
8uild N *un N (anage
-nterprise grade serer
solutions built on open
source
% tc Serer
% dm Serer
% http Serer
)igh Ler!ormance
(anageable
14
8uild N ;un N +nge
2epth and 8reath
% Application metrics
% -ntire stack isibility
Correctie Actions
*perations Intelligence
% 8I !or I& and *perations
S'A (onitoring
15
SpringSource *!!erings
Subscriptions
% Certi!ied So!tware
% 2eelopment and Lroduction Support
% 'egal Indemni!ication
&raining
% Lublic, on-site, certi!ication program
Lro!essional Serices
% Client-drien engagementsB packaged A custom
Delivered by Spring, Apache, Groovy/Grails and Hyperic Experts
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
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)
confirmation
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
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(80.00), 1, 2)$
assert49a#s(ne% 3onetar"Amont(100.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 , <dbcTemp#ate.9er"0or&nt(
=S4>4CT C?2:T(@) 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
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
Su&&ar%
3
'o( Spring !orks
Spring
ApplicationContext
Configuration
Instructions
Your Application Classes (POJOs)
Fully configured
application system
Ready for use
Creates
4
)our Application Classes
public class ransferSer!iceImpl implements ransferSer!ice "
public ransferSer!iceImpl(Account#epository ar) "
t$is%account#epository & ar'
(
)
(
public class JdbcAccount#epository implements Account#epository "
public JdbcAccount#epository(*ataSource ds) "
t$is%dataSource & ds'
(
)
(
+eeded to load accounts from t$e database
+eeded to perform money transfers
bet,een accounts
5
Configuration Instructions
-beans.
-bean id&/transferSer!ice0 class&/app%impl%ransferSer!iceImpl0.
-constructor1arg ref&/account#epository0 2.
-2bean.
-bean id&/account#epository0 class&/app%impl%JdbcAccount#epository0.
-constructor1arg ref&/dataSource0 2.
-2bean.
-bean id&/dataSource0 class&/com%oracle%3dbc%pool%Oracle*ataSource0.
-property name&/4#50 !alue&/3dbc6oracle6t$in67local$ost689:86;A+<0 2.
-property name&/user0 !alue&/moneytransfer1app0 2.
-2bean.
-2beans.
6
Creating and *sing the
Application
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(/application1config%xml0)'
22 5oo> up t$e application ser!ice interface
ransferSer!ice ser!ice &
(ransferSer!ice) context%get;ean(/transferSer!ice0)'
22 4se t$e application
ser!ice%transfer(ne, ?onetaryAmount(/@AA%AA0)B /80B /:0)'
7
Inside the Spring Application
Context
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(/application1config%xml0)'
Application Context
Oracle*ataSource
dataSource
JdbcAccount#epository
account#epository
ransferSer!iceImpl
transferSer!ice
8
Quick Start Su&&ar%
Spring &anages the lifec%cle of the application
" All beans are full% initiali+ed before the% are used
,eans are al(a%s created in the right order
" ,ased on their dependencies
-ach bean is bound to a uni.ue id
" The id reflects the ser/ice the bean pro/ides to clients
Spring encapsulates the bean i&ple&entations
chosen for a gi/en application deplo%&ent
" Conceals i&ple&entation details
9
Topics in this session
Spring .uick start
!riting ben de"initions
" Configuring ob#ects
" $oing be%ond constructor instantiation
Creating an application context
Su&&ar%
10
,asic Spring XML ,ean
0efinition Te&plate
-Cxml !ersion&/8%A0 encoding&/4F1D0C.
-beans xmlns&/$ttp622,,,%springframe,or>%org2sc$ema2beans0
xmlns6xsi&/$ttp622,,,%,@%org2:AA82=?5Sc$ema1instance0
xsi6sc$ema5ocation&/
$ttp622,,,%springframe,or>%org2sc$ema2beans
$ttp622,,,%springframe,or>%org2sc$ema2beans2spring1beans1:%9%xsd0.
-E11 Add your bean definitions $ere 11.
-2beans.
11
Si&plest 1ossible ,ean
0efinition
-bean id&/ser!ice0 class&/example%Ser!iceImpl02.
Ser!iceImpl ser!ice & ne, Ser!iceImpl()'
2esults in 3/ia 2eflection45
ApplicationContext
ser!ice 1. instance of Ser!iceImpl
A class ,it$ no dependencies
12
Constructor 0ependenc%
In#ection
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-constructor1arg ref&/repository02.
-2bean.
-bean id&/repository0 class&/example%#epositoryImpl02.
#epositoryImpl repository & ne, #epositoryImpl()'
Ser!iceImpl ser!ice & ne, Ser!iceImpl(repository)'
-.ui/alent to5
ApplicationContext
ser!ice 1. instance of Ser!iceImpl
repository 1. instance of #epositoryImpl
A class ,it$ a single
dependency expected
by its constructor
13
Setter 0ependenc% In#ection
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-property name&/repository0 ref&/repository02.
-2bean.
-bean id&/repository0 class&/example%#epositoryImpl02.
#epositoryImpl repository & ne, #epositoryImpl()'
Ser!iceImpl ser!ice & ne, Ser!iceImpl()'
ser!ice%set#epository(repository)'
-.ui/alent to5
ApplicationContext
ser!ice 1. instance of Ser!iceImpl
repository 1. instance of #epositoryImpl
A class ,it$ a single
dependency expected
by a setter met$od
14
!hen to *se Constructors /s6
Setters7
Spring supports both
)ou can &ix and &atch
15
The Case for Constructors
-nforce &andator% dependencies
1ro&ote i&&utabilit%
" Assign dependencies to final fields
Concise for progra&&atic usage
" Creation and in#ection in one line of code
16
The Case for Setters
Allo( optional dependencies and defaults
'a/e descripti/e na&es
8ollo( 9a/a,ean: con/entions
Inherited auto&aticall%
17
$eneral 2eco&&endations
8ollo( standard 9a/a design guidelines
" *se constructors to set re.uired properties
" *se setters for optional or those (ith default /alues
So&e classes are designed for a particular
in#ection strateg%
" In that case go (ith it; do not fight it
,e consistent abo/e all
18
Co&bining Constructor and
Setter In#ection
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-constructor1arg ref&/reFuired0 2.
-property name&/optional0 ref&/optional0 2.
-2bean.
-bean id&/reFuired0 class&/example%#eFuiredImpl0 2.
-bean id&/optional0 class&/example%OptionalImpl0 2.
#eFuiredImpl reFuired & ne, #eFuiredImpl()'
OptionalImpl optional & ne, OptionalImpl()'
Ser!iceImpl ser!ice & ne, Ser!iceImpl(reFuired)'
ser!ice%setOptional(optional)'
-.ui/alent to5
19
In#ecting Scalar <alues
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-property name&/stringProperty0 !alue&/foo0 2.
-2bean.
Ser!iceImpl ser!ice & ne, Ser!iceImpl()'
ser!ice%setStringProperty(/foo0)'
-.ui/alent to5
ApplicationContext
ser!ice 1. instance of Ser!iceImpl
public class Ser!iceImpl "
public !oid setStringProperty(String s) " %%% (
22 %%%
(
20
Auto&atic <alue T%pe
Con/ersion
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-property name&/integerProperty0 !alue&/:G0 2.
-2bean.
Ser!iceImpl ser!ice & ne, Ser!iceImpl()'
Integer !alue & ne, Integer(/:G0)'
ser!ice%setIntegerProperty(!alue)'
-.ui/alent to5
ApplicationContext
ser!ice 1. instance of Ser!iceImpl
public class Ser!iceImpl "
public !oid setIntegerProperty(Integer i) " %%% (
22 %%%
(
21
In#ecting lists
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-property name&/listProperty0.
-list.
-ref bean&HxyIH2.
-!alue.8:@J-2!alue.
-null2.
-2list.
-2property.
-2bean.
Ser!iceImpl ser!ice & ne, Ser!iceImpl()'
22 create list ,it$ bean referenceB 8:@J !alue and null element
ser!ice%set5istProperty(list)'
-.ui/alent to5
ApplicationContext
ser!ice 1. instance of Ser!iceImpl
22
In#ecting collections
Si&ilar support a/ailable for
" 1roperties 3through props = prop ele&ents4
" Set 3through a set ele&ent; si&ilar to list4
" Map 3through &ap = ke% ele&ents4
23
Topics in this session
'o( Spring (orks
!riting Spring bean definitions
" Configuring ob#ects
" #oing beyond constructor instntition
Creating a Spring application context
Su&&ar%
24
Calling 8actor% Methods
So&e ob#ects cannot be created b% a constructor
public class 5egacySingleton "
pri!ate static 5egacySingleton inst & ne, 5egacySingleton()'
pri!ate 5egacySingleton() " %%% (
public static 5egacySingleton getInstance() "
return inst'
(
(
-bean id&/ser!ice0 class&/example%5egacySingleton0
factory-method="getInstance" 2.
25
Calling 8actor% ,eans
So&eti&es %ou (ant Spring to al(a%s delegate
to 9a/a code to create another bean
public class ComplexSer!iceFactory m!"ements #actory$ean "
Ob3ect getOb3ect() t$ro,s Kxception "
22 create complex ser!ice impl in Ja!a code
(
(
-bean id&/ser!ice0 class&/example%ComplexSer!iceFactory0.
-property name&/neededoCreateSer!ice0 !alue&/)0 2.
-2bean.
26
The 8actor%,ean Contract
Spring auto detects an% bean that i&ple&ents
Factory;ean and returns the ob#ect created b%
get>b#ect34 to clients
" The factor% itself is concealed
ApplicationContext
Factory;ean
get;ean(bean+ame)
getOb3ect() ob3ect
27
A $ood 8actor% ,ean
-xa&ple
-ncapsulating the creation of a test *ataSource
ApplicationContext
est*ataSourceFactory
(8) get;ean(/dataSource0)
(:) getOb3ect() (9) dataSource
%3& createIn'emory(ata)ase%&*
%4& !o!u"ate+th,est(ata%&*
#uns before
t$e data source
is usable by
t$e application
28
8actor%,eans in Spring
9ndi>b#ect8actor%,ean
" >ne option for looking up 9?0I ob#ects
8actor%,eans for creating re&oting proxies
8actor%,eans for configuring data access
technologies like 'ibernate; 91A or i,atis
29
Topics in this session
Spring .uick start
!riting bean definitions
" Configuring ob#ects
" $oing be%ond constructor instantiation
Creting n ppliction context
Su&&ar%
30
Creating a Spring Application
Context
Spring application contexts can be
bootstrapped in an% en/iron&ent; including
" 9*nit s%ste& test
" !eb application
" -nterprise 9a/a ,ean 3-9,4
" Standalone application
Loadable (ith bean definitions fro& files
" In the class path
" >n the local file s%ste&
" At an en/iron&ent-relati/e resource path
31
-xa&ple5 *sing an Application
Context Inside a 9*nit S%ste& Test
import static org%3unit%Assert%L'
public !oid ransferSer!iceest "
pri!ate ransferSer!ice ser!ice'
7;efore public !oid set4p() "
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(/application1config%xml0)'
22 5oo> up t$e application ser!ice interface
ser!ice & (ransferSer!ice) context%get;ean(/transferSer!ice0)'
(
7est public !oid moneyransfer() "
Confirmation receipt &
ser!ice%transfer(ne, ?onetaryAmount(/@AA%AA0)B /80B /:0))'
assertEquals(receipt%get+e,;alance()B /9AA%AA0)'
(
)
(
ests t$e system
;ootstraps t$e system to test
32
Spring@s 8lexible 2esource
Loading Mechanis&
ApplicationContext i&ple&entations ha/e
default resource loading rules
ne, ClassPat$=mlApplicationContext(/com2acme2application1config%xml0)'

ne, FileSystem=mlApplicationContext(/C6MMetcMMapplication1config%xml0)'
NC5ASSPAO2com2acme2application1config%xml
C6MetcMapplication1config%xml
ne, =mlPebApplicationContext(/PK;1I+F2application1config%xml0)'

NO?CAQ#OO2,ebapp2my,ebapp2PK;1I+F2application1config%xml
33
Spring@s 8lexible 2esource
Loading Mechanis& 3A4
'o(e/er; default rules can be o/erridden (ith
resource loading prefixes
These prefixes can be used anywhere Spring
needs to deal (ith resources
" ?ot #ust in constructor args to application context
<arious prefixes
" classpath5
" file5
" http5
ne, =mlPebApplicationContext(/c"ass!ath-com2acme2application1config%xml0)'

NC5ASSPAO2com2acme2application1config%xml
34
Creating a Spring Application
Context fro& Multiple 8iles
A context can be configured fro& &ultiple files
Allo(s partitioning of bean definitions into
logical groups
$enerall% a best practice to separate out
BapplicationC beans fro& BinfrastructureC beans
" Infrastructure often changes bet(een en/iron&ents
" -/ol/es at a different rate
35
Mixed Configuration
-beans.
-bean id&/transferSer!ice0 class&/app%impl%ransferSer!iceImpl0.
-constructor1arg ref&/account#epository0 2.
-2bean.
-bean id&/account#epository0 class&/app%impl%JdbcAccount#epository0.
-constructor1arg ref&/dataSource0 2.
-2bean.
-bean id&/dataSource0 class&/com%oracle%3dbc%pool%Oracle*ataSource0.
-property name&/4#50 !alue&/3dbc6oracle6t$in67local$ost689:86;A+<0 2.
-property name&/user0 !alue&/moneytransfer1app0 2.
-2bean.
-2beans.
Coupled to an Oracle en!ironment
36
-beans.
-bean id&/dataSource0 class&/app%testdb%est*ataSourceFactory0 2.
-2beans.
1artitioning Configuration
-beans.
-bean id&/transferSer!ice0 class&/app%impl%ransferSer!iceImpl0.
-constructor1arg ref&/account#epository0 2.
-2bean.
-bean id&/account#epository0 class&/app%impl%JdbcAccount#epository0.
-constructor1arg ref&/dataSource0 2.
-2bean.
-2beans.
+o, substitutable for ot$er en!ironments
37
,ootstrapping in -ach
-n/iron&ent
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(ne, StringRS "
/application1config%xml0B
/test1infrastructure1config%xml0
()'
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(ne, StringRS "
/application1config%xml0B
/oracle1infrastructure1config%xml0
()'
In the test en/iron&ent
In the production >racle en/iron&ent
38
Topics in this session
'o( Spring (orks
!riting Spring bean definitions
" Configuring ob#ects
" $oing be%ond constructor instantiation
Creating a Spring application context
Summry
39
,enefits of 0ependenc%
In#ection
)our ob#ect is handed (hat it needs to (ork
" 8rees %our ob#ect fro& the burden of resol/ing its
dependencies
" Si&plifies %our code; i&pro/es code reusabilit%
1ro&otes progra&&ing to interfaces
" Conceals the i&ple&entation details of each dependenc%
I&pro/es testabilit%
" 0ependencies can be easil% stubbed out for unit testing
Allo(s for centrali+ed control o/er ob#ect lifec%cle
" >pens the door for ne( possibilities
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibit
LA,
*sing Spring to Configure an Application
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Understanding the Bean
Lifecycle
An In-depth Look at Springs Lifecycle
Management Features
2
Topics in this session
Introduction to Spring's !" n#mesp#ces
The lifecycle of a Spring application conte!t
" The initiali#ation phase
" The use phase
" The destruction phase
Bean scoping
3
Introduction to Spring$s
%ustom &ML 'amespaces
Spring pro(ides higher-le(el configuration
languages that )uild on the generic *)eans+,
language
" -ro(ide a)straction and semantic (alidation
" Simplify common configuration needs
.ach language is defined )y its o/n &ML
namespace you may import
" 0ou can e(en /rite your o/n
4
Importing a %ustom &ML
'amespace
<?xml version=1.0 encoding=UTF-8?>
<beans xmlns=h!"##$$$.s!ring%rame$or&.org#schema#beans
xmlns"xsi=h!"##$$$.$'.org#(001#)*+,chema-insance
xmlns"conex=h!"##$$$.s!ring%rame$or&.org#schema#conex
xsi"schema+ocaion=
h!"##$$$.s!ring%rame$or&.org#schema#beans
h!"##$$$.s!ring%rame$or&.org#schema#beans#s!ring-beans-(.-.xsd
h!"##$$$.s!ring%rame$or&.org#schema#conex
h!"##$$$.s!ring%rame$or&.org#schema#conex#s!ring-conex-(.-.xsd>
<.-- /o0 can no$ 0se <conex"1#> ags -->
<#beans>
2ssign names!ace a !re%ix
2ssociae names!ace $ih is ),3
5
Benefits of Using 'amespace
%onfiguration
<beans>
<bean class=org.s!ring%rame$or&.beans.%acor4.con%ig.
5ro!er45laceholder6on%ig0rer>
<!ro!er4 name=locaion val0e=#789-:;F#daaso0rce.!ro!eries #>
<#bean>
<#beans>
<beans ... >
<conex"!ro!er4-!laceholder locaion=#789-:;F#daaso0rce.!ro!eries #>
<#beans>
Before
After
<eneric bean#!ro!er4
s4nax is all ha=s available
>e?0ires remembering
%rame$or& classnames
6reaes same bean as
above@ b0 hides
%rame$or& deails
2rib0es are s!eci%ic o
he as&@ raher han
generic name#val0e !airs
6
'amespaces Summary
'amespace configuration is a)out simplification
and e!pressi(eness
" 1eneric )ean+property synta! can )e too lo/-le(el
" 2ides frame/ork details
'amespaces are defined for categories of
related frame/ork functionality
3
" aop4 )eans4 conte!t4 5ee4 5ms4 t!4 util
6e /ill use namespaces to simplify
configuration throughout this training
* an incomplete list. see http://www.springframework.org/schema/ for details
7
Topics in this session
Introduction to Spring$s &ML namespaces
$he li%ecycle o% # Spring #pplic#tion
context
" The initiali#ation phase
" The use phase
" The destruction phase
Bean scoping
8
-hases of the Application
Lifecycle
:niialiAaion Use 3esr0cion
-repares for use
Application
ser(ices
" Are created
" %onfigured
" May allocate
system resources
Application is not
usa)le until this
phase is complete
Used )y clients
Application
ser(ices
" -rocess client
re7uests
" %arry out
application
)eha(iors
88988: of the
time is spent in
this phase
Shuts do/n
Application
ser(ices
" ;elease any
system resources
" Are eligi)le for
gar)age
collection
9
Springs ;ole as a Lifecycle
Manager
For nearly any class of application
" Standalone <a(a application
" <Unit System Test
" <a(a ..= /e) application
" <a(a ..= enterprise application
Spring fits in to manage the application
lifecycle
" -lays an important role in all phases
10
Topics in this session
Introduction to Spring$s &ML namespaces
The lifecycle of a Spring application conte!t
" $he initi#li&#tion ph#se
" The use phase
" The destruction phase
Bean scoping
:niialiAaion Use 3esr0cion
11
The Lifecycle of a Spring Application
%onte!t >?@ - The Initiali#ation -hase
6hen you create a conte!t the initiali#ation
phase completes
But e!actly /hat happens in this phaseA
## 6reae he a!!licaion %rom he con%ig0raion
2!!licaion6onex conex =
ne$ 6lass5ah)ml2!!licaion6onexBne$ ,ringCD E
a!!licaion-con%ig.xml@
es-in%rasr0c0re-con%ig.xml
FGH
12
Inside The Application %onte!t
Initiali#ation Lifecycle
"o#d be#n de%initions
Initiali#e )ean instances
13
Load Bean Befinitions
The &ML files are parsed
Bean definitions are loaded into the conte!ts
9eanFacor4
I
.ach inde!ed under its id
Special 9eanFacor45os5rocessor )eans are
in(oked
I %an modify the definition of any )ean
14
2!!licaion 6onex
Load Bean Befinitions
<beans>
<bean id=rans%er,ervice J
<bean id=acco0n>e!osior4J
<#beans>
a!!licaion-con%ig.xml
<beans>
<bean id=daa,o0rce J
<#beans>
es-in%rasr0c0re-con%ig.xml
rans%er,ervice
acco0n>e!osior4
9eanFacor4
9eanFacor45os5rocessors
!os5rocessB9eanFacor4G
rans%er,ervice
acco0n>e!osior4
daa,o0rce
6an modi%4 he de%iniion o%
an4 bean in he %acor4
be%ore an4 obKecs are creaed
15
The BeanFactory-ost-rocessor
.!tension -oint
Useful for applying transformations to groups
of )ean definitions
" Before any o)5ects are actually created
Se(eral useful implementations are pro(ided
)y the frame/ork
0ou can also /rite your o/n
" Implement the BeanFactory-ost-rocessor interface
16
An .!ample
BeanFactory-ost-rocessor
I
PropertyPlaceholderConfigurer su)situtes
CD(aria)lesE in )ean definitions /ith (alues
from 9properties files
17
2o/ -roperty-laceholder%onfigurer
6orks
5ro!er45laceholder6on%ig0rer
,!ring 2!!licaion 6onex
Ba%er bean de%iniions are loadedG
!os5rocessB9eanFacor4G
9ean de%iniion
daa,o0rce
U>+=LEdaaso0rce.0rlF
0ser=LEdaaso0rce.0serF
9ean de%iniion
daa,o0rce
U>+=Kdbc"oracle"J
0ser=mone4rans%er-a!!
18
Using
-roperty-laceholder%onfigurer
<beans>
<bean id=daa,o0rce class=com.oracle.Kdbc.!ool.Mracle3aa,o0rce>
<!ro!er4 name=U>+ val0e=LEdaaso0rce.0rlF #>
<!ro!er4 name=0ser val0e=LEdaaso0rce.0serF #>
<#bean>
<bean class=org.s!ring%rame$or&.beans.%acor4.con%ig.
5ro!er45laceholder6on%ig0rer>
<!ro!er4 name=locaion val0e=#789-:;F#daaso0rce.!ro!eries #>
<#bean>
<#beans>
File $here he variable
val0es reside
datasource.url!d"c#oracle#thin#$localhost#1521#%&'(
datasource.user)oneytransfer*app
daaso0rce.!ro!eries
Nariables o re!lace
8asil4 ediable
19
Simplifying configuration /ith
*conte!tFproperty-placeholder,
<beans ... >
<bean id=daa,o0rce class=com.oracle.Kdbc.!ool.Mracle3aa,o0rce>
<!ro!er4 name=U>+ val0e=LEdaaso0rce.0rlF #>
<!ro!er4 name=0ser val0e=LEdaaso0rce.0serF #>
<#bean>
<conex"!ro!er4-!laceholder locaion=#789-:;F#daaso0rce.!ro!eries #>
<#beans>
6reaes he same 5ro!er45laceholder6on%ig0rer
bean de%iniion in a more concise %ashion
20
Inside the Application %onte!t
Initiali#ation Lifecycle
Load )ean definitions
Initi#li&e be#n inst#nces
21
Initiali#ing Bean Instances
.ach )ean is eagerly instantiated )y default
" %reated in the right order /ith its dependencies
in5ected
After dependency in5ection each )ean goes
through a post-processing phase
" 6here further configuration and initiali#ation can
occur
After post processing the )ean is fully
initiali#ed and ready for use
" Tracked )y its id until the conte!t is destroyed
22
Bean Initiali#ation Steps
9ean
:nsaniaed
3e!endencies
:nKeced
9ean 5os
5rocessed
9ean
>ead4
For Use
23
Bean -ost -rocessing
Bean post processing can )e )roken do/n into
t/o steps
" Initiali#e the )ean if instructed
" %all special 9ean5os5rocessors to perform additional
configuration
24
Bean -ost -rocessing Steps
Initi#li&e the be#n i% instructed
%all special 9ean5os5rocessors to perform
additional configuration
25
Initiali#e the Bean if
Instructed
A )ean can optionally register for one or more
initiali#ation call)acks
" Useful for e!ecuting custom initiali#ation )eha(iors
There$s more than one /ay to do it
" <S;-GHI J-ost%onstruct
" *)ean+, init-method attri)ute
" Implement Spring$s Initiali#ingBean interface
26
Bean Initiali#ation
Techni7ues
'(ostConstruct
init-method
Initiali#ingBean
27
First4 a -rimer on <S;-GHI
K%ommon AnnotationsL
<S;-GHI pro(ides a set of common annotations
for use in <a(a .. applications
" 2elps a(oid proliferation of frame/ork-specific
annotations
" Facilitates porta)ility
" Used )y .<B M9I
" Used )y Spring4 starting /ith (ersion G9H
28
<S;-GHI -rimer4 cont9
All annotations reside in the 5a(a!9annotation
package
" Included in the <BN starting in <a(a O
" A(aila)le as part of the $5a(aee-api$ 5ar for <a(a H
To name a fe/
" J-ost%onstruct
" J-reBestroy
" J;esource
Which brings us back to... initiali#ationP
" Spring makes use of these annotations to trigger
lifecycle e(ents
29
;egistering for Initiali#ation
/ith J-ost%onstruct
!0blic class Trans%er,ervice:m!l E
O5os6onsr0c
void iniBG E
## 4o0r c0som iniialiAaion code
F
F
;o resricions on
mehod name or visibili4
Tells ,!ring o call his
mehod a%er
de!endenc4 inKecion
This is the preferred initiali#ation techni7ue
" Fle!i)le4 a(oids depending on Spring A-Is
" ;e7uires Spring G9H or )etter
30
.na)ling %ommon Annotation-
Based Initiali#ation
J-ost%onstruct /ill )e ignored unless Spring is
instructed to detect and process it
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice:m!l #>
<bean class=org.s!ring%rame$or&.conex.annoaion.
6ommon2nnoaion9ean5os5rocessor #>
<#beans>
3eecs and invo&es an4
mehods annoaed $ih
O5os6onsr0c
31
Simplifying %onfiguration /ith
*conte!tFannotation-config,
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice:m!l #>
<conex"annoaion-con%ig#>
<#beans>
8nables m0li!le 9ean5os5rocessors@ incl0ding"
>e?0ired2nnoaion9ean5os5rocessor
6ommon2nnoaion9ean5os5rocessor
32
Bean Initiali#ation
Techni7ues
J-ost%onstruct
init-method
Initiali#ingBean
33
Initiali#ing a Bean 0ou Bo
'ot %ontrol
Use init-method to initiali#e a )ean you do not
control the implementation of
<bean id=bro&er
class=org.a!ache.acivem?.bro&er.9ro&er,ervice
ini-mehod=sar>
J
<#bean>
*ehod m0s be !0blic $ih no arg0mens
6lass $ih no ,!ring de!endenc4
34
Bean Initiali#ation
Techni7ues
J-ost%onstruct
init-method
Initi#li&ing)e#n
35
;egistering for an Initiali#ation
%all)ack /ith Initiali#ingBean
Initiali#ation techni7ue used prior to Spring G9H
" ;e7uires implementing a Spring-specific interface
" Fa(or use of J-ost%onstruct if possi)le
!ac&age org.s!ring%rame$or&.beans.%acor4H
!0blic iner%ace :niialiAing9ean E
!0blic void a%er5ro!eries,eBGH
F
36
!0blic class *essage>eceiver im!lemens :niialiAing9ean E
!0blic void a%er5ro!eries,eBG E
## allocae message receiving reso0rces
F
F
<beans>
<bean id=message>eceiver class=exam!le.*essage>eceiver #>
<#beans>
:m!lemens
s!ecial ,!ring
li%ec4cle iner%ace
,!ring invo&es mehod a0omaicall4
;o oher con%ig0raion re?0ired
;egistering for an Initiali#ation
%all)ack /ith Initiali#ingBean
37
Bean -ost -rocessing Steps
Initiali#e the )ean if instructed
C#ll speci#l %eanPostProcessors to per%orm
#ddition#l con%igur#tion
38
The Bean-ost-rocessor
.!tension -oint
An important e!tension point in Spring
%an modify )ean instances in any /ay
" -o/erful ena)ling feature
Se(eral implementations are pro(ided )y the
frame/ork
'ot common to /rite your o/n
39
An .!ample
Bean-ost-rocessor
;e7uiredAnnotationBean-ost-rocessor
" -ro(ided )y the frame/ork
" .nforces that '*e+uired properties are set
" Must )e e!plicitly ena)led (ia configuration
40
Using
;e7uiredAnnotationBean-ost-rocessor
!0blic void Trans%er,ervice:m!l im!lemens Trans%er,ervice E
!rivae 2cco0n>e!osior4 acco0n>e!osior4H
O>e?0ired
!0blic void se2cco0n>e!osior4B2cco0n>e!osior4 arG E
his.acco0n>e!osior4 = arH
F
F
:ndicaes he de!endenc4
is re?0ired
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice:m!l #>
<bean class=org.s!ring%rame$or&.beans.%acor4.annoaion.
>e?0ired2nnoaion9ean5os5rocessor #>
<#beans>
20omaicall4 deecedH no oher con%ig0raion is necessar4
41
Simplifying %onfiguration
/ith *conte!tFannotation-config,
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice:m!l #>
<conex"annoaion-con%ig#>
<#beans>
20omaicall4 enables >e?0ired2nnoaion9ean5os5rocessor
;emem)er *conte!tFannotation-config,A
42
Topics in this session
Introduction to Spring$s &ML namespaces
The lifecycle of a Spring application conte!t
" The initiali#ation phase
" $he use ph#se
" The destruction phase
Bean scoping
Use 3esr0cion :niialiAaion
43
The Lifecycle of a Spring Application
%onte!t >G@ - The Use -hase
6hen you in(oke a )ean o)tained from the
conte!t the application is used
But e!actly /hat happens in this phaseA
2!!licaion6onex conex = ## ge i %rom some$here
## +oo&0! he enr4 !oin ino he a!!licaion
Trans%er,ervice service =
BTrans%er,erviceG conex.ge9eanBrans%er,erviceGH
## Use i.
service.rans%erBne$ *onear42mo0nB-0.00G@ 1@ (GH
44
Inside The Bean ;e7uest
>Use@ Lifecycle
If the )ean is 5ust your ra/ o)5ect it is simply
in(oked directly >nothing special@
If your )ean has )een /rapped in a pro!y
things get more interesting
Trans%er,ervice:m!l
rans%erBL-0@ 1@ (G
rans%erBL-0@ 1@ (G
Trans%er,ervice:m!l
,!ring 5rox4
45
-ro!y -o/er
A 9ean5os5rocessor may /rap your )eans in a
dynamic pro!y and add )eha(ior to your
application logic transparently
Trans%er,ervice:m!l
rans%erBL-0@ 1@ (G
,!ring
Transacion:nerce!or
Transacion*anager
begin commi
Transacion
managemen
behavior is added
aro0nd 4o0r code
,!ring 5rox4
46
-ro!ies are %entral to the Spring
Triangle
Simple
Object
,
e
p
e
n
d
e
n
c
y

I
n
-
e
c
t
i
o
n
.
s
p
e
c
t
-
/
r
i
e
n
t
e
d

(
r
o
g
r
#
m
m
i
n
g
0nterprise Ser1ice .bstr#ctions
1. The 2!!licaion
conex drives bean
con%ig0raion
(. 34namic !roxies
add behaviors o
4o0r beans
'. ,!ring can inegrae man4
ener!rise behaviors
47
Bean Initiali#ation Steps
9ean
:nsaniaed
3e!endencies
:nKeced
9ean 5os
5rocessed
9ean
>ead4
For Use
5roxies are
creaed here
48
Topics in this session
:niialiAaion
Introduction to Spring$s &ML namespaces
The lifecycle of a Spring application conte!t
" The initiali#ation phase
" The use phase
" $he destruction ph#se
Bean scoping
Use 3esr0cion
49
The Lifecycle of a Spring Application
%onte!t >M@ - The Bestruction -hase
6hen you close a conte!t the destruction
phase completes
But e!actly /hat happens in this phaseA
6on%ig0rable2!!licaion6onex conex = J
## 3esro4 he a!!licaion
conex.closeBGH
50
Inside the Application
%onte!t Bestruction Lifecycle
Bestroy )ean instances if instructed
Bestroy itself
" The conte!t is not usa)le again
51
Bestroy Bean Instances if
Instructed
A )ean can optionally register for one or more
destruction call)acks
" Useful for releasing resources and $cleaning up$
There$s more than one /ay to do it
" <S;-GHI J-reBestroy
" *)ean+, destroy-method attri)ute
" Implement Spring$s Bisposa)leBean interface
52
Bean Bestruction Techni7ues
'(re,estroy
destroy-method
Bisposa)leBean
53
;egistering for Bestruction
/ith J-reBestroy
!0blic class Trans%er,ervice:m!l E
O5re3esro4
void release>eso0rcesBG E
## 4o0r c0som desr0cion code
F
F
;o resricions on mehod
name or visibili4
Tells ,!ring o call his
mehod !rior o desro4ing he
bean insance
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice:m!l #>
<conex"annoaion-con%ig#>
<#beans>
8nables common annoaion
!rocessing
54
Bean Bestruction Techni7ues
J-reBestroy
destroy-method
Bisposa)leBean
55
Bestroying a Bean 0ou Bo
'ot %ontrol
Use destroy-method to dispose a )ean you do
not control the implementation of
<bean id=daa,o0rce
class=org.a!ache.commons.dbc!.9asic3aa,o0rce
desro4-mehod=close>
J
<#bean>
*ehod m0s be !0blic $ih no arg0mens
6lass $ih no ,!ring de!endenc4
56
Bean Bestruction Techni7ues
J-reBestroy
destroy-method
,ispos#ble)e#n
57
;egistering for a Bestruction
%all)ack /ith Bisposa)leBean
;egister for a )ean destruction call)ack )y
implementing the +isposa"le%ean interface
Spring in(okes this method at the right time
!ac&age org.s!ring%rame$or&.beans.%acor4H
!0blic iner%ace 3is!osable9ean E
!0blic void desro4BGH
F
58
Topics in this session
Introduction to Spring$s &ML namespaces
The lifecycle of a Spring application conte!t
" The initiali#ation phase
" The use phase
" The destruction phase
)e#n scoping
59
Bean Scoping
Spring puts each )ean instance in a scope
Singleton scope is the default
" The KsingleL instance is scoped )y the conte!t itself
" By far the most common
Qther scopes can )e used on a )ean-)y-)ean
)asis
<bean id=m49ean class=exam!le.*49ean
sco!e=J>
<#bean>
50 his bean in some oher sco!e
60
A(aila)le Scopes
I
prototype - A ne/ instance is created each time
the )ean is referenced
I
session - A ne/ instance is created once per
user session
I
re,uest - A ne/ instance is created once per
re7uest
I
custo) - 0ou define your o/n rules
" Ad(anced feature
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
LAB
Understanding the Bean Lifecycle
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Simplifying Application
Configuration
Techniques for Creating Reusable and
Concise Bean Definitions
2
Topics in this session
Bean e!inition "nheritance
Inner Beans
Property ditors
Importing Configuration !iles
Bean "aming
The p "amespace
The util "amespace
3
Bean Definition Inheritance
#$%
Sometimes se&eral beans need to be
configured in the same 'ay
(se bean definition inheritance to define the
common configuration once
) Inherit it 'here needed
4
*ithout Bean Definition
Inheritance
<beans>
<bean id=pool-A class=com.oracle.jdbc.pool.OracleDataSource>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-a"%&'%"(A)* +>
<property name=user !alue=moneytrans,er-app +>
<+bean>
<bean id=pool-( class=com.oracle.jdbc.pool.OracleDataSource>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-b"%&'%"(A)* +>
<property name=user !alue=moneytrans,er-app +>
<+bean>

<bean id=pool-- class=com.oracle.jdbc.pool.OracleDataSource>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-c"%&'%"(A)* +>
<property name=user !alue=moneytrans,er-app +>
<+bean>
<+beans>
-an you ,ind t#e duplication.
5
*ith Bean Definition
Inheritance
<beans>
<bean id=abstract/ool
class=com.oracle.jdbc.pool.OracleDataSource abstract=true>
<property name=user !alue=moneytrans,er-app +>
<+bean>
<bean id=pool-A parent=abstractPool>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-a"%&'%"(A)* +>
<+bean>
<bean id=pool-( parent=abstractPool>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-b"%&'%"(A)* +>
<+bean>
<bean id=pool-- parent=abstractPool>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-c"%&'%"(A)* +>
<+bean>
<+beans>
0ill not be instantiated
1ac# pool in#erits its parent con,i2uration
6
+&erriding Parent Bean Configuration
<beans>
<bean id=de,ault/ool class=com.oracle.jdbc.pool.OracleDataSource>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-a"%&'%"(A)* +>
<property name=user !alue=moneytrans,er-app +>
<+bean>
<bean id=pool-( parent=de,ault/ool>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-b"%&'%"(A)* +>
<+bean>
<bean id=pool-- parent=de,ault/ool class=e3ample.SomeOt#er/ool>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-c"%&'%"(A)* +>
<+bean>
<+beans>
)ot abstract4 acts as a concrete de,ault
O!errides class as 5ell
O!errides UR property
7
Topics in this session
Bean Definition Inheritance
"nner Beans
Property ditors
Importing Configuration !iles
Bean "aming
The p "amespace
The util "amespace
8
Inner Beans
Sometimes a bean naturally scopes the
definition of another bean
) The ,scoped- bean is not useful to anyone else
.a/e the scoped bean an inner bean
) .ore manageable
) A&oids polluting the bean namespace
9
*ithout an Inner Bean
<beans>
<bean id=restaurantRepository
class=re5ards.internal.restaurant.6dbcRestaurantRepository>
<property name=dataSource re,=dataSource +>
<property name=bene,itA!ailability/olicy7actory re,=,actory +>
<+bean>
<bean id=,actory
class=re5ards.internal.restaurant.a!ailability.
De,ault(ene,itA!ailability/olicy7actory>
<constructor-ar2 re,=re5ard8istorySer!ice +>
<+bean>
9
<+beans>
-an be re,erenced by ot#er beans
:e!en i, it s#ould not be;
10
*ith an Inner Bean
<beans>
<bean id=restaurantRepository
class=re5ards.internal.restaurant.6dbcRestaurantRepository>
<property name=dataSource re,=dataSource +>
<property name=bene,itA!ailability/olicy7actory>
<bean class=re5ards.internal.restaurant.a!ailability.
De,ault(ene,itA!ailability/olicy7actory>
<constructor-ar2 re,=re5ard8istorySer!ice +>
<+bean>
<+property>
<+bean>
9
<+beans>
<nner bean #as no id :it is anonymous;
-annot be re,erenced outside t#is scope
11
<beans>
<bean id=restaurantRepository
class=re5ards.internal.restaurant.6dbcRestaurantRepository>
<property name=dataSource re,=dataSource +>
<property name=bene,itA!ailability/olicy7actory>
<bean class=re5ards.internal.restaurant.a!ailability.
De,ault(ene,itA!ailability/olicy7actory>
<constructor-ar2>
<bean class=re5ards.internal.re5ards.6dbcRe5ard8istory>
<property name=dataSource re,=dataSource +>
<+bean>
<+constructor-ar2>
<+bean>
<+property>
<+bean>
<+beans>
.ultiple 0e&els of "esting
12
Topics in this session
Bean Definition Inheritance
Inner Beans
#roperty $ditors
Importing Configuration !iles
Bean "aming
The p "amespace
The util "amespace
13
Introducing Propertyditor
#$%
In 1.0 all literal &alues are te2t strings
In your code there are often rich ob3ect types
<bean id=p#one=alidator class=sample./#one=alidator>
<property name=pattern !alue=>?-@ABCD->?-@ABCD->?-@ABED +>
<+bean>
public class /#one=alidator B
pri!ate /attern pattern4
public !oid set/attern:/attern pattern; B
t#is.pattern = pattern4
D
D
A ric# object 5it# be#a!ior
A te3t strin2
14
Introducing Propertyditor
#4%
5our code should not be burdened 'ith the
responsibility of type con&ersion
Spring 'ill con&ert for you using a PropertyEditor
) Comes 'ith many property editors pre6installed
) 5ou may 'rite and install your o'n
15
Built6In Propertyditor
implementations
See the or2.sprin2,rame5orF.beans.propertyeditor
pac/age
Some highlights
G )umber1ditor con&erts to the "umber types
G (oolean1ditor con&erts to Boolean
G Date1ditor con&erts to 3a&a7util7Date
G Resource1ditor con&erts to a Resource
G /roperties1ditor con&erts to 3a&a7util7Properties
G (yteArray1ditor con&erts to a byte89
G ocale1ditor con&erts to a 0ocale
16
Built6In Propertyditor
2ample
<bean id=session7actory
class=or2.sprin2,rame5orF.orm.#ibernateC.support.
ocalSession7actory(ean>
9
<property name=#ibernate/roperties>
<!alue>
#ibernate.,ormatHsIl=true
#ibernate.jdbcHbatc#HsiJe=C?
<+!alue>
<+property>
<+bean>
public class ocalSession7actory(ean B
public !oid set8ibernate/roperties:/roperties p; B 9
D
Strin2-encoded properties
Kyped ja!a.util./roperties object
17
Implementing 5our +'n
Propertyditor
Create a custom editor by e2tending /roperty1ditorSupport
+&erride setAsKe3t:Strin2; to con&ert from String
+&erride 2etAsKe3t:; to format the &alue #optional%
public class /attern1ditor e3tends /roperty1ditorSupport B
public !oid setAsKe3t:Strin2 te3t; B
set=alue:te3t L= null . /attern.compile:te3t; " null;4
D
public Strin2 2etAsKe3t:; B
/attern !alue = :/attern; 2et=alue:;4
return :!alue L= null . !alue.pattern:; " ;4
D
D
-on!erts ,rom Strin2
18
Installing your Custom
Property ditor
(se a -ustom1ditor-on,i2urer to install your
custom editor #a (ean7actory/ost/rocessor%
<bean class=or2.sprin2,rame5orF.beans.,actory.con,i2.
-ustom1ditor-on,i2urer>
<property name=custom1ditors>
<map>
<entry Fey=ja!a3.util.re2e3./attern
!alue=e3ample./attern1ditor +>
<+map>
<+property>
<+bean>
7ully-Iuali,ied con!ertible type
K#e /roperty1ditor to
per,orm con!ersions
to t#at type
*A PatternEditor implementation is built-in as of Spring 2.0.1
19
Topics in this session
Bean Definition Inheritance
Inner Beans
Property ditors
"mporting Con!iguration %iles
Bean "aming
The p "amespace
The util "amespace
20
Importing Configuration !iles
#$%
(se the import tag to encapsulate including
another configuration file
<beans>
<import resource=accounts+account-con,i2.3ml +>
<import resource=restaurant+restaurant-con,i2.3ml +>
<import resource=re5ards+re5ards-con,i2.3ml +>
<+beans>
application-con,i2.3ml
<beans>
<import resource=application-con,i2.3ml+>
<bean id=dataSource class=e3ample.KestDataSource7actory +>
<+beans>
system-test-con,i2.3ml
ne5 -lass/at#MmlApplication-onte3t:system-test-con,i2.3ml;4
-lient only imports one ,ile
21
Importing Configuration !iles
#4%
Promotes splitting configuration into logical groups of
bean definitions
nables reuse across modules 'ithin an application
Compliments the option of creating an
ApplicationConte2t from multiple files
Application-onte3t conte3t =
ne5 -lass/at#MmlApplication-onte3t:
ne5 Strin2>A B
classpat#"+module%+module-con,i2.3mlN
classpat#"+module'+module-con,i2.3ml
D;4
22
Topics in this session
Bean Definition Inheritance
Inner Beans
Property ditors
Importing Configuration !iles
Bean &aming
The p "amespace
The util "amespace
23
Bean "aming
.ost beans are assigned a unique name 'ith the id
attribute
As an 1.0 ID this attribute has se&eral limitations
) Can only hold a single &alue
) Some special characters cannot be used #' (%
<bean id=dataSource 9+>
<bean id=dataource!a 9+>
O+P not allo5ed
24
Assigning a Bean .ultiple
"ames
(se the name attribute 'hen special characters
are needed
Also consider it 'hen you need to assign a
bean multiple names
<bean name=dataSource+primary 9+>
<bean name=dataSourceN dataSource+primary 9+>
25
Topics in this session
Bean Definition Inheritance
Inner Beans
Property ditors
Importing Configuration !iles
Bean "aming
)he p &amespace
The util "amespace
26
Shortcut to specifying bean
properties
After:
<bean name=e3ample class=com.,oo.13ample>
<property name=email !alue=,oo$,oo.com+>
<+bean>
<bean name=e3ample class=com.,oo.13ample
p"email=,oo$,oo.com+>
The p namespace allo's properties to be set as
an attribute to the bean definition
Before:
27
Shortcut to specifying bean
references
<bean name=e3ample class=com.,oo.13ample>
<property name=dataSource re,=dataSource+>
<+bean>
<bean name=e3ample class=com.,oo.13ample
p"dataSource-re,=dataSource+>
References to other beans require the format
p:<property-name>-ref=<reference>
Before:
After:
28
Considerations of the p
namespace
Requires a namespace definition:
"amespace not specified in an 1SD file; unli/e
other Spring namespaces
) So no e2tra schema0ocation entry required
3mlns"p=#ttp"++555.sprin2,rame5orF.or2+sc#ema+p
29
Topics in this session
Bean Definition Inheritance
Inner Beans
Property ditors
Importing Configuration !iles
Bean "aming
The p "amespace
)he util &amespace
30
Spring<s (til "amespace
*util('+ is one of the ,out6of6the6bo2- namespaces you
can import
+ffers high6le&el configuration for common utility tas/s
) Populating collections
) Accessing constants #static fields%
) 0oading properties
Before this namespace you 'rote more to do the same
thing
) (sing internal concepts li/e !ieldRetrie&ing!actoryBean
31
Configuring a 0ist
<bean id=in!entoryQana2er class=,oo.Qy<n!entoryQana2er>
<property name=5are#ouses>
<util"list>
<re, bean=primary0are#ouse +>
<re, bean=secondary0are#ouse +>
<bean class=,oo.0are#ouse 9+>
<+util"list>
<+property>
<+bean>
<bean id=primary0are#ouse ...+>
<bean id=secondary0are#ouse ...+>
1lements are beans :one inner;
ist is an inner bean
32
Configuring a Set
<bean id=noti,icationSer!ice class=,oo.Qy)oti,icationSer!ice>
<property name=subscribers re,=subscribers+>
<+bean>
<util"set id=subscribers>
<!alue>larry$,oo.com<+!alue>
<!alue>curly$,oo.com<+!alue>
<!alue>moe$,oo.com<+!alue>
<+util"set>
1lements are literal !alues
Set is a top-le!el bean
33
Configuring a .ap #$%
<bean id=in!entoryQana2er class=,oo.Qy<n!entoryQana2er>
<property name=5are#ouses>
<util"map>
<entry Fey=primary !alue-re,=primary0are#ouse +>
<entry Fey=secondary>
<bean class=,oo.0are#ouse 9+>
<+entry>
<+util"map>
<+property>
<+bean>
<bean id=primary0are#ouse ...+>
=alue is a top-le!el bean
=alue is an inner bean
34
Configuring a .ap #4%
<bean id=in!entoryQana2er class=,oo.Qy<n!entoryQana2er>
<property name=5are#ouses>
<util"map>
<entry>
<Fey>
<bean class=,oo.0are#ouse*ey>
<constructor-ar2 !alue=%'CE&RST@ +>
<+bean>
<+Fey>
<bean class=,oo.0are#ouse 9+>
<+entry>
<+util"map>
<+property>
<+bean>
*ey is an inner bean
35
Accessing Constants
<bean id=noti,icationSer!ice
class=e3ample.Qy)oti,icationSer!ice>
<property name=#ostname>
<util"constant static-,ield=e3ample.Qy-onstants.8OSKH)AQ1 +>
<+property>
<+bean>
Accesses static ,ield in t#e Qy-onstants class
36
0oading Properties
<bean id=noti,icationSer!ice
class=e3ample.Qy)oti,icationSer!ice>
<property name=emailQappin2s>
<util"properties location=classpat#"mail.properties +>
<+property>
<+bean>
oads a ja!a.util./roperties ,rom t#e location
37
Summary
Spring offers many techniques to simplify
configuration
) *e=&e seen 3ust a fe' here
) It=s about e2pressi&eness and elegance; 3ust li/e code
Don=t repeat yourself>
) (se bean inheritance if you=re seeing repetiti&e 1.0
Consider hiding lo'6le&el beans
) (se inner beans 'here it=s natural to do so
A&oid monolithic configuration
) (se *import'+ to aid in modulari?ing your 1.0
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Annotation-Based
Dependency Injection
Introducing Springs Annotations for
Dependency Injection
2
Topics in this Session
Annotation Quick Start
All Configuration Annotations
Suary
3
!o" Spring #orks
Spring
Application Context
Configuration
Instructions
Your Application Classes (POJOs)
Fully configured
application system
Ready for use
Creates
4
The Approach $oure %sed to
public class ransferSer!iceImpl implements ransferSer!ice "
public ransferSer!iceImpl(Account#epository ar) "
t$is%account#epository & ar'
(
)
(
public class JdbcAccount#epository implements Account#epository "
public JdbcAccount#epository(*ataSource ds) "
t$is%dataSource & ds'
(
)
(
+eeded to load accounts from t$e database
+eeded to perform money transfers
bet,een accounts
5
The Approach $oure %sed to
-beans.
-bean id&/transferSer!ice0 class&/app%impl%ransferSer!iceImpl0.
-constructor1arg ref&/account#epository0 2.
-2bean.
-bean id&/account#epository0 class&/app%impl%JdbcAccount#epository0.
-constructor1arg ref&/dataSource0 2.
-2bean.
-bean id&/dataSource0 class&/com%oracle%3dbc%pool%Oracle*ataSource0.
-property name&/4#50 !alue&/3dbc6oracle6t$in67local$ost689:86;A+<0 2.
-property name&/user0 !alue&/moneytransfer1app0 2.
-2bean.
-2beans.
6
The Annotation-Based Approach
public class ransferSer!iceImpl implements ransferSer!ice "
@Autowired
public ransferSer!iceImpl(Account#epository ar) "
t$is%account#epository & ar'
(
)
(
public class JdbcAccount#epository implements Account#epository "
@Autowired
public JdbcAccount#epository(*ataSource ds) "
t$is%dataSource & ds'
(
)
(
Spring6 =automatically try to ,ire t$is>?
7
The Annotation-Based Approach
-beans.
-bean id&/transferSer!ice0
class&/app%impl%ransferSer!iceImpl02.
-bean id&/account#epository0
class&/app%impl%JdbcAccount#epository02.
-bean id&/dataSource0 class&/com%oracle%3dbc%pool%Oracle*ataSource0.
-property name&/4#50 !alue&/3dbc6oracle6t$in67local$ost689:86;A+<0 2.
-property name&/user0 !alue&/moneytransfer1app0 2.
-2bean.
-context6annotation1config2.
-2beans.
+o more need to
specify
constructor1args
8
%sage - &othing Changes'
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$@mlApplicationContext(/application1config%xml0)'
22 5ooA up t$e application ser!ice interface
ransferSer!ice ser!ice &
(ransferSer!ice) context%get;ean(/transferSer!ice0)'
22 4se t$e application
ser!ice%transfer(ne, BonetaryAmount(/CDD%DD0E /80)E /:0)'
9
Quick Start Suary
Spring container needs ()*)s and "iring
instructions to asse+le your application
#iring instructions can +e pro,ided in -./0
0+ut also using annotations0
0or a co+ination of the t"o
10
Topics in this Session
Annotation Quick Start
Configuration nnotations
Suary
11
Configuration Annotations
1Auto"ired
12esource
1Coponent 3 12epository
1(ostConstruct 3 1(reDestroy 3 12e4uired
5 As sho"n earlier
12
1Auto"ired
Asks Spring to auto"ire fields6 ethods or
constructors +y using the type
5 2e4uires uni4ue atch'

2eo,es the need to specify constructor-arg


or property eleents in -./
public class ransferSer!iceImpl implemets ransferSer!ice
@Autowired
public ransferSer!iceImpl(Account#epository ar) "
t!is%account#epository & ar'
(
)
(
13
1Auto"ired
.ethods can ha,e any nae
.ethods and constructors can ha,e ultiple
arguents that "ill all +e injected
public class BySer!iceImpl implemets BySer!ice
@Autowired
public "oid initialiFe(Some*ependency sdE Ot$er*ependency od) "
t!is%some*ependency & sd'
t!is%ot$er*ependency & od'
(
)
(
14
1Auto"ired #orks 7or
Collections Too'
*ust include a typed Collection to o+tain a
reference to all +eans of a certain type
public class ransferSer!iceImpl implemets ransferSer!ice
@Autowired
public ransferSer!iceImpl(5ist-Account#epository. repos) "
t!is%repositories & repos'
(
)
(
In3ects all beans of type Account#epository
a!ailable in t$e ApplicationContext
15
)ptional 1Auto"iring
%sing the re4uired eleent6 specify "hether or
not Spring should fail if no instance "as found
Defaults to true
@Autowired#re$uired%false&
pri"ate Account#epository account#epository'
(ro,ides nice "ay of specifying defaults
@Autowired#re$uired%false&
pri"ate Account#epository account#epository &
ew *efaultAccount#epository()'
16
Disa+iguation "ith 1Auto"ired
Although not often needed6 1Auto"ired
pro,ides disa+iguation features
&eeded in case ultiple instances of the sae
type e8ist6 one of "hich needs to +e injected
%sing 1Qualifier you can inject +eans +y nae
7Auto,ired
@'ualifier#(primary)ata*ource+&
pri!ate *ataSource dataSource'
Specify name of
bean to in3ect
17
12esource 9:yBean&ae:;
*S2-<=> annotation 9not Spring-specific;
Injects a +ean identified +y the gi,en nae
%seful "hen auto"iring +y type does not "ork
Can also lookup *&DI references
public class ransferSer!iceImpl implemets ransferSer!ice "
@Resource(Gmy;acAup#epositoryG)
public "oid set;acAup#epo(Account#epository repo) "
t!is%bacA#epo & repo'
(
(
18
12esource in Spring
Soe additional +eha,ior o,er *a,a ?? =@
By default6 falls +ack to auto"iring +y type if no
+ean "ith gi,en nae e8ists
#orks for all methods6 not just setters
5 But not for constructors'
19
7or these Annotations to
#ork0
-beans xmlns&G$ttp622,,,%springframe,orA%org2sc$ema2beansG
xmlns6xsi&G$ttp622,,,%,C%org2:DD82@B5Sc$ema1instanceG
xmlns6context&G$ttp622,,,%springframe,orA%org2sc$ema2contextG
xsi6sc$ema5ocation&G$ttp622,,,%springframe,orA%org2sc$ema2beans
$ttp622,,,%springframe,orA%org2sc$ema2beans2spring1beans1:%9%xsd
$ttp622,,,%springframe,orA%org2sc$ema2context
$ttp622,,,%springframe,orA%org2sc$ema2context2spring1context1:%9%xsdG.
,cote-t.aotatio/cofi012
-bean id&/transferSer!ice0 class&/transfer%ransferSer!ice02.
-bean id&/account#epository0 class&/transfer%JdbcAccount#epository02.
-2beans.
urns on c$ecAing of *I
annotations for beans declared
in t$is context
#e need to Aena+le the
20
1Coponent
Identifies ()*)s as Spring Beans
2eo,es the need to specify almost anything in -./
)ptionally pass it a String6 "hich "ill +e the +ean nae
Default +ean nae is de-capitaliBed non-4ualified nae
@3ompoet
public class ransferSer!iceImpl implemets ransferSer!ice
7Auto,ired
public ransferSer!iceImpl(Account#epository ar) "
t!is%account#epository & ar'
(
)
(
21
1Coponent and naes
1Coponent takes a String that naes the +ean
Argua+ly not a +est practice to put +ean naes in your
*a,a code
@3ompoet#(my4rasfer*er"ice+&
public class ransferSer!iceImpl implemets ransferSer!ice
7Auto,ired
public ransferSer!iceImpl(Account#epository ar) "
t!is%account#epository & ar'
(
)
(
22
7or This Annotation To #ork0
#e need to ena+le Acoponent scanning
5 Auto-ena+les Cconte8t@annotation-config3D
-beans xmlns&G$ttp622,,,%springframe,orA%org2sc$ema2beans0
xmlns6xsi&G$ttp622,,,%,C%org2:DD82@B5Sc$ema1instanceG
xmlns6context&G$ttp622,,,%springframe,orA%org2sc$ema2contextG
xsi6sc$ema5ocation&G$ttp622,,,%springframe,orA%org2sc$ema2beans
$ttp622,,,%springframe,orA%org2sc$ema2beans2spring1beans1:%9%xsd
$ttp622,,,%springframe,orA%org2sc$ema2context
$ttp622,,,%springframe,orA%org2sc$ema2context2spring1context1:%9%xsdG.
,cote-t.compoet/sca base/pac5a0e%(trasfer+12
-2beans.
+o more need to mention t$e
beans in t$e application context
23
1Scope
1Scope allo"s you to custoiBe the instantiation
strategy to EprototypeE6 Ere4uestE6 EsessionE or any other
9possi+ly custo; scope
@*cope#(prototype+& @3ompoet
public class ransferSer!iceImpl implemets ransferSer!ice
7Auto,ired
public ransferSer!iceImpl(Account#epository ar) "
t!is%account#epository & ar'
(
)
(
24
1Coponent Is A .eta-Annotation
Allo"s introduction of custo annotation +eing
picked up +y the coponent scanner
pac5a0e com%mycompany%util'
@3ompoet
@Retetio(#etentionPolicy%RUNTIME)
public @iterface ByCustomComponent "
(
@6y3ustom3ompoet
public class ransferSer!iceImpl implemets ransferSer!ice
)
(
25
Including F ?8cluding Beans
%sing filters6 "e can include or e8clude +eans6
+ased on type or class-le,el annotation
-context6component1scan base1pacAage&Gre,ardsG.
-context6include1filter type&GregexG
expression&G%HStub%H#epositoryG2.
-context6exclude1filter type&GannotationG
expression&Gorg%springframe,orA%stereotype%#epositoryG2.
-2context6component1scan.
26
#hen use "hatG
Start using annotations for sall isolated parts
of your application 9Spring 1.HC controllers;
Annotations are spread across your code +ase
-./ is centraliBed in one 9or a fe"; places
-./ for infrastructure and ore EstaticE +eans
Annotations for fre4uently changing +eans
Spring ID? does not 9yet; fully support
1Auto"ired and 1Coponent
27
Topics in this Session
Annotation Quick Start
All Configuration Annotations
Summary
28
Suary
Springs configuration directi,es can +e "ritten
in -./ or using annotations
$ou can i8 and atch -./ and annotations
as you please
1Auto"ired and 1Coponent allo" for alost
epty configuration files
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
/AB
%sing Springs annotations to Configure and
test an application
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;
}
}
}
$%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;
}
}
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*));
}
}
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);
}
}
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
locations using the locations propert& 6b&
de"ault Spring loads con"ig.5!l "ro! the sa!e
package7
Use FAutowired annotations as be"ore
@ContextConfiguration(locations={89trans!er:con!ig.%ml8})
@RunWith(Spring;'nit<6lass7unner.class)
public class -rans!erService-est {
@uto!ire" -rans!erService service-o-est;
}
27
Using Spring4s test support
.7un5ith(Spring;'nit<6lass7unner.class)
.6onte%t6on!iguration(locations={)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
)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 Gueues
29
Su!!ar&
Testing is an essential part o" any
develop!ent
Unit testing tests a class in isolation where
e5ternal dependencies should be !ini!iHed
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
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' (
+
(
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+
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
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 pat
t#pe name metod name
metod params
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 taes a single parameter
e$ecution(5;a0a$%annotation%securit#%RolesAllowed 0oid 8%%send8(%%))
" An, void method starting with send and 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
Advice T,pes8 After
AfterAd0ice !ro$# 6arget
"uccessful return or &$ception
40
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
41
Advice T,pes8 Around
AroundAd0ice !ro$# 6arget
proceed()
42
Around Advice E$ample
5Around(7e$ecution(8 rewards%ser0ice%%8%8(%%))9)
public Bb;ect cace(!roceedingFoin!oint point) {
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# ser0ices
!roceed onl# if not alread# caced
=se @Around annotation
" ProceedingJoinPoint parameter
" !nherits from JoinPoint and adds the proceed() method
43
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.-
" Eas, to learn once annotation s,nta$ is
understood
44
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
45
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
47
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
48
#amed pointcuts
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() {(
(
49
#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
50
#amed Pointcuts - Summar,
+ive the possi&ilit, to &rea one complicated
e$pression into several su&-e$pressions
Allow pointcut e$pression reusa&ilit,
0est practice8 e$ternali*e pointcut e$pressions
into one dedicated class
51
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
52
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,
53
Conte$t Selecting E$ample
Consider this &asic re2uirement
/og a message e0er# time "er0er is about to start
public interface "er0er {
public 0oid start(,ap input)'
public 0oid stop()'
(
In te ad0ice- ow do we access "er0erN ,apN
54
%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
55
%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$#
56
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
57
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
58
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
59
E$ample
5"ecured(allowedRoles){7teller9-9manager9()
public 0oid wai0eFee () {
+
(
Requirements:
Run a securit# ceck before an# 5"ecured ser0ice operation
"ecurit# logic depends on:

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


60
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())'
(
Run a securit# ceck before an# 5"ecured ser0ice operation
=se of the annotation() designator
61
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) {(
Run a securit# ceck before an# 5"ecured ser0ice operation
62
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 "#
63
-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 0 on
the same class@interfaceD advice will never &e
e$ecuted for method 0
64
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
" The three advice t,pes are &eforeD afterD 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
! 2aa Data 5#6ects 32D54
! 5racle Toplin"
! 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 ma6or data
access technologies
9 :&'& ,&t&b&(e Connecti'ity (:,;C!
9 %p&c4e i;&ti(
9 :;o(( Hibern&te
9 :&'& <er(i(tence %rc4itecture (:<%!
9 :&'& ,&t& Object( (:,O!
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 DA5s
! A helper called a data access template to help you
use the pu#lic API effectiely
2
2D)C DA5 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
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#6ect 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
! 5ften 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 ma6or data
access technologies
! 2D)C
! 2aa Persistence API 32PA4
! 2aa Data 5#6ects 32D54
! '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#6ects that encapsulate domain
#ehaiors
32
The (ayers *or"ing Together
at 8se Time 3>4
A serice continues processing
! )y e$ecuting #usiness logic
! 5ften #y coordinating #etween domain o#6ects loaded
#y repositories
And finally+ completes processing
! )y updating changed data and committing the
transaction
! Some technologies apply repository updates for you
35R%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(
43
Spring Data Access Support
%atri$
"urpose #!$C %ibernte Top&in'
Technology
configurtion
support
Seeral local
DataSource
implementations@
2,DI loo"up
support
(ocalSession0actory)ean@
2,DI loo"up support
Session0actory)ean@
2,DI loo"up support
!()
implementtion
support
2d#cDaoSupport 'i#ernateDaoSupport Top(in"DaoSupport
("* %elper 2d#cTemplate 'i#ernateTemplate Top(in"Template
Trnsction
mngement
DataSource
Transaction
%anager or 2TA
'i#ernateTransaction
%anager or 2TA
Top(in"Transaction
%anager or 2TA
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
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
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)
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
1or Ja-a 2 or higher! use SimpleJdbcTemplate
3ses generics and -arargs
Create a template once and re-use it
Do not create one for each use
Thread safe after construction
JdbcTemplate template = new JdbcTemplate(dataSource)
SimpleJdbcTemplate template =
new SimpleJdbcTemplate(dataSource)
88
&hen to use
4Simple5JdbcTemplate
3seful standalone
,nytime JDBC is needed
In utility or test code
To clean up messy legacy code
3seful for implementing a repository in
a layered application
,lso 'nown as a data access ob6ect 4D,05
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
Creating a JDBC-based
epository class
Spring pro-ides two support classes you may
e#tend from
(#tend JdbcDaoSupport on Ja-a 789
(#tend SimpleJdbcDaoSupport on Ja-a 28: or greater
;ou inherit a JdbcTemplate configured by
in6ecting a DataSource

Cet access to t*e template using getJdbcTemplate()


Code your own class using constructor-in6ection
Support class uses setter in6ection< less concise
Support class does not wor' well with =,utowired
81
, &ord on JdbcTemplate -ersus
SimpleJdbcTemplate
D SimpleJdbcTemplate is not :ust for compatibility wit*
Ja=a E and abo=e
F Some infre"uently used functionality *as also been remo=ed
D 3f you need more control% use getJdbc)perations()

gets t*e underlying JdbcTemplate


D SticA to using SimpleJdbcTemplate w*ere possible
D Note@ 3n Spring G.H JdbcTemplate uses Ja=a E as well

Less need for t*e SimpleJdbcTemplate


82
%uerying with JdbcTemplate
D
JdbcTemplate can /uery for
Simple types 4int! long! String5
+eneric >aps
Domain 0b6ects
85
%uerying for Simple Ja-a
Types 475
%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
86
%uerying for Simple Ja-a
Types 4?5
%uery with a bind -ariable on Ja-a 789
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%
new )b:ectIJ { new 3nteger(age) 4)
4
87
%uerying &ith
SimpleJdbcTemplate

1uery wit* a bind =ariable on Ja=a E or greater

Ja=a E supports a =ariable argument list


pri=ate SimpleJdbcTemplate :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
No need for new )b:ectIJ { new 3nteger(age) 4
29
+eneric %ueries
D
JdbcTemplate can return each row of a (esultSet
as a <ap
&hen e#pecting a single row
3se "uery;or<ap(..)
&hen e#pecting multiple rows
3se "uery;orList(..)
3seful for reporting! testing! and @window-on-
data$ use cases
28
%uerying for +eneric >aps
475
%uery for a single row
returns<
>ap { 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 map of I!olumn Name K ;ield Lalue J pairs
22
%uerying for +eneric >aps
4?5
%uery for multiple rows

returns<
List {
H 7 <ap { 3,=/% ;3(ST$NA<'=#Jo*n2% LAST$NA<'=#,oe2 4
/ 7 <ap { 3,=M% ;3(ST$NA<'=#Jane2% LAST$NA<'=#,oe2 4
M 7 <ap { 3,=G% ;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 :a=a.util.List of <ap of I!olumn Name K ;ield Lalue J pairs
23
Domain 0b6ect %ueries
0ften it is useful to map relational data into
domain ob6ects
e8g8 a (esultSet to an Account
Spring$s JdbcTemplate supports this using a
callback approach
;ou may prefer to use 0> for this
.eed to decide between JdbcTemplate /ueries and
J), 4or similar5 mappings
24
%uerying for Domain 0b6ects 475
D
%uery for single row with SimpleJdbcTemplate
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 &arameteriNed(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
&arameteriNes return type
No need to cast
<aps rows to &erson ob:ects
21
%uerying for Domain 0b6ects 4?5
public List>&erson? getAll&ersons() {
return :dbcTemplate."uery(
8select first$name% last$name from &'(S)N8%
new &erson<apper())
class &erson<apper implements &arameteriNed(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
22
owCallbac'*andler
Spring pro-ides a simpler owCallbac'*andler
interface when there is no return ob6ect
Streaming rows to a file
Con-erting rows to A>"
1iltering rows before adding to a Collection
but filtering in S%" is much more efficient
0nly a-ailable in JdbcTemplate
public interface (ow!allbacAOandler {
=oid process(ow((esultSet rs) t*rows S1L'0ception
4
25
3sing a owCallbac'*andler
public class Jdbc)rder(epository {
public =oid generate(eport(9riter out) {
55 select all orders for a full report
:dbcTemplate."uery(#select...from order o% item i2%
new )rder(eport9riter(out))
4
4
class )rder(eport9riter implements (ow!allbacAOandler {
public =oid process(ow((esultSet rs) t*rows S1L'0ception {
55 stream row to output
4
4
26
esultSet(#tractor
Spring pro-ides a (esultSet'0tractor interface for
mapping an entire esultSet to an ob6ect
You are responsible for iterating the esultSet
0nly a-ailable in JdbcTemplate
public interface (esultSet'0tractor {
)b:ect e0tract,ata((esultSet rs) t*rows S1L'0ception%
,ataAccess'0ception
4
27
3sing 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 ()rder) :dbcTemplate."uery(
#select...from order o% item i...conf$id = +2%
new )b:ectIJ { number 4%
new )rder'0tractor())
4
4
class )rder'0tractor implements (esultSet'0tractor {
public )b:ect e0tract,ata((esultSet rs) t*rows S1L'0ception {
55 create an )rder ob:ect from multiple rows
4
4
39
Summary of Callbac'
Interfaces
ow>apper
Best choice when each row of a esultSet maps to a
domain ob6ect
owCallbac'*andler
Best choice when no -alue should be returned from
the callbac' method
esultSet(#tractor
Best choice when multiple rows of a esultSet map to
a domain ob6ect
38
Inserts and 3pdates 475
Inserting a new row
public int insert&erson(&erson person) {
return :dbcTemplate.update(
#insert into &'(S)N (first$name% last$name% age)2 P
#=alues (+% +% +)2%
person.get;irstName()%
person.getLastName()%
person.getAge())
4
32
Inserts and 3pdates 4?5
3pdating 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
33
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
3sing the JdbcTemplate ensures that
S%"(#ceptions are handled in a consistent!
portable fashion
34
S%"(#ception *andling
Issues
*ard to determine cause of failure
>ust 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 things<
BCatch and wrapC
Being swallowed
31
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
1rees you from your own catch-and-wrap approach
(nables selecti-e handling by type of failure
(#ceptions always propagate if not caught
32
Spring Data,ccess(#ception
*ierarchy 4subset5
: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
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
" Programmatic transactions
" Rea!#onl$ transactions
" %istribte! transactions
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
" Programmatic transactions
" Rea!#onl$ transactions
" %istribte! transactions
'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
" Programmatic transactions
" Rea!#onl$ transactions
" %istribte! transactions
'/
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
" Programmatic transactions
" Rea!#onl$ transactions
" %istribte! transactions
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
" Programmatic transactions
" Rea!#onl$ transactions
" %istribte! transactions
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 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 )
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)
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)
32
Topics in this session
&h$ se Transactions'
Local Transaction Management
Spring Transaction Management
Transaction Propagation
+ollbc, rules
Testing
A!vance! topics
" Programmatic transactions
" Rea!#onl$ transactions
" %istribte! transactions
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()"

.
.
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) {
>> ...
.
.
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
" Programmatic transactions
" Rea!#onl$ transactions
" %istribte! transactions
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() {
...
.
.
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() {
...
.
.
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() {
...
.
.
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
" 'rogrmmtic trnsctions
" +ed-only trnsctions
" -istributed trnsctions
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.update(@)"
.
E5ransactional(readBnly=true)
public void rewardAccount'() {
<dbc5eplate.!ueryForBb<ect(@)"
<dbc5eplate.update(@)"
.

$ 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'
%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)
52
%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
' Toplin3
' 41O
' 4a&a ,ersistence A,/ #4,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" modern5da* 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 Re0ard6et0or3
application
Re0ards an account "or dining
' !* as3ing the est!ur!nt 0here the dining occurred
to calculate the bene"it amount
' Then. b* ma3ing a contribution to the $ccount that
initiated the dining
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 10
The Re0ard6et0or3 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
e7g7 89 o" the dining bill
' !ene"it a&ailabilit* polic*
e7g7 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 $;;9
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 object5oriented language. cohesi&e "ine5
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 4a&a. there is a di""erence bet0een Object
identit* and Object e>ui&alence+
' ?? * identity #same memor* address%
' 7e>uals#*% equivalence
/n a database. identit* is based solel* on
primar* 3e*s+
' 7getEntit*/d#%7e>uals#*7getEntit*/d#%%
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 17
O/R Mismatch+ /dentit* #)%
When 0or3ing 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* 3e* "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 object5oriented 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 #)%
!i5directional associations are common in a
domain model #e7g7 ,arent5Child%
' This can be modeled naturall* in each Object
/n a database+
' One side #parent% pro&ides a primar*53e*
' Other side #child% pro&ides a "oreign53e* re"erence
For man*5to5man* 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 @uer* Aanguage
Automatic Change 1etection
,ersistence b* Reachabilit*
Caching
' ,er5Transaction #$
st
Ae&el%
' ,er51ata-ource #)
nd
Ae&el%
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 22
Object @uer* Aanguage
When 0or3ing 0ith domain objects. it is more
natural to >uer* based on objects7
' @uer* 0ith -@A+
' @uer* 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 unit5o"50or3 completes. all modi"ied
state 0ill be s*nchroni(ed 0ith the database7
,er$ice
in$oke(input!
find
output
Repositor#'
find
commit
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 "irst5le&el cache #$AC% is scoped at the
le&el o" a unit5o"50or3
' When an object is "irst loaded "rom the database
0ithin a unit5o"50or3 it is stored in this cache
' -ubse>uent re>uests to load that same entit* "rom
the database 0ill hit this cache "irst
The second5le&el cache #)AC% is scoped at the
le&el o" the ,essionFactor#
' Reduce trips to database "or read5hea&* 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&
-
(((
"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(*$$.
tar%etEntity=*""ress(class)
@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 table=T_*==RESS
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
Configuring a SessionFactor
with annotation "appings
2bean i"=or"erSer#ice class=e5ample(Or"erSer#ice!mpl7
<constructor-arg ref=orer!e"ository#$%
28bean7
2bean i"=or"erRepository
class=e5ample(GibernateOr"erRepository7
<"ro"erty na&e=sessionFactory# ref=sessionFactory#$%
28bean7
2bean i"=session,actory
class=o(s(orm()ibernateA(annotation(*nnotationSession,actoryFean7
<"ro"erty na&e=ataSource# ref=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
18
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
19
Topics in this session
!ntroduction to Hibernate
Mapping
:uering
Configuring a Hibernate SessionFactor
Implementing %ti&e Hibernte '()s
Spring's HibernateTe"plate
20
!"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
21
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
22
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!")&
-
-
23
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
<"ro"erty na&e=sessionFactory# ref=sessionFactory#$%
28bean7
2bean i"= transactionMana%er
class=or%(s'>4(orm()ibernateA(GibernateTransactionMana%er7
<"ro"erty na&e=sessionFactory# ref=sessionFactory# $%
28bean7
28beans7
coul" use 9taTransactionMana%er i' nee"e"
24
Spring("anaged
Transactions *B-
7est practice 8 use read(onl transactions when
ou don;t write anthing in the database
/re$ents Hibernate fro" flushing its session.
which can result in a dra"atic perfor"ance
i"pro$e"ent
Can pro$ide an additional safeguard with so"e
databases 8 Oracle will onl accept S>,>CT
state"ents
'(ransactional)rea*nly=true+
public $ist2Re>ar"Con'irmation7 listRe>ar"s,rom(=ate ")
88 rea"3only. atomic unit3o'3>or4
-
25
Transparent >3ception
Translation *+-
9sed as(is. the pre$ious %&O i"ple"entation
will throw nati$e. $endor(specific
,i-ernate./ce"tions
#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 0ata1ccess./ce"tion hierarch
26
Transparent >3ception
Translation *+-
9sed as(is. the pre$ious %&O i"ple"entation
will throw nati$e. $endor(specific
,i-ernate./ce"tions
#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 0ata1ccess./ce"tion 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
2ersistence./ce"tion(ranslation3nterce"tor
28
Transparent >3ception Translation *@-8
6a$a CA >n$iron"ent
the code
the configuration
'!e"ository
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(H H((MyRepositoryI(H((())
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 =
ne4 GibernateTemplate(session,actory)&
33
Hibernate%aoSupport
Spring also pro$ides this con$enience base
class that data access objects can e3tend if
the need a HibernateTe"plate
!nject it with a reference to the SessionFactor
!t creates the HibernateTe"plate for ou
#o $alue for #ati$e %&Os
34
>3tending
Hibernate%aoSupport
public class GibernateCustomer=ao e/tens ,i-ernate0aoSu""ort
implements Customer=ao

public $ist 'in"*llCustomers()
Strin% )Cl = 'rom Customer&
return get,i-ernate(e&"late)+5'in"()Cl)&
-
88 ot)er "ata access met)o"s
-
35
Configuring a subclass of
Hibernate%aoSupport
2bean i"=customer=ao
class=e5ample(customer(GibernateCustomer=ao 7
<"ro"erty na&e=sessionFactory# ref=sessionFactory#$%
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)De5ample8customer8Customer()bm(5ml28#alue7
28list7
28property7
28bean7
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
Goals o eecti!e web application
architecture
Overview of Spring Web
Spring Web MVC
Spring JavaScript
Spring Web low
Spring aces
!sing Spring in Web "pplications
3
#oals of $ffective Web
"pplication "rchitect%re
&e thin
"n effective web architect%re is thin
The web la'er pla's the role of an adapter responsible for
mapping (TT) re*%ests to application f%nctionalit'
The application la'er encaps%lates the b%siness logic and
domain comple+it'
&e clean
"n effective web architect%re allows for a separation of
concerns
Designers can foc%s on mar,%p and st'le
Java developers can foc%s on re*%est processing logic
#ood modern web framewor,s help meet these goals
4
JVM
Java EE Servlet Container
$ffective Web "pplication
"rchitect%re
Application Layer
(Spring)
Web Layer
Local Java Business Interfaces
e!ote "##$ Interfaces
Clients
5
Topics in this Session
#oals of effective web application architect%re
"!er!iew o Spring #eb
Spring Web MVC
Spring JavaScript
Spring Web low
Spring aces
!sing Spring in Web "pplications
6
Spring Web- The &ig )ict%re
7
Spring Web MVC
Spring.s web framewor,
Optional component
!ses Spring for its own config%ration
&%ilds on the Java Servlet ")/
" parallel )ortlet version is also provided
Comparable to Str%ts 01+
provides a stronger architect%ral fo%ndation
The core platform for developing web
applications with Spring
"ll higher2level mod%les b%ild on it
8
Spring Web MVC Strengths
$as' to learn
ew e+ternal dependencies
le+ible
Smart e+tension points p%t 'o% in control
3a'ered architect%re facilitates re%se
Versatile
/ntegrates pop%lar view and controller technologies
!ses Spring for its config%ration
testable artifacts
benefits from dependenc' in4ection
9
Spring MVC View /ntegration
S%pported View Technologies
JS) 5 JST3
"pache Velocit'
reemar,er
"dobe )D
Microsoft $+cel
Jasper 6eports
7M3 5 7S3T
10
Other 8e' eat%res
Data &inding ramewor,
Validation S%pport
/nternationali9ation S%pport
Tag 3ibrar'
11
Spring JavaScript
12
Spring JavaScript
JavaScript abstraction framewor,
b%ilds on e+isting JS framewor,s
Do4o is c%rrentl' s%pported
Simplifies %se for common enterprise scenarios
avoid proliferation of JavaScript code
"ims to promotes best practices
)rogressive enhancement
13
Spring JavaScript eat%res
Decorate form inp%t fields
Client2side validation
"4a+ events
ragment rendering
"4a+ modal dialogs :pop2%p;
14
More Spring JS eat%res
#racef%l degradation
"pplies progressive enhancement techni*%es
Ma,es 'o%r web application more accessible
CSS framewor,
)erformance optimi9ations
O%r reference applications receive a <"= >ahoo !/
)erformance #rade
C%stom Do4o &%ild
6ed%ces overall amo%nt of JavaScript transferred to client
6eso%rceServlet
Serves %p cached? compressed JavaScript and CSS reso%rces
"4a+ error handling
15
See Spring JS /n "ction
SpringSo%rce b%ndle repositor' application
http-55www1springso%rce1com5repositor'
&%ilt on Spring MVC and Spring JavaScript
16
Spring Web low
17
Spring Web low
)l%gs into Spring Web MVC as a Controller
technolog' for implementing statef%l <flows=
A flow encapsulates a reusable sequence of steps that
can execute in different contexts
6aises the abstraction level b' providing a
dedicated flow definition language :DS3;
18
Web low Sweet Spot
19
$+ample low Definition
<flow>
<view-state id=step1>
<transition on=eventA to=step2/>
</view-state>
<view-state id=step2>
<transition on=eventB to=done/>
</view-state>
<end-state id=done/>
</flow>
20
low Design
lows model statef%l operations that ta,e a
series of re*%ests to complete
&oo,(otel
lightChec,/n
$dit"cco%nt
#et/ns%rance@%ote
"ppl'or3oan
6egisterAew!ser
Can be %sed for simple <single2re*%est=
operations? b%t not its foc%s or <sweet spot=
21
lows as Web 6eso%rces
lows are addressable web reso%rces
"ddress them to begin new operations
$+amples
http-55localhost5acco%nts5register
&egins a new acco%nt registration operation
http-55localhost5flights5chec,in
&egins a new flight chec,2in operation
22
low $+ec%tions are /solated
lows e+ec%te in isolation from other %sers
)rovide a local conte+t for operations c%rrentl' <in
progress= b%t not 'et completed
The e+ec%tion conte+t for each operation is
session-specific
http-55localhost5flights5chec,inBe+ec%tionCe0s0
Session%specific flo& e'ecution (ey
23
Spring Sec%rit' /ntegration
<flow>
<secured attributes="ROLE_USER" />
</flow>
Can also sec%re states and transitions
Can refer to %ser )rincipal %sing $3
!se the current$ser implicit variable
6esolvable within flow and view templates
24
low2Managed )ersistence
<flow>
<persistence-context/>
</flow>
Scopes a persistence conte+t with this flow
"%tomaticall' %sed b' 'o%r data access ob4ects
S%pport for committing changes made b' the
flow %pon completion
<end-state id=boo!in"#onfir$ed co$$it=true />
25
Spring aces
26
Spring aces
Combines the JS !/ component model with
Web low navigation5state management
"ll in a native Spring MVC environment
Spring aces also incl%des a lightweight JS
component librar'
Designed for the DEF
/ncl%des "4a+ s%pport? client2side form validation
&%ilt on a new Spring JavaScript
/ntegrates Do4o as the primar' !/ tool,it
"pplies progressive enhancement techni*%es
27
Spring aces &enefits
$nhanced page navigation r%les
&etter e+ception handling policies
$asier client and server2side :model; validation
ine2grained state management
flow scope? view scope? flash scope
"4a+ s%pport with gracef%l degradation
28
28
Spring Travel 6eference
"pplication Comparison
)lain JS Spring aces
A%mber of
controller artifacts
G H
3ines of code III JK
29
Spring aces Observations
Ma,es JS easier for the Spring comm%nit'
)ioneering approach to JS integration
Compliant with JS 010 and 01H specifications
Ma4or component libraries are all %sable in a
Spring aces environment
J&oss 6ich aces? "pache Trinidad? /ceSoft /ceaces
30
Topics in this Session
#oals of effective web application architect%re
Overview of Spring Web
Spring Web MVC
Spring JavaScript
Spring Web low
Spring aces
$sing Spring in #eb %pplications
31
Spring "pplication Conte+t
3ifec'cle in Webapps
Spring can be initiali9ed within a webapp
start %p b%siness services? repositories? etc1
!ses a standard servlet listener
initiali9ation occ%rs before an' servlets e+ec%te
application read' for %ser re*%ests
32
Config%ration in web1+ml
J%st add a Spring2provided 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
33
Servlet Container "fter
Starting !p
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
34
"ccess To Spring2Managed
Ob4ects
Web"pplicationConte+t!tils
static helper
provides access to the Spring "pplication Conte+t
&%ilt2in framewor, integration
JS
Spring Web MVC
via dependenc' in4ection
35
<)lain= Servlet "ccess To Spring
public class #opSpen0erseport3enerator e'ten0s "ttpServlet 4
private Merc.anteportingService reportingService5
67verri0e
public voi0 init() 4
ApplicationConte't conte't 8 WebApplicationConte't9tils/
getRequiredWebApplicationContext(getServletConte't())5
reportingService 8 (Merc.anteportingService)
conte't/getBean(:!erc.anteportingService;)5
<
=
<
Saves t.e reference to t.e application entry%point for invocation
0uring re>uest .an0ling
Loo(s up ApplicationConte't un0er its
special na!e in t.e ServletConte't
36
Spring Web MVC Controllers
6Controller
public class #opSpen0erseportController 4
private Merc.anteportingService reportingService5
6Auto&ire0
public #opSpen0erseportController(Merc.anteportingService service) 4
t.is/reportingService 8 service5
<
=
<
?epen0ency is auto!atically in@ecte0 by type
37
JavaServer aces "ccess To Spring
JS2centric integration
Spring pl%gs in as as a JS managed bean provider
config%re a Variable6esolver in faces2config1+ml
replace all managed beans in faces2config1+ml
Spring2centric integration
JS managed beans t'picall' declared in flow
definition in one of several scopes
38
S%mmar'
Spring Web has a set of mod%les for rich web
application development
"pplication2la'er? Spring2managed ob4ects can
be %sed in an' web application
Separate G2da' SpringSo%rce co%rse available-
<6ich Web "pplications with Spring=
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
handleRequest
(request& response)
&e'$est "andlers
4nco)ing re'$ests are dispatched to handlers
There are potentially )any handlers per
ispatcherSer!let
Dispatcher
Servlet
Handler
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
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 yo$ define are typically +&,>
based= optionally $sing wild cards1
Alogin
AeditAcco$nt
ArewardACACC
Mapping r$les in Spring ;-<1 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 Dfill inD 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
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 ;E acco$nts
17
Topics in this Session
&e'$est 0rocessing ,ifecycle
Key Artifacts
ispatcherSer!let
"andlers
'iews
#$ic% Start
18
Selecting a View
Controllers typically ret$rn a !iew na)e
*y defa$lt the !iew na)e is interpreted as a path to
a FS0 page
Controllers )ay ret$rn n$ll .or !oid/
The ispatcherSer!let will then select a defa$lt !iew based
on the re'$est +&,
Controller are also allowed to ret$rn a concrete View
new FstlView.2AWE*>4G5ArewardAlist-9sp3/
new &eward,isting0df./
6ot ver$ co++on7
19
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
20
C$sto) 4nternal &eso$rce
View &esol!er E7a)ple
Rewardontroller
handle 8*9
/reward/list
rewardList
+odel:,rewards0
DispatcherServlet
usto+
5nternalResource
ViewResolver
rewardList
/"*(;56F/views/rewardList'<sp
=
>
Lo.ical view na+e
Resolved ph$sical path
?#ean class:1or.'sprin.2ra+ewor@'we#'servlet'view'
5nternalResourceViewResolver3A
?propert$ na+e:1pre2i!3 value:1/"*(;56F/views/3 /A
?propert$ na+e:1su22i!3 value:1'<sp3 /A
?/#eanA
21
Topics in this Session
&e'$est 0rocessing ,ifecycle
Key Artifacts
ispatcherSer!let
"andlers
Views
(uic) St%rt
22
#$ic% Start
Steps to de!eloping a Spring MVC application
H- eploy a ispatcher Ser!let .one>ti)e only/
;- 4)ple)ent a re'$est handler .controller/
I- 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
23
H-a eploy ispatcherSer!let
efine inside @webappB within web-7)l
?servletA
?servlet;na+eArewardsad+in?/servlet;na+eA
?servlet;classA
or.'sprin.2ra+ewor@'we#'servlet'DispatcherServlet
?/servlet;classA
?init;para+A
?para+;na+eAconte!ton2i.Location?/para+;na+eA
?para+;valueA
/"*(;56F/rewardsad+in;servlet;con2i.'!+l
?/para+;valueA
?/init;para+A
?/servletA
ontains the ServletBs con2i.uration
24
H-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.A
?servlet;na+eArewardsad+in?/servlet;na+eA
?url;patternA/rewardsad+in/C?/url;patternA
?/servlet;+appin.A
http%//localhost%DEDE/rewardsad+in/reward/list
http%//localhost%DEDE/rewardsad+in/reward/new
http%//localhost%DEDE/rewardsad+in/reward/showFid:=
25
4nitial ispatcherSer!let
Config$ration
?#eansA
?#ean class:1or.'sprin.2ra+ewor@'we#'''5nternalResourceViewResolver3A
?propert$ na+e:1pre2i!3 value:1/"*(;56F/views/3 /A
?propert$ na+e:1su22i!3 value:1'<sp3 /A
?/#eanA
?/#eansA
/"*(;56F/rewardsad+in;servlet;con2i.'!+l
26
)ontroller
public class Rewardontroller ,
private RewardLoo@upService loo@upServiceG
)Autowired
public Rewardontroller(RewardLoo@upService svc) ,
this'loo@upService : svcG
0

)Request-appin.(//reward/show/)
public Strin. show(long id& -odel +odel) ,
Reward reward : loo@upService'loo@upReward(id)G
+odel'addAttri#ute(reward)G
return 1rewardView3G
0
0
;- 4)ple)ent the Controller
Selects the 1rewardView3 to
to render the reward
Depends on
application service
Auto+aticall$ 2illed
in #$ Sprin.
27
I- 4)ple)ent the View
?ht+lA
?headA?titleAHour Reward?/titleA?/headA
?#od$A
A+ount:I,reward'a+ount0
Date:I,reward'date0
Account 6u+#er:I,reward'account0
-erchant 6u+#er:I,reward'+erchant0
?/#od$A
?/ht+lA
/"*(;56F/views/rewardView'<sp
Re2erences result +odel o#<ect #$ na+e
28
J- &egister the Controller
?#ean id:1rewardontroller3 class:1rewardsad+in'Rewardontroller3A
?constructor;ar. re2:1rewardLoo@upService3 /A
?/#eanA
/"*(;56F/rewardsad+in;servlet;con2i.'!+l
29
<- eploy and Test
http%//localhost%DEDE/rewardsad+in/reward/showFid:=
Hour Reward
A+ount : I=EE'EE
Date : >EEJ/=>/>K
Account 6u+#er : =>LMNJODK
-erchant 6u+#er : =>LMNJODKE
30
(ptionally1
Enable Co)ponent Scanning
?conte!t%co+ponent;scan #ase;pac@a.e:1rewardsad+in3/A
Sprin. -V ontrollers can #e auto;detected
)ontroller
public class Rewardontroller ,
private RewardLoo@upService loo@upServiceG
)Autowired public Rewardontroller(RewardLoo@upService svc) ,
this'loo@upService : svcG
0

)Request-appin.(//reward/show/)
public Strin. show(long id& -odel +odel) , ''' 0
0
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.
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%pro9ider#
""" Configure specific +serDetailsSer9ice
!(security$authentication%pro9ider#
20
The =+4C +serDetailsSer9ice
(?(@)
>ueries R+4MS for users and their authorities
&rovides default queries
' S#CT username( password( enabled :R9M users
W8R username ? @
' S#CT username( authority :R9M authorities
W8R username ? @
21
The =+4C +serDetailsSer9ice
(@(@)
Configuration$
!security$authentication%pro9ider#

!security$;dbc%user%ser9ice data%source%ref&'3yDatasource' (#
!(security$authentication%pro9ider#
possibility to custo3iAe >ueries using
attributes such as
authorities%by%userna3e%>uery
22
The 5n1Memory +serDetailsSer9ice
!seful for development and testing
!security$authentication%pro9ider#

!security$user%ser9ice properties&'(B.C%I/0(users"properties' (#
!(security$authentication%pro9ider#
admin=secret,ROLE_ADMIN
testuser1=pass,ROLE_MEMBER
testuser2=pass,ROLE_MEMBER
guest=guest,ROLE_GUEST
23
9ther Authentication 9ptions
5mplement a custom +serDetailsSer9ice
' +elegate to an e;isting !ser repository or +A9
#+A&
-,./0 Certificates
=AAS #ogin Module
Single1Sign19n
' SiteMinder
' =A1S57 Central Authentication Service
AuthoriAation is not affected by changes to AuthenticationD
24
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
25
Tag library declaration
The Spring Security tag library can be declared
as follows
!EF taglib prefix&'security'
uri&'http$((444"springfra3e4or5"org(security(tags' E#
a9ailable since Spring Security @"G
26
Spring Security)s Tag #ibrary
+isplay properties of the Authentication obAect
8ide sections of output based on R9#
2ou are logged in as$
!security$authentication property&8principal"userna3e<(#
!security$authoriAe ifAny=ranted&8R61.*ADMI/<#
,6P%S.CR., I/06RMA,I6/
Clic5 !a href&8(ad3in(deleteAll<#-.R.!(a# to delete all records"
!(security$authoriAe#
,his +R1 should be protected by
the intercept%url tag alsoD
27
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
28
Method security
Spring Security B,/ uses A9& for security at
the method level
' ;ml configuration with the Spring Security
namespace
' annotations based on Spring annotations or =SR1B./
annotations
29
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#
30
Method security with Spring
annotations
Spring Security annotations should be enabled
!security$global%3ethod%security secured%annotations&'enabled' (#

on the =ava level$
import org.springframework.security.annotation.Secured
pu!"ic c"ass Ite3Manager H
FSecured('R61.*M.MC.R')
pu!"ic Ite3 findIte3(long ite3/u3ber) H
"""
I
I
31
Method security with =SR B./
annotations
=SR1B./ annotations should be enabled
!security$global%3ethod%security ;sr@JG%annotations&'enabled' (#

on the =ava level$
import #a$a%.annotation.security.&o"es'""owed
pu!"ic c"ass Ite3Manager H
FRolesAllo4ed('R61.*M.MC.R')
pu!"ic Ite3 findIte3(long ite3/u3ber) H
"""
I
I
32
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
33
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
34
Web Security :ilter
Configuration
(e!
)ser
Ser9let
Ser9let Container
Spring ApplicationContext
0ilter
@ K
0ilter
/
Delegating0ilterProxy
springSecurity*i"ter+,ain
0ilter
?
35
The :ilter chain
With AC75 Security C,;
' :ilters were manually configured as individual
DbeanE elements
' #ed to verbose and error1prone -M#
Since Spring Security B,/
' :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
36
Access !nsecured Resource &rior
to #ogin
Beb Cro4ser
+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
37
Access Secured Resource &rior to
#ogin
Beb Cro4ser
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
./&0(S 10.
')./-1.2+'.-3
-4+-5.201
Authentication
exceptionD
L Sa$es current
re6uest in session
L+"ears conte%t
L&edirects to
aut,entication entry
point
%
1ogin 0or3
38
Submit #ogin Request
Beb Cro4ser
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
LS)++-SS
populates context
redirects to target url
L*'27)&-
redirects to failure url
39
Access Resource With
Required Role
Beb Cro4ser
SecuredResource
0ilterSecurityInterceptor
.xception,ranslation0ilter
AuthenticationProcessing0ilter
-ttpSessionContextIntegration0ilter
1ogout0ilter
*inds conte%t in
session and sets
for current t,read
Does nothing
Does nothing
Does nothing
Consults attributes7
obtains context7 and
delegates to access
decision 3anager
Does nothing
Does nothing
Stores conte%t !ack
into session
Does nothing
Does nothing
40
Access Resource Without
Required Role
Beb Cro4ser
SecuredResource
0ilterSecurityInterceptor
.xception,ranslation0ilter
AuthenticationProcessing0ilter
-ttpSessionContextIntegration0ilter
1ogout0ilter
*inds conte%t in
session and sets
for current t,read
Does nothing
Does nothing
Does nothing
.,rows '++-SS 3-12-3 -4+-5.201
%
Consults attributes7
obtains context7 and
delegates to access
decision 3anager
Access Denied
.xceptionD
L 5uts e%ception in
re6uest scope
L *orwards to t,e
error page
.rror Page
41
Submit #ogout Request
Beb Cro4ser
SecuredResource
0ilterSecurityInterceptor
.xception,ranslation0ilter
AuthenticationProcessing0ilter
-ttpSessionContextIntegration0ilter
1ogout0ilter
*inds conte%t in
session and sets
for current t,read
L +"ears conte%t
L &edirects to
"ogout success ur"
1ogout Success
42
The :ilter Chain$ Summary
. /ilter 0#me "#in 1urpose
C
8ttpSessionConte;t
5ntegration:ilter
stablishes SecurityConte;t and
maintains between 8TT& requests
B #ogout:ilter
Clears SecurityConte;t8older when
logout requested
F
Authentication
&rocessing :ilter
&uts Authentication into the
SecurityConte;t on login request
G
;ception
Translation:ilter
Converts SpringSecurity e;ceptions
into 8TT& response or redirect
.
:ilterSecurity
5nterceptor
Authori*es web requests based on
!R# patterns
43
Custom filter chain 2CHB3
9ne filter on the stac% may be repl#ced by a
custom filter
9ne filter can be #dded to the chain
!bean id&'3y0ilter' class&'co3"3yco3pany"MySpecialAuthentication0ilter'#
!security$custo3%filter
position&'A+,-./,ICA,I6/*PR6C.SSI/=*0I1,.R' (#
!(bean#
!bean id&'3y0ilter'
class&'co3"3yco3pany"MySpecial0ilterBithSpecial0eatures'#
!security$custo3%filter
after&'A+,-./,ICA,I6/*PR6C.SSI/=*0I1,.R' (#
!(bean#
44
Custom filter chain 2BHB3
Writing the =ava class
' The easiest way is to e;tend SpringSecurity:ilter
pu!"ic c"ass MySpecialAuthentication0ilter e%tends SpringSecurity0ilter H
pu!"ic $oid do0ilter-ttp(-ttpSer9letRe>uest re>uest7 -ttpSer9letResponse
response7 0ilterChain chain) t,rows I6.xception7Ser9let.xception H
"""
I
I
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 server0
side re1uirements
$inding to registry or e,posing an endpoint
+onforming to a programming model if necessary
Spring provides FactoryBeans that generate
proxies to handle client0side re1uirements
+ommunicate with the server0side endpoint
+onvert remote e,ceptions to a runtime hierarchy
6
The Declarative Approach
Spring2s abstraction uses a configuration0based
approach
On the server side
",pose e,isting services with 3O code changes
On the client side
Invo&e remote methods from e,isting code
Ta&e advantage of polymorphism by using
dependency in4ection
7
+onsistency across Protocols
Spring2s e,porters and pro,y FactoryBeans bring
the same approach to multiple protocols
Provides fle,ibility
Promotes ease of adoption
On the server side
",pose a single service over multiple protocols
On the client side
Switch easily between protocols
!igrate between remote vs5 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 ",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 #ava remoting protocol
Server0side e,poses a skeleton
+lient0side invo&es methods on a stub 6pro,y7
#ava seriali8ation is used for marshalling
13
Traditional R!I
The R!I model is invasive 0 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
Spring2s R!I Service ",porter
Transparently e,pose an e,isting PO#O service
to the R!I registry
3o need to write the binding code
Avoid traditional R!I re1uirements
Service interface does not e,tend Remote
Service class is a PO#O
15
+onfiguring the R!I Service ",porter
Start with an e,isting PO#O 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 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
Spring2s R!I Pro,y (enerator
Spring provides a FactoryBean implementation
that generates an R!I client0side pro,y
It is simpler to use than a traditional R!I stub
+onverts chec&ed (emoteExceptions into Spring2s
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
In4ect 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
R!I0IIOP for Interoperability/
Service
(enerate IIOP stubs and ties
9se R!I compiler with IIOP flag/ rmic )iiop
Define the service interface
!ust e,tend the R!I (emote interface
All methods must throw (emoteException
Implement the service class
All methods must throw (emoteException
:everage Spring to e,pose the service to a
+OR$A Ob4ect Re1uest $ro&er via #3DI
9se Spring2s *niRmi+er%iceExporter
Provide *n#i3ame and *n#iEnvironment properties
19
R!I0IIOP for Interoperability/
+lient
Spring also provides a ;n#i(mi!roxyFactoryBean
The generated pro,y can implement any
interface
3o need to throw (emoteExceptions
The pro,y will convert to the runtime hierarchy
+lient0side code is decoupled from R!I even
when accessing an IIOP0based +OR$A service
20
Accessing "#$s
Spring generates proxies to access Stateless
Session $eans
+onceals #3DI loo&up 6and retry logic7
+aches the "#$ home
+onverts (emoteExceptions to runtime hierarchy
$ean definitions can use the *ee namespace
< <*ee:local=sls>
< <*ee:remote=sls>
21
Accessing an "#$ with a
Spring Pro,y
Server !rocess
TransferService
Bean
TransferService
(emote
<<interface>>
TransferService
exten#s
implements
TransferService
>ome
creates
S?SB
!roxy
Client !rocess
Teller
$es%top
&I
implements
<<interface>>
TransferService
22
+onfiguring the "#$ Pro,y
9se the 4ee namespace to generate the pro,y
In4ect it into the client
<*ee:remote=sls i#/0transferService1
*n#i=name/0*ava:comp.env.e*.transferService1
'siness=interface/0foo.Tra#eService1>
<*ee:environment>
*ava.naming.provi#er.'rl/t@:..remoteserver:A776
*ava.naming.factory.initial/2elogic.*n#i.B?InitialContextFactory
<.*ee:environment>
<.*ee:remote=sls>
<ean i#/0teller$es%top&I1 class/0foo.Teller$es%top&I1>
<property name/0transferService1 ref/0transferService1.>
<.ean>
InitialContext settings are not necessary if co=locate#
23
Spring2s %ttpInvo&er
A lightweight %TTP0based 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 #ava seriali8ation
>TT! !)ST re,'est
>ttpInvo%er
ServiceExporter
Server !rocess
>ttpInvo%er
!roxy
Client !rocess
>TT! response
;ava serialiCation
24
+onfiguring the %ttpInvo&er
Service ",porter
Start with an e,isting PO#O 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
25
+onfiguring the %ttpInvo&er
Pro,y
Define a factory bean to generate the pro,y
In4ect 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:D7D7.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 &(?
26
%essian and $urlap
+aucho created these two lightweight protocols
for sending ;!: over %TTP
%essian uses binary ;!: 6more efficient7
Implementations for many languages
$urlap uses te,tual ;!: 6human readable7
The Ob4ect';!: seriali8ation'deseriali8ation
relies on a proprietary mechanism
$etter performance than #ava seriali8ation
:ess predictable when wor&ing with comple, types
27
%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
28
+hoosing a Remoting
Protocol 6<7
Spring on server and client=
%ttpInvo&er
#ava 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!I0IIOP 6+OR$A7
29
+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
3ame. parameters. and return value
?hen using #ava 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
Document0based 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 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
http$%%blog.spring&r"mewor'.com%"r(en%"rchies%2007%0)%27%ws-duc'-typing%
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 0.!-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-/(transfer7ws7cf..!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
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
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
Con!iguring JS "esources with Spring
Springs JmsTemplate
Sending Messages
Receiving Messages
12
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 fle-i#ility
% use a standalone JMS provider
% use an ApplicationServer to manage JMS resources
13
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
14
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
15
Topics in this Session
"ntroduction to JMS
Configuring JMS Resources with Spring
Spring#s JmsTemlate
Sending Messages
Receiving Messages
16
Springs JmsTemplate
The template simplifies usage of the A!"
% Reduces #oilerplate code
% Manages resources transparently
% .andles e-ceptions properly
% Converts chec&ed e-ceptions to runtime e/uivalents
% !rovides convenience methods and call#ac&s
17
JmsTemplate Strategies
The JmsTemplate delegates to colla#orators to
handle some of the wor&
% MessageConverter
% (estinationResolver
18
MessageConverter
The JmsTemplate uses a MessageCon%erter to
convert #etween o#0ects and messages
The default SimpleMessageConverter handles
#asic types
String to TextMessage
Seriali1able to ObjectMessage
Map to MapMessage
byteBC to BytesMessage
19
"mplementing
MessageConverter
"t is sometimes desira#le to provide your own
conversion strategy
% Reuse e-isting code
% (elegate to an o#0ect'to'1M2 translator
"mplement the two necessary methods
!rovide the implementation to JmsTemplate via
dependency in0ection
Message toMessage!Object o, Session session"
Object DromMessage!Message message"
20
(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 re/uires one method
Destination resol%eDestination(ame!Session session,
String 'estination(ame,
boolean pubSubDomain"
t!rows JMSException#
21
(efining a JmsTemplate 3ean
!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
22
Topics in this Session
"ntroduction to JMS
Configuring JMS Resources with Spring
Springs JmsTemplate
Sending ess$ges
Receiving Messages
23
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!"
4se the simplest option for the tas& at hand
24
Sending Messages with
Conversion
2everaging 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"#
25
Sending Messages with
Call#ac&s
5hen more control is needed* use call#ac&s
"blic #oi$ sen'!MessageCreator messageCreator"#
"blic Object execute!$ro'ucerCallbac* action"#
"blic Object execute!SessionCallbac* action"#
Message createMessage!Session session" /F0
26
Creating the /ueue reference
yourself using a call#ac&
jmsTemplateexecute!new SessionCallbac*!" /
"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!+Gello QueueH+"#
pro'ucersen'!message"#
ret"rn n"ll#
0
0"#
27
Topics in this Session
"ntroduction to JMS
Configuring JMS Resources with Spring
Springs JmsTemplate
Sending Messages
"ecei%ing ess$ges
28
Synchronous Message
Reception
The JmsTemplate can receive messages also*
#ut these are #loc&ing methods
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"#
29
The JMS Message2istener
The JMS A!" defines this interface for
asynchronous reception of messages
public %oi' onMessage!Message" /
&& .an'le t.e message
0
30
Springs Message2istener
Containers
Traditionally* use of Message<istener
implementations re/uired an 6J3 container
Spring provides lightweight alternatives
% SimpleMessage2istenerContainer
4ses plain JMS client A!"
Creates a fi-ed num#er of Sessions
% (efaultMessage2istenerContainer
Adds transactional capa#ility
Advanced scheduling and endpoint
management options availa#le for each
container option
31
(efining a plain
JMS Message 2istener
(efine listeners using 0ms7listener elements
2istener need to implement Message2istener or
SessionAwareMessage2istener
0ms7listener'container allows for twea&ing of
tas& e-ecution 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
32
Spring8s message'driven o#0ects
Spring also allows you to specify a plain Java
o#0ect that can serve as a listener
!arameter is 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
Copyright 2006-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
2A3
Sending and Receiving Messages in a Spring
6nvironment
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Spring JMX
Management and Monitoring of Java
Applications
2
Topics in this session
Introduction to J!
JMX Architecture
Introducing Spring JMX
Explicitly exporting beans ith Spring
Automatically exporting existing M!eans
3
"oals of JMX
The Java Management Extensions specification
aims to create a standard A#I for adding
management and monitoring to Java
applications
Management
$ %hanging configuration properties at runtime
Monitoring
$ &eporting cache hit'miss ratios at runtime
4
(o JMX )or*s
To add this management and monitoring
capability JMX instruments application
components
JMX introduces the concept of the M!ean
$ A Java !ean ith a management interface
5
Topics in this session
Introduction to JMX
J! "rchitecture
Introducing Spring JMX
Explicitly exporting beans ith Spring
Automatically exporting existing M!eans
6
JMX Architecture
MBeanServer
MBean MBean MBean
JSR-160
Connector
JSR-160
Connector
7
JMX Architecture
An M!ean is a standard Java !ean ith an
additional management interface
$ Attributes
here getters and setters define readability and
riteability
$ +perations
The management interface can be defined
statically ith a Java interface or defined
dynamically at runtime
8
JMX Architecture
An M!eanServer acts as a bro*er for
communication beteen
$ Multiple local M!eans
$ &emote clients and M!eans
An M!eanServer maintains a *eyed reference
to all M!eans registered ith it
$ This *ey is referred to as an +b,ect-ame
9
JMX Architecture
External communication ith an M!eanServer
is accomplished using a JS&./01 connector
This specification defines a generic A#I for
communicating ith an M!eanServer
The only protocol re2uired by the spec is &MI
$ !ut there are additional protocols including3
S+A#
(essian
I#%
10
Topics in this session
Introduction to JMX
JMX Architecture
Introducing Spring J!
Explicitly exporting beans ith Spring
Automatically exporting existing M!eans
11
"oals of Spring JMX
4sing the ra JMX A#I is difficult and complex
The goal of Spring5s JMX support is to simplify
the use of JMX hile hiding the complexity of
the A#I
12
"oals of Spring JMX
Exposing existing Spring beans as M!eans
$ Transparently ithout changing any Java code
$ 6eclaratively using Spring bean definitions
%onfiguring JMX infrastructure
$ 6eclaratively using 7actory!eans
%onsuming JMX managed beans
$ Transparently using a proxy.based mechanism
13
Topics in this session
Introduction to JMX
JMX Architecture
Introducing Spring JMX
#xplicitly exporting be$ns with Spring
Automatically exporting existing M!eans
14
%reating an M!eanServer
To create an M!eanServer declaratively8 define
a bean
<bean id="mBeanServer"
class="org.springframework.jmx.support.
MBeanServerFactorBean"!
<propert name="locate"xistingServer#f$ossible" value="true"%!
<%bean!
15
Spring5s M!eanExporter
Transparently expose an existing #+J+ bean to
the M!eanServer
$ -o need to rite the registration code
!y default avoids the need to create an explicit
management interface or create an
+b,ect-ame instance
$ 4ses reflection to manage all properties and methods
$ 4ses map *ey as the +b,ect-ame
16
Exporting a bean as an
M!ean
Start ith an existing #+J+ bean
4se the M!eanExporter to export it
<bean id="messageService" class="MessageService"%!
<bean class="org.springframework.jmx.export.MBean"xporter"!
<propert name="beans"!
<util&map!
<entr ke="service&name=messageService"
value'ref="messageService"%!
<%util&map!
<%propert!
<%bean!
17
%ontrolling M!ean 6etails
In many cases the default strategies for
creating the management interface and setting
the +b,ect-ame are not sufficient
The M!eanExporter allos alternative
strategies to be in,ected
$ +b,ect-amingStrategy
$ M!eanInfoAssembler
18
+b,ect-amingStrategy
+b,ect-ames are controlled by
implementations of the +b,ect-amingStrategy
interface
Three included implementations
$ 9ey-amingStrategy
6efault implementation
4ses the *ey passed to the M!eanExporter by default
%an be configured to loo* in a properties file
$ Identity-amingStrategy
"enerates an +b,ect-ame dynamically based on the
J:M identity of a bean
$ Metadata-amingStrategy
&eads an +b,ect-ame from source.level metadata
19
+b,ect-amingStrategy
<bean class="org.springframework.jmx.export.MBean"xporter"!
<propert name="beans"!
<util&map!
<entr ke="not.important"
value'ref="messageService"%!
<%util&map!
<%propert!
<propert name="namingStrateg"!
<bean class="org.springframework.jmx.export.naming.
#dentit(amingStrateg"%!
<%propert!
<%bean!
20
M!eanInfoAssembler
Management interfaces are controlled by
implementaions of the M!eanInfoAssembler
interface
$ !uilds on the JMX standard ModelM!ean
infrastructure
$ Allos for the full feature set of JMX to be exposed
$ Easily extensible for your on re2uirements
21
M!eanInfoAssembler
7our included implementations
$ Simple&eflectiveM!eanInfoAssembler
6efault implementation
Exposes all public properties and methods
$ Method-ame!asedM!eanInfoAssembler
Supports declarative selection of methods in a Spring
configuration file
Extremely easy to configure
Allos per instance configuration
22
M!eanInfoAssembler
$ Interface!asedM!eanInfoAssembler
Supports management interface definition using Java
interfaces
Extends the Standard M!ean interface semantics
$ 4se multiple interfaces per bean
$ !eans do not need to implement the management
interface directly
$ MetadataM!eanInfoAssembler
6efine management interfaces using source.level
metadata
$ J69 ;<1 Annotations
Supports autodetection
$ Any bean mar*ed ith the =Managed&esource annotation
ill be automatically registered ith an M!eanServer
23
M!eanInfoAssembler
<bean class="org.springframework.jmx.export.MBean"xporter"!
)
<propert name="assembler"!
<bean class="org.springframework.jmx.export.assembler.
#nterfaceBasedMBean#nfo*ssembler"!
<propert name="interfaceMappings"!
<util&map!
<entr ke="service&name=messageService"
value="infoassembler.Message+apable" %!
<%util&map!
<%propert!
<%bean!
<%propert!
<%bean!
24
Topics in this session
Introduction to JMX
JMX Architecture
Introducing Spring JMX
Explicitly exporting beans ith Spring
"utom$tic$lly exporting existing %e$ns
25
Automatically exporting
pre.existing M!eans
Some beans are Mbeans themselves
$ (ibernate StatisticsService
Spring can easily autodetect those and export
them for you
<context&mbean'export%!
<bean id="statisticsService"
class="org.,ibernate.jmx.StatisticsService"!
<propert name="sessionFactor" ref="sessionFactor"%!
<%bean!
26
Summary
Spring JMX allos you to easily export
Spring.managed beans to a JMX MbeanServer
$ Simple value.add no that your beans are managed
4se MbeanInfoAssembler to customi>e the
management interface
4sing ?context3mbean.export@ to
automatically export pre.existing M!eans
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
AA!
Adding Management and Monitoring
ith Spring JMX

Anda mungkin juga menyukai