Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
e
c
t
i
o
n
Simple
Object
The Spring Triangle
!
s
p
e
c
t
-
"
r
i
e
n
t
e
d
#
r
o
g
r
$
m
m
i
n
g
%nterprise Ser&ice !bstr$ctions
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
8+4
,eveloping an +pplication from %lain &ava
O"/ects
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibit
Spring Quick Start
Introducing the Spring Application Context and
Springs XML-based configuration language
2
Topics in this session
Spring quick strt
!riting bean definitions
" Configuring ob#ects
" $oing be%ond constructor instantiation
Creating an application context
&etrie'ing bean instances
Su((ar%
3
)o* Spring !orks
Spring
ApplicationContext
Configuration
Instructions
Your Application Classes (POJOs)
Fully configured
application system
Ready for use
Creates
4
+our Application Classes
public class ransferSer!iceImpl implements ransferSer!ice "
public ransferSer!iceImpl(Account#epository ar) "
t$is%account#epository & ar'
(
)
(
public class ransferSer!iceImpl implements ransferSer!ice "
public ransferSer!iceImpl(Account#epository ar) "
t$is%account#epository & ar'
(
)
(
public class JdbcAccount#epository implements Account#epository "
public JdbcAccount#epository(*ataSource ds) "
t$is%dataSource & ds'
(
)
(
public class JdbcAccount#epository implements Account#epository "
public JdbcAccount#epository(*ataSource ds) "
t$is%dataSource & ds'
(
)
(
+eeded to load accounts from t$e database
+eeded to perform money transfers
bet,een accounts
5
Configuration Instructions
-beans.
-bean id&/transferSer!ice0 class&/app%impl%ransferSer!iceImpl0.
-constructor1arg ref&/account#epository0 2.
-2bean.
-bean id&/account#epository0 class&/app%impl%JdbcAccount#epository0.
-constructor1arg ref&/dataSource0 2.
-2bean.
-bean id&/dataSource0 class&/com%oracle%3dbc%pool%Oracle*ataSource0.
-property name&/4#50 !alue&/3dbc6oracle6t$in67local$ost689:86;A+<0 2.
-property name&/user0 !alue&/moneytransfer1app0 2.
-2bean.
-2beans.
6
Creating and ,sing the
Application
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(/application1config%xml0)'
22 5oo> up t$e application ser!ice interface
ransferSer!ice ser!ice &
(ransferSer!ice) context%get;ean(/transferSer!ice0)'
22 4se t$e application
ser!ice%transfer(ne, ?onetaryAmount(/@AA%AA0)B /80B /:0)'
7
Inside the Spring Application
Context
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(/application1config%xml0)'
Application Context
Oracle*ataSource
dataSource
JdbcAccount#epository
account#epositor
y
ransferSer!iceImpl
transferSer!ice
8
Quick Start Su((ar%
Spring (anages the lifec%cle of the application
" All beans are full% initiali-ed before the% are used
.eans are al*a%s created in the right order
" .ased on their dependencies
/ach bean is bound to a uni0ue id
" The id reflects the ser'ice the bean pro'ides to clients
The ApplicationContext *orks as a container1
encapsulating the bean i(ple(entations
chosen for a gi'en deplo%(ent
" Conceals i(ple(entation details
9
Topics in this session
Spring 0uick start
!riting ben de"initions
" Configuring ob#ects
" $oing be%ond constructor instantiation
Creating an application context
&etrie'ing bean instances
Su((ar%
10
.asic Spring XML .ean
2efinition Te(plate
-Cxml !ersion&/8%A0 encoding&/4F1D0C.
-beans xmlns&/$ttp622,,,%springframe,or>%org2sc$ema2beans0
xmlns6xsi&/$ttp622,,,%,@%org2:AA82=?5Sc$ema1instance0
xsi6sc$ema5ocation&/
$ttp622,,,%springframe,or>%org2sc$ema2beans
$ttp622,,,%springframe,or>%org2sc$ema2beans2spring1beans1@%A%xsd0.
-E11 Add your bean definitions $ere 11.
-2beans.
-Cxml !ersion&/8%A0 encoding&/4F1D0C.
-beans xmlns&/$ttp622,,,%springframe,or>%org2sc$ema2beans0
xmlns6xsi&/$ttp622,,,%,@%org2:AA82=?5Sc$ema1instance0
xsi6sc$ema5ocation&/
$ttp622,,,%springframe,or>%org2sc$ema2beans
$ttp622,,,%springframe,or>%org2sc$ema2beans2spring1beans1@%A%xsd0.
-E11 Add your bean definitions $ere 11.
-2beans.
11
Si(plest 3ossible .ean
2efinition
-bean id&/ser!ice0 class&/example%Ser!iceImpl02. -bean id&/ser!ice0 class&/example%Ser!iceImpl02.
Ser!iceImpl ser!ice & ne, Ser!iceImpl()' Ser!iceImpl ser!ice & ne, Ser!iceImpl()'
&esults in 4'ia &eflection56
ApplicationContext ApplicationContext
ser!ice 1. instance of Ser!iceImpl ser!ice 1. instance of Ser!iceImpl
A class ,it$ no dependencies
12
Constructor 2ependenc%
In#ection
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-constructor1arg ref&/repository02.
-2bean.
-bean id&/repository0 class&/example%#epositoryImpl02.
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-constructor1arg ref&/repository02.
-2bean.
-bean id&/repository0 class&/example%#epositoryImpl02.
#epositoryImpl repository & ne, #epositoryImpl()'
Ser!iceImpl ser!ice & ne, Ser!iceImpl(repository)'
#epositoryImpl repository & ne, #epositoryImpl()'
Ser!iceImpl ser!ice & ne, Ser!iceImpl(repository)'
/0ui'alent to6
ApplicationContext ApplicationContext
ser!ice 1. instance of Ser!iceImpl
repository 1. instance of #epositoryImpl
ser!ice 1. instance of Ser!iceImpl
repository 1. instance of #epositoryImpl
A class ,it$ a single
dependency expected
by its constructor
13
Setter 2ependenc% In#ection
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-property name&/repository0 ref&/repository02.
-2bean.
-bean id&/repository0 class&/example%#epositoryImpl02.
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-property name&/repository0 ref&/repository02.
-2bean.
-bean id&/repository0 class&/example%#epositoryImpl02.
#epositoryImpl repository & ne, #epositoryImpl()'
Ser!iceImpl ser!ice & ne, Ser!iceImpl()'
ser!ice%set#epository(repository)'
#epositoryImpl repository & ne, #epositoryImpl()'
Ser!iceImpl ser!ice & ne, Ser!iceImpl()'
ser!ice%set#epository(repository)'
/0ui'alent to6
ApplicationContext ApplicationContext
ser!ice 1. instance of Ser!iceImpl
repository 1. instance of #epositoryImpl
ser!ice 1. instance of Ser!iceImpl
repository 1. instance of #epositoryImpl
A class ,it$ a single
dependency expected
by a setter met$od
14
!hen to ,se Constructors 's7
Setters8
Spring supports both
+ou can (ix and (atch
15
The Case for Constructors
/nforce (andator% dependencies
3ro(ote i((utabilit%
" Assign dependencies to final fields
Concise for progra((atic usage
" Creation and in#ection in one line of code
16
The Case for Setters
Allo* optional dependencies and defaults
)a'e descripti'e na(es
Inherited auto(aticall%
17
$eneral &eco((endations
9ollo* standard :a'a design guidelines
" ,se constructors to set re0uired properties
" ,se setters for optional or those *ith default 'alues
So(e classes are designed for a particular
in#ection strateg%
" In that case go *ith it1 do not fight it
.e consistent abo'e all
18
Co(bining Constructor and
Setter In#ection
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-constructor1arg ref&/reFuired0 2.
-property name&/optional0 ref&/optional0 2.
-2bean.
-bean id&/reFuired0 class&/example%#eFuiredImpl0 2.
-bean id&/optional0 class&/example%OptionalImpl0 2.
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-constructor1arg ref&/reFuired0 2.
-property name&/optional0 ref&/optional0 2.
-2bean.
-bean id&/reFuired0 class&/example%#eFuiredImpl0 2.
-bean id&/optional0 class&/example%OptionalImpl0 2.
#eFuiredImpl reFuired & ne, #eFuiredImpl()'
OptionalImpl optional & ne, OptionalImpl()'
Ser!iceImpl ser!ice & ne, Ser!iceImpl(reFuired)'
ser!ice%setOptional(optional)'
#eFuiredImpl reFuired & ne, #eFuiredImpl()'
OptionalImpl optional & ne, OptionalImpl()'
Ser!iceImpl ser!ice & ne, Ser!iceImpl(reFuired)'
ser!ice%setOptional(optional)'
/0ui'alent to6
19
In#ecting Scalar ;alues
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-property name&/stringProperty0 !alue&/foo0 2.
-2bean.
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-property name&/stringProperty0 !alue&/foo0 2.
-2bean.
Ser!iceImpl ser!ice & ne, Ser!iceImpl()'
ser!ice%setStringProperty(/foo0)'
Ser!iceImpl ser!ice & ne, Ser!iceImpl()'
ser!ice%setStringProperty(/foo0)'
/0ui'alent to6
ApplicationContext ApplicationContext
ser!ice 1. instance of Ser!iceImpl
public class Ser!iceImpl "
public !oid setStringProperty(String s) " %%% (
22 %%%
(
public class Ser!iceImpl "
public !oid setStringProperty(String s) " %%% (
22 %%%
(
20
Auto(atic ;alue T%pe
Con'ersion
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-property name&/integerProperty0 !alue&/:G0 2.
-2bean.
-bean id&/ser!ice0 class&/example%Ser!iceImpl0.
-property name&/integerProperty0 !alue&/:G0 2.
-2bean.
Ser!iceImpl ser!ice & ne, Ser!iceImpl()'
Integer !alue & :G'
ser!ice%setIntegerProperty(!alue)'
Ser!iceImpl ser!ice & ne, Ser!iceImpl()'
Integer !alue & :G'
ser!ice%setIntegerProperty(!alue)'
/0ui'alent to6
ApplicationContext ApplicationContext
ser!ice 1. instance of Ser!iceImpl
public class Ser!iceImpl "
public !oid setIntegerProperty(Integer i) " %%% (
22 %%%
(
public class Ser!iceImpl "
public !oid setIntegerProperty(Integer i) " %%% (
22 %%%
(
21
In#ecting lists
-bean id&/ser!ice0
class&/com%springsource%,are$ouse%In!entory?anagerImpl0.
-property name&/,are$ouse5ist0.
-list.
-ref bean&H,are$ouse8H2.
-ref bean&H,are$ouse:H2.
-ref bean&H,are$ouse@H2.
-2list.
-2property.
-2bean.
-bean id&/ser!ice0
class&/com%springsource%,are$ouse%In!entory?anagerImpl0.
-property name&/,are$ouse5ist0.
-list.
-ref bean&H,are$ouse8H2.
-ref bean&H,are$ouse:H2.
-ref bean&H,are$ouse@H2.
-2list.
-2property.
-2bean.
In!entory?anagerImpl manager & ne, In!entory?anagerImpl()'
manager%setIare$ouse5ist(list)' 22 create list ,it$ bean references
In!entory?anagerImpl manager & ne, In!entory?anagerImpl()'
manager%setIare$ouse5ist(list)' 22 create list ,it$ bean references
/0ui'alent to6
ApplicationContext ApplicationContext
manager 1. instance of In!entory?anagerImpl
22
In#ecting other t%pes of
collection
Si(ilar support a'ailable for
" 3roperties 4through props < prop ele(ents5
" Set 4through a set ele(ent1 si(ilar to list5
" Map 4through (ap < ke% ele(ents5
Some more ad!anced features about collections ,ill be seen later ,it$
t$e util namespace
23
Topics in this session
)o* Spring *orks
!riting Spring bean definitions
" Configuring ob#ects
" #oing beyond constructor instntition
Creating a Spring application context
&etrie'ing bean instances
Su((ar%
24
The factor%-(ethod attribute
=on-intrusi'e
" ,seful for existing Singletons or 9actories
public class 5egacySingleton "
pri!ate static 5egacySingleton inst & ne, 5egacySingleton()'
pri!ate 5egacySingleton() " %%% (
public static 5egacySingleton getInstance() "
return inst'
(
(
public class 5egacySingleton "
pri!ate static 5egacySingleton inst & ne, 5egacySingleton()'
pri!ate 5egacySingleton() " %%% (
public static 5egacySingleton getInstance() "
return inst'
(
(
-bean id&/ser!ice0 class&/example%5egacySingleton0
factory-method="getInstance" 2.
-bean id&/ser!ice0 class&/example%5egacySingleton0
factory-method="getInstance" 2.
getInstance() s$ould al,ays be static
25
3>:>s as 9actor% .eans
An% 3>:> can be used as a factor%
-bean id&/clientSer!iceFactory0 class&/example%ClientSer!iceFactory02.
-bean id&/clientSer!ice0 factory-ean=!c"#ent$er%#ce&actory'
factory1met$od&Hget+e,InstanceH.
-bean id&/clientSer!iceFactory0 class&/example%ClientSer!iceFactory02.
-bean id&/clientSer!ice0 factory-ean=!c"#ent$er%#ce&actory'
factory1met$od&Hget+e,InstanceH.
public class ClientSer!iceFactory "
%%%
public ClientSer!ice get+e,Instance() "
%%%
(
(
public class ClientSer!iceFactory "
%%%
public ClientSer!ice get+e,Instance() "
%%%
(
(
+o need for class attribute
26
The 9actor%.ean interface
3art of the Spring fra(e*ork
,sed b% (an% Spring classes
" can also choose to use this %ourself
(u"#c c"ass ClientSer!iceFactory;ean #m("ements
Factory;ean-ClientSer!ice. "
22%%%
(u"#c ClientSer!ice getOb3ect() thro)s Jxception "
return clientSer!ice'
(
(u"#c Class-C. getOb3ectype() "
return ClientSer!ice%c"ass'
(
(u"#c oo"ean isSingleton() " return true' (
(
(u"#c c"ass ClientSer!iceFactory;ean #m("ements
Factory;ean-ClientSer!ice. "
22%%%
(u"#c ClientSer!ice getOb3ect() thro)s Jxception "
return clientSer!ice'
(
(u"#c Class-C. getOb3ectype() "
return ClientSer!ice%c"ass'
(
(u"#c oo"ean isSingleton() " return true' (
(
27
The 9actor%.ean interface
.eans i(ple(enting 9actor%.ean are
auto-detected
2ependenc% in#ection using the factor% bean id
causes get>b#ect45 to be in'oked transparentl%
-bean id&/cpxSer!ice0 class&/example%ComplexSer!iceFactory0 2.
-bean id&/controller0 class&/example%?yController0.
-property name&/ser!ice0 ref&/cpxSer!ice0 2.
-2bean.
-bean id&/cpxSer!ice0 class&/example%ComplexSer!iceFactory0 2.
-bean id&/controller0 class&/example%?yController0.
-property name&/ser!ice0 ref&/cpxSer!ice0 2.
-2bean.
28
9actor%.eans in Spring
:ndi>b#ect9actor%.ean
" >ne option for looking up :=2I ob#ects
9actor%.eans for creating re(oting proxies
9actor%.eans for configuring data access
technologies like )ibernate1 :3A or i.atis
29
Topics in this session
Spring 0uick start
!riting bean definitions
" Configuring ob#ects
" $oing be%ond constructor instantiation
Creting n ppliction context
Su((ar%
30
Creating a Spring Application
Context
Spring application contexts can be bootstrapped
in an% en'iron(ent1 including
" :,nit s%ste( test
" !eb application
" /nterprise :a'a .ean 4/:.5
" Standalone application
Loadable *ith bean definitions fro( files
" In the class path
" >n the local file s%ste(
" At an en'iron(ent-relati'e resource path
31
/xa(ple6 ,sing an Application
Context Inside a :,nit S%ste( Test
import static org%3unit%Assert%K'
public !oid ransferSer!iceest "
pri!ate ransferSer!ice ser!ice'
7;efore public !oid set4p() "
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(/application1config%xml0)'
22 5oo> up t$e application ser!ice interface
ser!ice & (ransferSer!ice) context%get;ean(/transferSer!ice0)'
(
7est public !oid moneyransfer() "
Confirmation receipt &
ser!ice%transfer(ne, ?onetaryAmount(/@AA%AA0)B /80B /:0))'
assertEquals(receipt%get+e,;alance()B /9AA%AA0)'
(
(
import static org%3unit%Assert%K'
public !oid ransferSer!iceest "
pri!ate ransferSer!ice ser!ice'
7;efore public !oid set4p() "
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(/application1config%xml0)'
22 5oo> up t$e application ser!ice interface
ser!ice & (ransferSer!ice) context%get;ean(/transferSer!ice0)'
(
7est public !oid moneyransfer() "
Confirmation receipt &
ser!ice%transfer(ne, ?onetaryAmount(/@AA%AA0)B /80B /:0))'
assertEquals(receipt%get+e,;alance()B /9AA%AA0)'
(
(
ests t$e system
;ootstraps t$e system to test
32
Spring?s 9lexible &esource
Loading Mechanis(
ApplicationContext i(ple(entations ha'e
default resource loading rules
ne, ClassPat$=mlApplicationContext(/com2acme2application1config%xml0)'
ne, ClassPat$=mlApplicationContext(/com2acme2application1config%xml0)'
ne, FileSystem=mlApplicationContext(/C6LLetcLLapplication1config%xml0)'
22 absolute pat$6 C6LetcLapplication1config%xml
ne, FileSystem=mlApplicationContext(/%2application1config%xml0)'
22 pat$ relati!e to t$e JM? ,or>ing directory
ne, FileSystem=mlApplicationContext(/C6LLetcLLapplication1config%xml0)'
22 absolute pat$6 C6LetcLapplication1config%xml
ne, FileSystem=mlApplicationContext(/%2application1config%xml0)'
22 pat$ relati!e to t$e JM? ,or>ing directory
NC5ASSPAO2com2acme2application1config%xml
=mlIebApplicationContext is also a!ailable
1 $e pat$ is relati!e to t$e Ieb application
1 4sually created indirectly !ia a declaration in ,eb%xml
33
Creating a Spring Application
Context fro( Multiple 9iles
A context can be configured fro( (ultiple files
Allo*s partitioning of bean definitions into
logical groups
$enerall% a best practice to separate out
@applicationA beans fro( @infrastructureA beans
" Infrastructure often changes bet*een en'iron(ents
" /'ol'es at a different rate
34
Mixed Configuration
-beans.
-bean id&/transferSer!ice0 class&/app%impl%ransferSer!iceImpl0.
-constructor1arg ref&/account#epository0 2.
-2bean.
-bean id&/account#epository0 class&/app%impl%JdbcAccount#epository0.
-constructor1arg ref&/dataSource0 2.
-2bean.
-bean id&/dataSource0 class&/com%oracle%3dbc%pool%Oracle*ataSource0.
-property name&/4#50 !alue&/3dbc6oracle6t$in67local$ost689:86;A+<0 2.
-property name&/user0 !alue&/moneytransfer1app0 2.
-2bean.
-2beans.
-beans.
-bean id&/transferSer!ice0 class&/app%impl%ransferSer!iceImpl0.
-constructor1arg ref&/account#epository0 2.
-2bean.
-bean id&/account#epository0 class&/app%impl%JdbcAccount#epository0.
-constructor1arg ref&/dataSource0 2.
-2bean.
-bean id&/dataSource0 class&/com%oracle%3dbc%pool%Oracle*ataSource0.
-property name&/4#50 !alue&/3dbc6oracle6t$in67local$ost689:86;A+<0 2.
-property name&/user0 !alue&/moneytransfer1app0 2.
-2bean.
-2beans.
Coupled to a local Oracle en!ironment
35
-beans.
-E11 creates an in1memory database populated ,it$ test data for fast testing 11.
-bean id&HdataSourceH
class&Horg%sf,%3dbc%datasource%embedded%Jmbedded*atabaseFactory;eanH.
-property name&HdatabasePopulatorH ref&HpopulatorH2.
-2bean.
-bean id&HpopulatorH %%%.
%%%
-beans.
-E11 creates an in1memory database populated ,it$ test data for fast testing 11.
-bean id&HdataSourceH
class&Horg%sf,%3dbc%datasource%embedded%Jmbedded*atabaseFactory;eanH.
-property name&HdatabasePopulatorH ref&HpopulatorH2.
-2bean.
-bean id&HpopulatorH %%%.
%%%
3artitioning Configuration
-beans.
-bean id&/transferSer!ice0 class&/app%impl%ransferSer!iceImpl0.
-constructor1arg ref&/account#epository0 2.
-2bean.
-bean id&/account#epository0 class&/app%impl%JdbcAccount#epository0.
-constructor1arg ref&/dataSource0 2.
-2bean.
-2beans.
-beans.
-bean id&/transferSer!ice0 class&/app%impl%ransferSer!iceImpl0.
-constructor1arg ref&/account#epository0 2.
-2bean.
-bean id&/account#epository0 class&/app%impl%JdbcAccount#epository0.
-constructor1arg ref&/dataSource0 2.
-2bean.
-2beans.
+o, substitutable for ot$er en!ironments
36
.ootstrapping in /ach
/n'iron(ent
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(
/application1config%xml0B /test1infrastructure1config%xml0 )'
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(
/application1config%xml0B /test1infrastructure1config%xml0 )'
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(
/application1config%xml0B /oracle1infrastructure1config%xml0)'
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(
/application1config%xml0B /oracle1infrastructure1config%xml0)'
In the test en'iron(ent
In the production >racle en'iron(ent
37
!orking *ith prefixes
2efault rules can be o'erridden
;arious prefixes
" classpath6
" file6
" http6
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(
/config2dao1config%xml0B /config2ser!ice1config%xml0B
/file*oracle1infrastructure1config%xml0 )'
22 Create t$e application from t$e configuration
ApplicationContext context &
ne, ClassPat$=mlApplicationContext(
/config2dao1config%xml0B /config2ser!ice1config%xml0B
/file*oracle1infrastructure1config%xml0 )'
$ese prefixes can be used any,$ere Spring needs to deal ,it$
resources (not 3ust in constructor args to application context)
prefix
38
Topics in this session
)o* Spring *orks
!riting Spring bean definitions
" Configuring ob#ects
" $oing be%ond constructor instantiation
Creating a Spring application context
$etrie%ing ben instnces
Su((ar%
39
Accessing a .ean in Spring B
Cast is not co(pulsor% an%(ore
ApplicationContext context & ne, ClassPat$=mlApplicationContext(%%%)'
22 Classic ,ay6 cast is needed
ClientSer!ice ser!ice8 & (ClientSer!ice) context%get;ean(/clientSer!ice0)'
22 Since Spring @%A6 no more castB type is a met$od param
ClientSer!ice ser!ice: & context%get;ean(/clientSer!ice0B ClientSer!ice%class)'
22 +o need for bean id if type is uniFue
ClientSer!ice ser!ice@ & context%get;ean(ClientSer!ice%class )'
+e, in
Spring @%A
40
Topics in this session
)o* Spring *orks
!riting Spring bean definitions
" Configuring ob#ects
" $oing be%ond constructor instantiation
Creating a Spring application context
&etrie'ing bean instances
Summry
41
.enefits of 2ependenc%
In#ection
+our ob#ect is handed *hat it needs to *ork
" 9rees it fro( the burden of resol'ing its dependencies
" Si(plifies %our code1 i(pro'es code reusabilit%
3ro(otes progra((ing to interfaces
" Conceals the i(ple(entation details of each dependenc%
I(pro'es testabilit%
" 2ependencies can be easil% stubbed out for unit testing
Allo*s for centrali-ed control o'er ob#ect lifec%cle
" >pens the door for ne* possibilities
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibit
LA.
,sing Spring to Configure an Application
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Understanding the Bean Lifecycle
An In-depth Look at Springs Lifecycle
Management Features
2
Topics in this session
Introduction to Spring!s "ML namespaces
#S$-%&' annotations
The lifecycle of a Spring application conte(t
) The initiali*ation phase
) The use phase
) The destruction phase
Bean scoping
3
Introduction to Spring!s
+ustom "ML ,amespaces
Spring pro-ides higher-le-el configuration
languages that .uild on the generic /.eans01
language
) 2ro-ide a.straction and semantic -alidation
) Simplify common configuration needs
3ach language is defined .y its o4n "ML
namespace you may import
) 5ou can e-en 4rite your o4n
4
Importing a +ustom "ML
,amespace
<?xml version=1.0 encoding=UTF-8?>
<beans xmlns=h!"##$$$.s!ring%rame$or&.org#schema#beans
xmlns"xsi=h!"##$$$.$'.org#(001#)*+,chema-insance
xmlns"conex=h!"##$$$.s!ring%rame$or&.org#schema#conex
xsi"schema+ocaion=
h!"##$$$.s!ring%rame$or&.org#schema#beans
h!"##$$$.s!ring%rame$or&.org#schema#beans#s!ring-beans-'.0.xsd
h!"##$$$.s!ring%rame$or&.org#schema#conex
h!"##$$$.s!ring%rame$or&.org#schema#conex#s!ring-conex-'.0.xsd>
<--- .o/ can no$ /se <conex"0#> ags -->
<#beans>
1ssign names!ace a !re%ix
1ssociae names!ace $ih is ),2
5
Benefits of Using ,amespace
+onfiguration
<beans>
<bean class=org.s!ring%rame$or&.beans.%acor3.con%ig.
4ro!er34laceholder5on%ig/rer>
<!ro!er3 name=locaion val/e=#678-9:F#daaso/rce.!ro!eries #>
<#bean>
<#beans>
<beans ... >
<conex"!ro!er3-!laceholder locaion=#678-9:F#daaso/rce.!ro!eries #>
<#beans>
Before
After
;eneric bean#!ro!er3
s3nax is all ha<s available
=e>/ires remembering
%rame$or& classnames
5reaes same bean as
above? b/ hides
%rame$or& deails
1rib/es are s!eci%ic o
he as&? raher han
generic name#val/e !airs
6
,amespaces Summary
,amespace configuration is a.out simplification
and e(pressi-eness
) 6eneric .ean0property synta( can .e too lo4-le-el
) 7ides frame4ork details
,amespaces are defined for categories of
related frame4ork functionality
8
) aop9 .eans9 conte(t9 :ee9 :ms9 t(9 util
;e 4ill use namespaces to simplify
configuration throughout this training
* an incomplete list. see http://www.springframework.org/schema/ for details
7
Topics in this session
Introduction to Spring!s "ML namespaces
JSR-250 nnottions
The lifecycle of a Spring application conte(t
) The initiali*ation phase
) The use phase
) The destruction phase
Bean scoping
8
A 2rimer on #S$-%&'
<+ommon Annotations=
#S$-%&' pro-ides a set of common annotations
for use in #a-a 33 applications
) 7elps a-oid proliferation of frame4ork-specific
annotations
) Facilitates porta.ility
) Used .y 3#B >?'
) Used .y Spring9 starting 4ith -ersion %?&
9
#S$-%&' 2rimer9 cont?
All annotations reside in the :a-a(?annotation
package
) Included in the #@A starting in #a-a B
) A-aila.le as part of the !:a-aee-api! :ar for #a-a &
To name a fe4
) C2ost+onstruct
) C2re@estroy
) C$esource
Spring makes use of these annotations to
trigger lifecycle e-ents
10
Topics in this session
Introduction to Spring!s "ML namespaces
#S$-%&' annotations
!he li"ecycle o" Spring ppliction context
) The initiali*ation phase
) The use phase
) The destruction phase
Bean scoping
11
2hases of the Application
Lifecycle
9niiali@aion Use 2esr/cion
2repares for use
Application
ser-ices
) Are created
) +onfigured
) May allocate
system resources
Application is not
usa.le until this
phase is complete
Used .y clients
Application
ser-ices
) 2rocess client
reDuests
) +arry out
application
.eha-iors
EE?EEF of the
time is spent in
this phase
Shuts do4n
Application
ser-ices
) $elease any
system resources
) Are eligi.le for
gar.age
collection
12
Springs $ole as a Lifecycle
Manager
For nearly any class of application
) Standalone #a-a application
) #Unit System Test
) #a-a 33G 4e. application
) #a-a 33G enterprise application
Spring fits in to manage the application lifecycle
) 2lays an important role in all phases
13
Topics in this session
Introduction to Spring!s "ML namespaces
The lifecycle of a Spring application conte(t
) !he initili#tion phse
) The use phase
) The destruction phase
Bean scoping
9niiali@aion Use 2esr/cion
14
The Lifecycle of a Spring Application
+onte(t HIJ - The Initiali*ation 2hase
;hen a conte(t is created the initiali*ation
phase completes
But 4hat e(actly happens in this phaseK
## 5reae he a!!licaion %rom he con%ig/raion
1!!licaion5onex conex = ne$ 5lass4ah)ml1!!licaion5onexA
a!!licaion-con%ig.xml?
es-in%rasr/c/re-con%ig.xml
BC
15
Inside The Application +onte(t
Initiali*ation Lifecycle
$od ben de"initions
Initiali*e .ean instances
16
Load Bean @efinitions
The "ML files are parsed
Bean definitions are loaded into the conte(ts
8eanFacor3
D 3ach inde(ed under its id
Special 8eanFacor34os4rocessor .eans are
in-oked
D +an modify the definition of any .ean
17
1!!licaion 5onex 1!!licaion 5onex
Load Bean @efinitions
<beans>
<bean id=rans%er,ervice E
<bean id=acco/n=e!osior3E
<#beans>
<beans>
<bean id=rans%er,ervice E
<bean id=acco/n=e!osior3E
<#beans>
a!!licaion-con%ig.xml
<beans>
<bean id=daa,o/rce E
<#beans>
<beans>
<bean id=daa,o/rce E
<#beans>
es-in%rasr/c/re-con%ig.xml
rans%er,ervice
acco/n=e!osior3
rans%er,ervice
acco/n=e!osior3
8eanFacor3
8eanFacor34os4rocessors
!os4rocessA8eanFacor3B
rans%er,ervice
acco/n=e!osior3
daa,o/rce
rans%er,ervice
acco/n=e!osior3
daa,o/rce
5an modi%3 he de%iniion o%
an3 bean in he %acor3
be%ore an3 obFecs are creaed
18
The BeanFactory2ost2rocessor
3(tension 2oint
Useful for applying transformations to groups of
.ean definitions
) Before any o.:ects are actually created
Se-eral useful implementations are pro-ided .y
the frame4ork
5ou can also 4rite your o4n
) Implement the BeanFactory2ost2rocessor interface
19
An 3(ample
BeanFactory2ost2rocessor
D
PropertyPlaceholderConfigurer su.stitutes
LM-aria.lesN in .ean definitions 4ith -alues
from ?properties files
20
7o4 2roperty2laceholder+onfigurer
;orks
4ro!er34laceholder5on%ig/re
r
,!ring 1!!licaion 5onex
Aa%er bean de%iniions are loadedB
!os4rocessA8eanFacor3B
8ean de%iniion
daa,o/rce
U=+=GHdaaso/rce./rlI
/ser=GHdaaso/rce./serI
8ean de%iniion
daa,o/rce
U=+=Fdbc"oracle"E
/ser=mone3rans%er-a!!
21
Using
2roperty2laceholder+onfigurer
<beans>
<bean id=daa,o/rce class=com.oracle.Fdbc.!ool.Jracle2aa,o/rce>
<!ro!er3 name=U=+ val/e=GHdaaso/rce./rlI #>
<!ro!er3 name=/ser val/e=GHdaaso/rce./serI #>
<#bean>
<bean class=org.s!ring%rame$or&.beans.%acor3.con%ig.
4ro!er34laceholder5on%ig/rer>
<!ro!er3 name=locaion val/e=#678-9:F#daaso/rce.!ro!eries #>
<#bean>
<#beans>
File $here he variable
val/es reside
datasource.url!d"c#oracle#thin#$localhost#1521#%&'(
datasource.user)oneytransfer*app
daaso/rce.!ro!eries
Kariables o re!lace
7asil3 ediable
22
Simplifying configuration 4ith
/conte(tOproperty-placeholder1
<beans ... >
<bean id=daa,o/rce class=com.oracle.Fdbc.!ool.Jracle2aa,o/rce>
<!ro!er3 name=U=+ val/e=GHdaaso/rce./rlI #>
<!ro!er3 name=/ser val/e=GHdaaso/rce./serI #>
<#bean>
<conex"!ro!er3-!laceholder locaion=#678-9:F#daaso/rce.!ro!eries #>
<#beans>
5reaes he same 4ro!er34laceholder5on%ig/rer
bean de%iniion in a more concise %ashion
23
Inside the Application +onte(t
Initiali*ation Lifecycle
Load .ean definitions
%nitili#e ben instnces
24
Initiali*ing Bean Instances
3ach .ean is eagerly instantiated .y default
) +reated in the right order 4ith its dependencies
in:ected
After dependency in:ection each .ean goes
through a post-processing phase
) ;here further configuration and initiali*ation can
occur
After post processing the .ean is fully
initiali*ed and ready for use
) Tracked .y its id until the conte(t is destroyed
25
Bean Initiali*ation Steps
8ean
9nsaniaed
8ean
9nsaniaed
2e!endencies
9nFeced
2e!endencies
9nFeced
8ean 4os
4rocessed
8ean 4os
4rocessed
8ean
=ead3
For Use
8ean
=ead3
For Use
26
Bean 2ost 2rocessing
Bean post processing can .e .roken do4n into
t4o steps
) Initiali*e the .ean if instructed
) +all special 8ean4os4rocessors to perform additional
configuration
27
Bean 2ost 2rocessing Steps
%nitili#e the ben i" instructed
+all special 8ean4os4rocessors to perform
additional configuration
28
Initiali*e the Bean if
Instructed
A .ean can optionally register for one or more
initiali*ation call.acks
) Useful for e(ecuting custom initiali*ation .eha-iors
There!s more than one 4ay to do it
) #S$-%&' C2ost+onstruct
) /.ean01 init-method attri.ute
) Implement Spring!s Initiali*ingBean interface
29
Bean Initiali*ation
TechniDues
&'ostConstruct
init-method
Initiali*ingBean
30
$egistering for Initiali*ation
4ith C2ost+onstruct
!/blic class Trans%er,ervice9m!l H
L4os5onsr/c
void iniAB H
## 3o/r c/som iniiali@aion code
I
I
!/blic class Trans%er,ervice9m!l H
L4os5onsr/c
void iniAB H
## 3o/r c/som iniiali@aion code
I
I
:o resricions on
mehod name or visibili3
Tells ,!ring o call his
mehod a%er
de!endenc3 inFecion
This is the preferred initiali*ation techniDue
) Fle(i.le9 a-oids depending on Spring A2Is
) $eDuires Spring %?& or .etter
31
3na.ling +ommon Annotation-
Based Initiali*ation
C2ost+onstruct 4ill .e ignored unless Spring is
instructed to detect and process it
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice9m!l #>
<bean class=org.s!ring%rame$or&.conex.annoaion.
5ommon1nnoaion8ean4os4rocessor #>
<#beans>
2eecs and invo&es an3
mehods annoaed $ih
L4os5onsr/c
32
Simplifying +onfiguration 4ith
/conte(tOannotation-config1
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice9m!l #>
<conex"annoaion-con%ig#>
<#beans>
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice9m!l #>
<conex"annoaion-con%ig#>
<#beans>
7nables m/li!le 8ean4os4rocessors? incl/ding"
=e>/ired1nnoaion8ean4os4rocessor
5ommon1nnoaion8ean4os4rocessor
33
Bean Initiali*ation
TechniDues
C2ost+onstruct
init-method
Initiali*ingBean
34
Initiali*ing a Bean 5ou @o
,ot +ontrol
Use init-method to initiali*e a .ean you do not
control the implementation of
<bean id=bro&er
class=org.a!ache.acivem>.bro&er.8ro&er,ervice
ini-mehod=sar>
E
<#bean>
*ehod can be an3 visibili3? b/ m/s have no arg/mens
5lass $ih no ,!ring de!endenc3
35
Bean Initiali*ation
TechniDues
C2ost+onstruct
init-method
%nitili#ing(en
36
$egistering for an
Initiali*ation +all.ack 4ith
Initiali*ingBean
Initiali*ation techniDue used prior to Spring %?&
) @isad-antageO Ties your code to the frame4ork
) Ad-antageO The only 4ay to enforce initiali*ation
code should run Hnot affected .y configuration
changesJ
!ac&age org.s!ring%rame$or&.beans.%acor3C
!/blic iner%ace 9niiali@ing8ean H
!/blic void a%er4ro!eries,eABC
I
37
!/blic class *essage=eceiver im!lemens 9niiali@ing8ean H
!/blic void a%er4ro!eries,eAB H
## allocae message receiving reso/rces
I
I
<beans>
<bean id=message=eceiver class=exam!le.*essage=eceiver #>
<#beans>
9m!lemens
s!ecial ,!ring
li%ec3cle iner%ace
,!ring invo&es mehod a/omaicall3
:o oher con%ig/raion re>/ired
$egistering for an
Initiali*ation +all.ack 4ith
Initiali*ingBean
38
Bean 2ost 2rocessing Steps
Initiali*e the .ean if instructed
Cll specil %eanPostProcessors to per"orm
dditionl con"igurtion
39
The Bean2ost2rocessor
3(tension 2oint
An important e(tension point in Spring
+an modify .ean instances in any 4ay
) 2o4erful ena.ling feature
Se-eral implementations are pro-ided .y the
frame4ork
,ot common to 4rite your o4n
40
An 3(ample
Bean2ost2rocessor
$eDuiredAnnotationBean2ost2rocessor
) 2ro-ided .y the frame4ork
) 3nforces that &Re)uired properties are set
) Must .e e(plicitly ena.led -ia configuration
41
Using
$eDuiredAnnotationBean2ost2rocessor
!/blic class Trans%er,ervice9m!l im!lemens Trans%er,ervice H
!rivae 1cco/n=e!osior3 acco/n=e!osior3C
L=e>/ired
!/blic void se1cco/n=e!osior3A1cco/n=e!osior3 arB H
his.acco/n=e!osior3 = arC
I
I
!/blic class Trans%er,ervice9m!l im!lemens Trans%er,ervice H
!rivae 1cco/n=e!osior3 acco/n=e!osior3C
L=e>/ired
!/blic void se1cco/n=e!osior3A1cco/n=e!osior3 arB H
his.acco/n=e!osior3 = arC
I
I
9ndicaes he de!endenc3
is re>/ired
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice9m!l #>
<bean class=org.s!ring%rame$or&.beans.%acor3.annoaion.
=e>/ired1nnoaion8ean4os4rocessor #>
<#beans>
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice9m!l #>
<bean class=org.s!ring%rame$or&.beans.%acor3.annoaion.
=e>/ired1nnoaion8ean4os4rocessor #>
<#beans>
1/omaicall3 deecedC no oher con%ig/raion is necessar3
Property 'accountRepository' is
required for bean 'transferService'
42
Simplifying +onfiguration
4ith /conte(tOannotation-config1
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice9m!l #>
<conex"annoaion-con%ig#>
<#beans>
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice9m!l #>
<conex"annoaion-con%ig#>
<#beans>
1/omaicall3 enables =e>/ired1nnoaion8ean4os4rocessor
$emem.er /conte(tOannotation-config1K
43
Topics in this session
Introduction to Spring!s "ML namespaces
The lifecycle of a Spring application conte(t
) The initiali*ation phase
) !he use phse
) The destruction phase
Bean scoping
Use 2esr/cion 9niiali@aion
44
The Lifecycle of a Spring Application
+onte(t H%J - The Use 2hase
;hen you in-oke a .ean o.tained from the
conte(t the application is used
But e(actly 4hat happens in this phaseK
1!!licaion5onex conex = ## ge i %rom some$here
## +oo&/! he enr3 !oin ino he a!!licaion
Trans%er,ervice service =
ATrans%er,erviceB conex.ge8eanArans%er,erviceBC
## Use i-
service.rans%erAne$ *onear31mo/nAM0.00B? 1? (BC
45
Inside The Bean $eDuest
HUseJ Lifecycle
If the .ean is :ust your ra4 o.:ect it is simply
in-oked directly Hnothing specialJ
If your .ean has .een 4rapped in a pro(y
things get more interesting
Trans%er,ervice9m!l
rans%erAGM0? 1? (B
rans%erAGM0? 1? (B
Trans%er,ervice9m!l
,!ring 4rox3
46
2ro(y 2o4er
A 8ean4os4rocessor may 4rap your .eans in a
dynamic pro(y and add .eha-ior to your
application logic transparently
Trans%er,ervice9m!l
rans%erAGM0? 1? (B
,!ring
Transacion9nerce!or
Transacion*anager
begin commi
Transacion
managemen
behavior is added
aro/nd 3o/r code
,!ring 4rox3
47
2ro(ies are +entral to the Spring
Triangle
Simple
Object
*
e
p
e
n
d
e
n
c
y
%
n
+
e
c
t
i
o
n
,
s
p
e
c
t
-
-
r
i
e
n
t
e
d
'
r
o
g
r
m
m
i
n
g
.nterprise Ser/ice ,bstrctions
1. The 1!!licaion
conex drives bean
con%ig/raion
(. 23namic !roxies
add behaviors o
3o/r beans
'. ,!ring can inegrae man3
ener!rise behaviors
48
Bean Initiali*ation Steps
8ean
9nsaniaed
8ean
9nsaniaed
2e!endencies
9nFeced
2e!endencies
9nFeced
8ean 4os
4rocessed
8ean 4os
4rocessed
8ean
=ead3
For Use
8ean
=ead3
For Use
4roxies are
creaed here
49
Topics in this session
9niiali@aion
Introduction to Spring!s "ML namespaces
The lifecycle of a Spring application conte(t
) The initiali*ation phase
) The use phase
) !he destruction phse
Bean scoping
Use 2esr/cion
50
The Lifecycle of a Spring Application
+onte(t H>J - The @estruction 2hase
;hen you close a conte(t the destruction phase
completes
But e(actly 4hat happens in this phaseK
5on%ig/rable1!!licaion5onex conex = E
## 2esro3 he a!!licaion
conex.closeABC
51
Inside the Application
+onte(t @estruction Lifecycle
@estroy .ean instances if instructed
@estroy itself
) The conte(t is not usa.le again
52
@estroy Bean Instances if
Instructed
A .ean can optionally register for one or more
destruction call.acks
) Useful for releasing resources and !cleaning up!
There!s more than one 4ay to do it
) #S$-%&' C2re@estroy
) /.ean01 destroy-method attri.ute
) Implement Spring!s @isposa.leBean interface
53
Bean @estruction TechniDues
&'re*estroy
destroy-method
@isposa.leBean
54
$egistering for @estruction
4ith C2re@estroy
!/blic class Trans%er,ervice9m!l H
L4re2esro3
void release=eso/rcesAB H
## 3o/r c/som desr/cion code
I
I
!/blic class Trans%er,ervice9m!l H
L4re2esro3
void release=eso/rcesAB H
## 3o/r c/som desr/cion code
I
I
:o resricions on mehod
name or visibili3
Tells ,!ring o call his
mehod !rior o desro3ing he
bean insance
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice9m!l #>
<conex"annoaion-con%ig#>
<#beans>
<beans>
<bean id=rans%er,ervice class=exam!le.Trans%er,ervice9m!l #>
<conex"annoaion-con%ig#>
<#beans>
7nables common
annoaion !rocessing
55
Bean @estruction TechniDues
C2re@estroy
destroy-method
@isposa.leBean
56
@estroying a Bean 5ou @o
,ot +ontrol
Use destroy-method to dispose a .ean you do
not control the implementation of
<bean id=daa,o/rce
class=org.a!ache.commons.dbc!.8asic2aa,o/rce
desro3-mehod=close>
E
<#bean>
*ehod can be an3 visibili3? b/ m/s have no arg/mens
5lass $ih no ,!ring de!endenc3
57
Bean @estruction TechniDues
C2re@estroy
destroy-method
*isposble(en
58
$egistering for a @estruction
+all.ack 4ith @isposa.leBean
$egister for a .ean destruction call.ack .y
implementing the +isposa"le%ean interface
Spring in-okes this method at the right time
!ac&age org.s!ring%rame$or&.beans.%acor3C
!/blic iner%ace 2is!osable8ean H
!/blic void desro3ABC
I
59
Topics in this session
Introduction to Spring!s "ML namespaces
#S$-%&' annotations
The lifecycle of a Spring application conte(t
) The initiali*ation phase
) The use phase
) The destruction phase
(en scoping
60
Bean Scoping
Spring puts each .ean instance in a scope
Singleton scope is the default
) The <single= instance is scoped .y the conte(t itself
) By far the most common
Pther scopes can .e used on a .ean-.y-.ean
.asis
<bean id=m38ean class=exam!le.*38ean
sco!e=E>
<#bean>
4/ his bean in some oher sco!e
61
A-aila.le Scopes
D
prototype - A ne4 instance is created each time
the .ean is referenced
D
session - A ne4 instance is created once per
user session
D
re,uest - A ne4 instance is created once per
reDuest
D
custo) - 5ou define your o4n rules
) Ad-anced feature
62
Scoped @ependencies of
Singletons
Session-9 reDuest- or custom-scoped .eans often
act as dependency of singleton
;hat 4ill happen in this caseK
<bean id=Nsho!!ing,erviceN class=Nexam!le.,ho!!ing,ervice9m!lN>
<!ro!er3 name=Nsho!!ing5arN re%=Nsho!!ing5arN#>
<#bean>
<bean id=Nsho!!ing5arN class=Nexam!le.,ho!!ing5arN scope-session-#>
63
Pne-time In:ection
Singleton 4ill only .e in:ected once, on startup
,o current 7TT2 Session9 so you!ll get an error
) 3-en if there 4as a Session9 the ser-ice 4ould use the
same Shopping+art e-ery time
+ould fi( .y using lookup instead of in:ection
) In:ect the conte(t and call 1!!licaion5onex.ge8ean
) UglyO ties your code to Spring9 hard to test
<bean id=Nsho!!ing,erviceN class=Nexam!le.,ho!!ing,ervice9m!lN>
<!ro!er3 name=Nsho!!ing5arN re%=Nsho!!ing5arN#>
<#bean>
<bean id=Nsho!!ing5arN class=Nexam!le.,ho!!ing5arN sco!e=NsessionN#>
64
Scoped 2ro(ies
Solution is to proxy the scoped dependency
2ro(y delegates to correct instance for current
reDuest or session or custom conte(t
Same pro(y can .e used .y singleton for its
entire lifecycle9 so dependency in:ection 4orks
Built-in feature of Spring using ao! namespaceO
<bean id=Nsho!!ing,erviceN class=Nexam!le.,ho!!ing,ervice9m!lN>
<!ro!er3 name=Nsho!!ing5arN re%=Nsho!!ing5arN#>
<#bean>
<bean id=Nsho!!ing5arN class=Nexam!le.,ho!!ing5arN sco!e=NsessionN>
.aop#scoped*pro/y01
<#bean>
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
LAB
Understanding the Bean Lifecycle
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Simplifying Application
Configuration
Techniques for Creating Reusable and
Concise Bean Definitions
2
Topics in this session
Bean e!inition "nheritance
Inner Beans
Property ditors
Importing Configuration !iles
Bean "aming
The p "amespace
The util "amespace
Spring #pression $anguage
3
Bean Definition Inheritance
%&'
Sometimes se(eral beans need to be configured
in the same )ay
*se bean definition inheritance to define the
common configuration once
+ Inherit it )here needed
4
,ithout Bean Definition
Inheritance
<beans>
<bean id=pool-A class=com.oracle.jdbc.pool.OracleDataSource>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-a"%&'%"(A)* +>
<property name=user !alue=moneytrans,er-app +>
<+bean>
<bean id=pool-( class=com.oracle.jdbc.pool.OracleDataSource>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-b"%&'%"(A)* +>
<property name=user !alue=moneytrans,er-app +>
<+bean>
<bean id=pool-- class=com.oracle.jdbc.pool.OracleDataSource>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-c"%&'%"(A)* +>
<property name=user !alue=moneytrans,er-app +>
<+bean>
<+beans>
<beans>
<bean id=pool-A class=com.oracle.jdbc.pool.OracleDataSource>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-a"%&'%"(A)* +>
<property name=user !alue=moneytrans,er-app +>
<+bean>
<bean id=pool-( class=com.oracle.jdbc.pool.OracleDataSource>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-b"%&'%"(A)* +>
<property name=user !alue=moneytrans,er-app +>
<+bean>
<bean id=pool-- class=com.oracle.jdbc.pool.OracleDataSource>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-c"%&'%"(A)* +>
<property name=user !alue=moneytrans,er-app +>
<+bean>
<+beans>
-an you ,ind t#e duplication.
5
,ith Bean Definition
Inheritance
<beans>
<bean id=abstract/ool
class=com.oracle.jdbc.pool.OracleDataSource abstract=true>
<property name=user !alue=moneytrans,er-app +>
<+bean>
<bean id=pool-A parent=abstractPool>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-a"%&'%"(A)* +>
<+bean>
<bean id=pool-( parent=abstractPool>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-b"%&'%"(A)* +>
<+bean>
<bean id=pool-- parent=abstractPool>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-c"%&'%"(A)* +>
<+bean>
<+beans>
<beans>
<bean id=abstract/ool
class=com.oracle.jdbc.pool.OracleDataSource abstract=true>
<property name=user !alue=moneytrans,er-app +>
<+bean>
<bean id=pool-A parent=abstractPool>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-a"%&'%"(A)* +>
<+bean>
<bean id=pool-( parent=abstractPool>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-b"%&'%"(A)* +>
<+bean>
<bean id=pool-- parent=abstractPool>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-c"%&'%"(A)* +>
<+bean>
<+beans>
0ill not be instantiated
1ac# pool in#erits its parent con,i2uration
6
-(erriding Parent Bean Configuration
<beans>
<bean id=de,ault/ool class=com.oracle.jdbc.pool.OracleDataSource>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-a"%&'%"(A)* +>
<property name=user !alue=moneytrans,er-app +>
<+bean>
<bean id=pool-( parent=de,ault/ool>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-b"%&'%"(A)* +>
<+bean>
<bean id=pool-- parent=de,ault/ool class=e3ample.SomeOt#er/ool>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-c"%&'%"(A)* +>
<+bean>
<+beans>
<beans>
<bean id=de,ault/ool class=com.oracle.jdbc.pool.OracleDataSource>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-a"%&'%"(A)* +>
<property name=user !alue=moneytrans,er-app +>
<+bean>
<bean id=pool-( parent=de,ault/ool>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-b"%&'%"(A)* +>
<+bean>
<bean id=pool-- parent=de,ault/ool class=e3ample.SomeOt#er/ool>
<property name=UR !alue=jdbc"oracle"t#in"$ser!er-c"%&'%"(A)* +>
<+bean>
<+beans>
)ot abstract4 acts as a concrete de,ault
O!errides class as 5ell
O!errides UR property
7
Topics in this session
Bean Definition Inheritance
"nner Beans
Property ditors
Importing Configuration !iles
Bean "aming
The p "amespace
The util "amespace
Spring #pression $anguage
8
Inner Beans
Sometimes a bean naturally scopes the
definition of another bean
+ The .scoped/ bean is not useful to anyone else
0a1e the scoped bean an inner bean
+ 0ore manageable
+ A(oids polluting the bean namespace
9
,ithout an Inner Bean
<beans>
<bean id=restaurantRepository
class=re5ards.internal.restaurant.6dbcRestaurantRepository>
<property name=dataSource re,=dataSource +>
<property name=bene,itA!ailability/olicy7actory re,=,actory +>
<+bean>
<bean id=,actory
class=re5ards.internal.restaurant.a!ailability.
De,ault(ene,itA!ailability/olicy7actory>
<constructor-ar2 re,=re5ard8istorySer!ice +>
<+bean>
9
<+beans>
<beans>
<bean id=restaurantRepository
class=re5ards.internal.restaurant.6dbcRestaurantRepository>
<property name=dataSource re,=dataSource +>
<property name=bene,itA!ailability/olicy7actory re,=,actory +>
<+bean>
<bean id=,actory
class=re5ards.internal.restaurant.a!ailability.
De,ault(ene,itA!ailability/olicy7actory>
<constructor-ar2 re,=re5ard8istorySer!ice +>
<+bean>
9
<+beans>
-an be re,erenced by ot#er beans
:e!en i, it s#ould not be;
10
,ith an Inner Bean
<beans>
<bean id=restaurantRepository
class=re5ards.internal.restaurant.6dbcRestaurantRepository>
<property name=dataSource re,=dataSource +>
<property name=bene,itA!ailability/olicy7actory>
<bean class=re5ards.internal.restaurant.a!ailability.
De,ault(ene,itA!ailability/olicy7actory>
<constructor-ar2 re,=re5ard8istorySer!ice +>
<+bean>
<+property>
<+bean>
9
<+beans>
<nner bean #as no id :it is anonymous;
-annot be re,erenced outside t#is scope
11
<beans>
<bean id=restaurantRepository
class=re5ards.internal.restaurant.6dbcRestaurantRepository>
<property name=dataSource re,=dataSource +>
<property name=bene,itA!ailability/olicy7actory>
<bean class=re5ards.internal.restaurant.a!ailability.
De,ault(ene,itA!ailability/olicy7actory>
<constructor-ar2>
<bean class=re5ards.internal.re5ards.6dbcRe5ard8istory>
<property name=dataSource re,=dataSource +>
<+bean>
<+constructor-ar2>
<+bean>
<+property>
<+bean>
<+beans>
<beans>
<bean id=restaurantRepository
class=re5ards.internal.restaurant.6dbcRestaurantRepository>
<property name=dataSource re,=dataSource +>
<property name=bene,itA!ailability/olicy7actory>
<bean class=re5ards.internal.restaurant.a!ailability.
De,ault(ene,itA!ailability/olicy7actory>
<constructor-ar2>
<bean class=re5ards.internal.re5ards.6dbcRe5ard8istory>
<property name=dataSource re,=dataSource +>
<+bean>
<+constructor-ar2>
<+bean>
<+property>
<+bean>
<+beans>
0ultiple $e(els of "esting
12
Topics in this session
Bean Definition Inheritance
Inner Beans
#roperty $ditors
Importing Configuration !iles
Bean "aming
The p "amespace
The util "amespace
Spring #pression $anguage
13
Introducing Propertyditor
%&'
In 20$ all literal (alues are te#t strings
In your code there are often rich ob3ect types
<bean id=p#one=alidator class=sample./#one=alidator>
<property name=pattern !alue=>?-@ABCD->?-@ABCD->?-@ABED +>
<+bean>
<bean id=p#one=alidator class=sample./#one=alidator>
<property name=pattern !alue=>?-@ABCD->?-@ABCD->?-@ABED +>
<+bean>
public class /#one=alidator B
pri!ate /attern pattern4
public !oid set/attern:/attern pattern; B
t#is.pattern = pattern4
D
D
public class /#one=alidator B
pri!ate /attern pattern4
public !oid set/attern:/attern pattern; B
t#is.pattern = pattern4
D
D
A ric# object 5it# be#a!ior
A te3t strin2
14
Introducing Propertyditor
%4'
5our code should not be burdened )ith the
responsibility of type con(ersion
Spring )ill con(ert for you using a PropertyEditor
+ Comes )ith many property editors pre6installed
+ 5ou may )rite and install your o)n
15
Built6In Propertyditor
implementations
See the or2.sprin2,rame5orF.beans.propertyeditor
pac1age
Some highlights
G -ustom)umber1ditor con(erts to the "umber types
G -ustom(oolean1ditor con(erts to Boolean
G -ustomDate1ditor con(erts to 3a(a7util7Date
G Resource(undle1ditor con(erts to a Resource
G /roperties1ditor con(erts to 3a(a7util7Properties
G (yteArray/roperty1ditor con(erts to a byte89
G ocale1ditor con(erts to a $ocale
16
Built6In Propertyditor
#ample
<bean id=session7actory
class=or2.sprin2,rame5orF.orm.#ibernateC.support.
ocalSession7actory(ean>
9
<property name=#ibernate/roperties>
<!alue>
#ibernate.,ormatHsIl=true
#ibernate.jdbcHbatc#HsiJe=C?
<+!alue>
<+property>
<+bean>
public class ocalSession7actory(ean B
public !oid set8ibernate/roperties:/roperties p; B 9
D
Strin2-encoded properties
Kyped ja!a.util./roperties object
17
Implementing 5our -)n
Propertyditor
Create a custom editor by e#tending /roperty1ditorSupport
-(erride setAsKe3t:Strin2; to con(ert from String
-(erride 2etAsKe3t:; to format the (alue %optional'
public class /attern1ditor e3tends /roperty1ditorSupport B
public !oid setAsKe3t:Strin2 te3t; B
set=alue:te3t L= null . /attern.compile:te3t; " null;4
D
public Strin2 2etAsKe3t:; B
/attern !alue = :/attern; 2et=alue:;4
return :!alue L= null . !alue.pattern:; " ;4
D
D
public class /attern1ditor e3tends /roperty1ditorSupport B
public !oid setAsKe3t:Strin2 te3t; B
set=alue:te3t L= null . /attern.compile:te3t; " null;4
D
public Strin2 2etAsKe3t:; B
/attern !alue = :/attern; 2et=alue:;4
return :!alue L= null . !alue.pattern:; " ;4
D
D
-on!erts ,rom Strin2
18
Installing your Custom
Property ditor
*se a -ustom1ditor-on,i2urer to install your
custom editor %a (ean7actory/ost/rocessor'
<bean class=or2.sprin2,rame5orF.beans.,actory.con,i2.
-ustom1ditor-on,i2urer>
<property name=custom1ditors>
<map>
<entry Fey=ja!a3.util.re2e3./attern
!alue=e3ample./attern1ditor +>
<+map>
<+property>
<+bean>
7ully-Iuali,ied con!ertible type
K#e /roperty1ditor to
per,orm con!ersions
to t#at type
*A PatternEditor implementation is built-in as of Spring 2.0.1
19
Topics in this session
Bean Definition Inheritance
Inner Beans
Property ditors
"mporting Con!iguration %iles
Bean "aming
The p "amespace
The util "amespace
Spring #pression $anguage
20
Importing Config !iles %&'
*se the import tag to encapsulate including
another configuration file
<beans>
<import resource=accounts+account-con,i2.3ml +>
<import resource=restaurant+restaurant-con,i2.3ml +>
<import resource=re5ards+re5ards-con,i2.3ml +>
<+beans>
application-con,i2.3ml
<beans>
<import resource=application-con,i2.3ml+>
<bean id=dataSource class=e3ample.KestDataSource7actory +>
<+beans>
system-test-con,i2.3ml
ne5 -lass/at#MmlApplication-onte3t:system-test-con,i2.3ml;4
-lient only imports one ,ile
21
Importing Config !iles %4'
import tag uses relati(e path by default
This can be o(erriden using prefi#es
<beans>
<import resource=account-con,i2.3ml +>
<import resource=re5ards-con,i2.3ml +>
...
<+beans>
<beans>
<import resource=classpat#"com+sprin2source+account-con,i2.3ml +>
...
<+beans>
22
Importing Configuration !iles
%:'
Promotes splitting configuration into logical groups of
bean definitions
nables reuse across modules )ithin an application
Complements the option of creating an
ApplicationConte#t from multiple files
Application-onte3t conte3t =
ne5 -lass/at#MmlApplication-onte3t:
ne5 Strin2> A B
classpat#"com+module%+module-con,i2.3mlN
classpat#"com+module'+module-con,i2.3ml
D;4
23
Topics in this session
Bean Definition Inheritance
Inner Beans
Property ditors
Importing Configuration !iles
Bean &aming
The p "amespace
The util "amespace
Spring #pression $anguage
24
Bean "aming
0ost beans are assigned a unique name )ith the id
attribute
As an 20$ ID this attribute has se(eral limitations
+ Can only hold a single (alue
+ Some special characters cannot be used %' ('
<bean id=dataSource 9+>
<bean id=dataource!a 9+>
O+P not allo5ed
25
Assigning a Bean 0ultiple
"ames
*se the name attribute )hen special characters
are needed
Also consider it )hen you need to assign a bean
multiple names
<bean name=dataSource+primary 9+>
<bean name=dataSourceN dataSource+primary 9+>
26
Topics in this session
Bean Definition Inheritance
Inner Beans
Property ditors
Importing Configuration !iles
Bean "aming
)he p &amespace
The util "amespace
Spring #pression $anguage
27
Shortcut to specifying bean
properties
After;
<bean name=e3ample class=com.,oo.13ample>
<property name=email !alue=,oo$,oo.com+>
<+bean>
<bean name=e3ample class=com.,oo.13ample
p"email=,oo$,oo.com+>
The p namespace allo)s properties to be set as
an attribute to the bean definition
Before;
28
Shortcut to specifying bean
references
<bean name=e3ample class=com.,oo.13ample>
<property name=dataSource re,=dataSource+>
<+bean>
<bean name=e3ample class=com.,oo.13ample
p"dataSource-re,=dataSource+>
References to other beans require the format
p:<property-name>-ref=<reference>
Before;
After;
29
Considerations of the p
namespace
Requires a namespace definition;
"amespace not specified in an 2SD file< unli1e
other Spring namespaces
+ So no e#tra schema$ocation entry required
3mlns"p=#ttp"++555.sprin2,rame5orF.or2+sc#ema+p
30
Topics in this session
Bean Definition Inheritance
Inner Beans
Property ditors
Importing Configuration !iles
Bean "aming
The p "amespace
)he util &amespace
Spring #pression $anguage
31
Spring=s *til "amespace
*util('+ is one of the .out6of6the6bo#/ namespaces you
can import
-ffers high6le(el configuration for common utility tas1s
+ Populating collections
+ Accessing constants %static fields'
+ $oading properties
Also possible to load collections using the default .beans/
namespace
+ Collections in the .util/ namespace propose some more
ad(anced features
32
Configuring a $ist
<bean id=in!entoryQana2er class=,oo.Qy<n!entoryQana2er>
<property name=5are#ouses>
<util"list>
<re, bean=primary0are#ouse +>
<re, bean=secondary0are#ouse +>
<bean class=,oo.0are#ouse 9+>
<+util"list>
<+property>
<+bean>
<bean id=primary0are#ouse ...+>
<bean id=secondary0are#ouse ...+>
1lements are beans :one inner;
ist is an inner bean
33
Ad(anced configuration
<bean id=in!entoryQana2er class=,oo.Qy<n!entoryQana2er>
<property name=5are#ouses>
<util"list list-class=ja!a.util.Arrayist
!alue-type=,oo.0are#ouse>
<re, 9 +>
<+util"list>
<+property>
<+bean>
De,ault 6a!a type ,or
nested !alues
ist implementation
instantiated by Sprin2
34
Configuring a Set
<bean id=noti,icationSer!ice class=,oo.Qy)oti,icationSer!ice>
<property name=subscribers re,=subscribers+>
<+bean>
<util"set id=subscribers>
<!alue>larry$,oo.com<+!alue>
<!alue>curly$,oo.com<+!alue>
<!alue>moe$,oo.com<+!alue>
<+util"set>
1lements are literal !alues
Set is a top-le!el bean.
id is reIuired
35
Configuring a 0ap %&'
<bean id=in!entoryQana2er class=,oo.Qy<n!entoryQana2er>
<property name=5are#ouses>
<util"map>
<entry Fey=primary !alue-re,=primary0are#ouse +>
<entry Fey=secondary>
<bean class=,oo.0are#ouse 9+>
<+entry>
<+util"map>
<+property>
<+bean>
<bean id=primary0are#ouse ...+>
=alue is a top-le!el bean
=alue is an inner bean
36
Configuring a 0ap %4'
<bean id=in!entoryQana2er class=,oo.Qy<n!entoryQana2er>
<property name=5are#ouses>
<util"map>
<entry>
<Fey>
<bean class=,oo.0are#ouse*ey>
<constructor-ar2 !alue=%'CE&RST@ +>
<+bean>
<+Fey>
<bean class=,oo.0are#ouse 9+>
<+entry>
<+util"map>
<+property>
<+bean>
<bean id=in!entoryQana2er class=,oo.Qy<n!entoryQana2er>
<property name=5are#ouses>
<util"map>
<entry>
<Fey>
<bean class=,oo.0are#ouse*ey>
<constructor-ar2 !alue=%'CE&RST@ +>
<+bean>
<+Fey>
<bean class=,oo.0are#ouse 9+>
<+entry>
<+util"map>
<+property>
<+bean>
*ey is an inner bean
37
Accessing Constants
<bean id=noti,icationSer!ice
class=e3ample.Qy)oti,icationSer!ice>
<property name=#ttp/ort>
<util"constant static-,ield=e3ample.Qy-onstants.8KK/H/ORK +>
<+property>
<+bean>
Accesses static ,ield in t#e Qy-onstants class
public class Qy-onstants B
...
public static ,inal int HTTP_POT = T?4
...
D
38
$oading Properties
<bean id=noti,icationSer!ice
class=e3ample.Qy)oti,icationSer!ice>
<property name=emailQappin2s>
<util"properties location=classpat#"mail.properties +>
<+property>
<+bean>
oads a ja!a.util./roperties ,rom t#e location
39
Topics in this session
Bean Definition Inheritance
Inner Beans
Property ditors
Importing Configuration !iles
Bean "aming
The p "amespace
The util "amespace
Spring $xpression ,anguage
40
Spring #pression $anguage
Spring :7> introduces ne) #pression $anguage
+ Sp$ for short
*se programmatically< )ith 20$ or annotations
Inspired by ,eb!lo) $< superset of unified $
+ Property ? inde#ed collections access< incl7 filtering
and pro3ection
+ !unctions< operators< etc7
+ Can also call methods@constructors
Pluggable@e#tendable by other Spring6based
frame)or1s
41
Sp$ Conte#t Attributes
$ Attributes can be;
+ "amed Spring beans
+ Implicit references
Some global implicit references;
+ system/roperties
+ system1n!ironment
0ore a(ailable in )eb applications
#tensible through API
+ e7g7 Spring Security adds AprincipalA
42
Sp$ 20$ #ample
<bean class=Umycompany.Re5ardsKestDatabaseU>
<property name=Udatabase)ameU
!alue=U"#syste$Properties%database&a$e'U +>
<property name=UusernameU
!alue=U"#dbProps%userna$e'U+>
<property name=UFeyVeneratorU
!alue=U"#strate(y)ean%database*ey+enerator'U +>
<+bean>
<util"properties id=Udb/ropsU
location=Uclasspat#"db-con,i2.propertiesU+>
<bean id=Ustrate2y(eanU class=Umycompany.De,aultStrate2iesU>
<property name=Udatabase*eyVeneratorU re,=Umy*eyVeneratorU+>
...
<+bean>
43
Summary
Spring offers many techniques to simplify
configuration
+ ,eA(e seen 3ust a fe) here
+ ItAs about e#pressi(eness and elegance< 3ust li1e code
DonAt repeat yourselfB
+ *se bean inheritance if youAre seeing repetiti(e 20$
Consider hiding lo)6le(el beans
+ *se inner beans )here itAs natural to do so
A(oid monolithic configuration
+ *se *import'+ to aid in modulariCing your 20$
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Annotation- and Java-Based
Configuration Styles
2
History
2004: Spring 1.0
!"#-$ased %onfiguration
200&: Spring 2.'
Adds support for annotation-$ased
%onfiguration
200(: Spring ).0
Adds support for Java-$ased
%onfiguration
XML
XML
Annot.
XML
Annot.
Java
3
*opi%s in t+is Session
Annotation-based coniguration
Co,ponent-s%annning and $est pra%ti%es
Standard annotations
Java-$ased %onfiguration
"i-ing %onfiguration styles
.+en to use /+at
4
!"#0Annotation 12
<bean id=transferService class=com.springsource.TransferServicempl!
<constructor"arg ref=account#epositor$ %!
<%bean!
<bean id=transferService class=com.springsource.TransferServicempl!
<constructor"arg ref=account#epositor$ %!
<%bean!
!"#-$ased dependen%y in3e%tion
Annotation-$ased dependen%y in3e%tion
&'omponent
public class TransferServicempl implements TransferService (
&Auto)ired
public TransferServicempl*Account#epositor$ repo+ (
this.account#epositor$ = repo,
-
-
&'omponent
public class TransferServicempl implements TransferService (
&Auto)ired
public TransferServicempl*Account#epositor$ repo+ (
this.account#epositor$ = repo,
-
-
./ternal configuration
Annotations embedded
)it0 12J2s
<conte/t3component"scan base"pac4age=com.springsource%! <conte/t3component"scan base"pac4age=com.springsource%!
Minimal /ml config
5
1efinitions: 4Auto/ired
4Auto/ired
2ndi%ates t+at Spring s+ould in3e%t a dependen%y
Based on its type 5default6
Based on its na,e if used /it+ t+e 47ualifier annotation
@Autowired
public TransferServicempl*Account#epositor$ repo+ (
this.account#epositor$ = repo,
-
@Autowired
public TransferServicempl*Account#epositor$ repo+ (
this.account#epositor$ = repo,
-
@Autowired
public TransferServicempl* @Qualifier*account#epositor$+
Account#epositor$ repo+ (
this.account#epositor$ = repo,
-
@Autowired
public TransferServicempl* @Qualifier*account#epositor$+
Account#epositor$ repo+ (
this.account#epositor$ = repo,
-
6
1efinitions: Co,ponent s%anning
Co,ponent-s%anning
Base-pa%8age s%anned at startup
Su$-pa%8ages of t+e $ase-pa%8age also s%anned
All %lasses annotated /it+ 4Co,ponent loaded as
Spring $eans
So,e ot+er annotations /ill also $e dis%ussed later
<conte/t3component"scan base"pac4age=com.springsource%! <conte/t3component"scan base"pac4age=com.springsource%!
7
9sage of 4Auto/ired
%onstru%tor-in3e%tion
,et+od-in3e%tion
field-in3e%tion
&Auto)ired
public TransferServicempl*Account#epositor$ repo+ (
this.account#epositor$ = repo,
-
&Auto)ired
public TransferServicempl*Account#epositor$ repo+ (
this.account#epositor$ = repo,
-
&Auto)ired
public void setAccount#epositor$*Account#epositor$ repo+ (
t0is.account#epositor$ = repo,
-
&Auto)ired
public void setAccount#epositor$*Account#epositor$ repo+ (
t0is.account#epositor$ = repo,
-
&Auto)ired
private Account#epositor$ account#epositor$,
&Auto)ired
private Account#epositor$ account#epositor$,
'an also contain
multiple params
Met0od name does not
0ave to start )it0 set
8
Auto/iring and disa,$iguation
.+at +appens +ere:
&'omponent
public class TransferServicempl implements TransferService (
&Auto)ired
public TransferServicempl*Account#epositor$ account#epositor$+
( 5 -
-
&'omponent
public class JdbcAccount#epositor$ implements Account#epositor$ (..-
&'omponent
public class 6ibernateAccount#epositor$ implements Account#epositor$ (..-
&'omponent
public class TransferServicempl implements TransferService (
&Auto)ired
public TransferServicempl*Account#epositor$ account#epositor$+
( 5 -
-
&'omponent
public class JdbcAccount#epositor$ implements Account#epositor$ (..-
&'omponent
public class 6ibernateAccount#epositor$ implements Account#epositor$ (..-
70ic0 one s0ould get in8ected9
At startup3 :oSuc0;ean<efinition./ception= no uni>ue bean of t$pe
?Account#epositor$@ is defined3 e/pected single bean but found A...
9
Auto/iring and disa,$iguation
9se of t+e 47ualifier annotation
&'omponent
public class TransferServicempl implements TransferService (
&Auto)ired
public TransferServicempl* &Bualifier*C8dbcAccount#epositor$C+
Account#epositor$ account#epositor$+
( 5 -
-
&'omponent*C8dbcAccount#epositor$C+
public class JdbcAccount#epositor$ implements Account#epositor$ (..-
&'omponent*C0ibernateAccount#epositor$C+
public class 6ibernateAccount#epositor$ implements Account#epositor$ (..-
&'omponent
public class TransferServicempl implements TransferService (
&Auto)ired
public TransferServicempl* &Bualifier*C8dbcAccount#epositor$C+
Account#epositor$ account#epositor$+
( 5 -
-
&'omponent*C8dbcAccount#epositor$C+
public class JdbcAccount#epositor$ implements Account#epositor$ (..-
&'omponent*C0ibernateAccount#epositor$C+
public class 6ibernateAccount#epositor$ implements Account#epositor$ (..-
Bualifier
&Bualifier can also be used )it0 met0od in8ection and field in8ection
!
Co,ponent na,es
.+en not spe%ified
na,es are auto-generated
1e-%apitali;ed non-<ualified na,es $y default
=ever rely on generated na,es>
.+en spe%ified
#ess refa%toring-friendly
'ommon strateg$3 avoid using names )0en possible.
In many cases, it is not needed to have 2 implementations
of the same bean in the ApplicationContext
#ife%y%le
;eanDac11
XML
config
Annotations
config
;ean
detection
;ean instantiation and
dependenc$ in8ection
;ean11
&'omponent
scanning
nstantiation %
&Auto)ired
on constructor
n8ection of
&Auto)ired
met0ods and fields
Load /ml
definitions
nstantiation
% constr. in8ection
1ropert$
in8ection
;eanDac11 E ;eanDactor$1ost1rocessor
;ean11 E ;ean1ost1rocessor
2
!"# vs Annotations synta-
Sa,e options are availa$le
&'omponent*CtransferServiceC+
&Scope*Cprotot$peC+
public class TransferServicempl
implements TransferService (
&1ost'onstruct
public void init*+ ( %%.. -
&1re<estro$
public void destro$*+ ( %%.. -
-
&'omponent*CtransferServiceC+
&Scope*Cprotot$peC+
public class TransferServicempl
implements TransferService (
&1ost'onstruct
public void init*+ ( %%.. -
&1re<estro$
public void destro$*+ ( %%.. -
-
<bean id="transferService"
scope="prototype"
class="TransferServiceImpl"
init"met0od="init"
destro$"met0od="destroy" %!
<bean id="transferService"
scope="prototype"
class="TransferServiceImpl"
init"met0od="init"
destro$"met0od="destroy" %!
xml config annotations
3
Stereotype annotations
Co,ponent s%anning also %+e%8s for annotations
t+at are t+e,selves annotated /it+ 4Co,ponent
So-%alled stereotype annotations
?-a,ple:
&Target*(.lementT$pe.TYP-+
...
&'omponent
public @interface Service (...-
&Target*(.lementT$pe.TYP-+
...
&'omponent
public @interface Service (...-
&Service
public class TransferServicempl
implements TransferService (...-
&Service
public class TransferServicempl
implements TransferService (...-
<conte/t3component"scan
base"pac4age=com.springsource%!
<conte/t3component"scan
base"pac4age=com.springsource%!
scans
!eclaration of the "Service annotation
&Service annotation is part of t0e Spring frame)or4
4
Stereotype annotations
Spring fra,e/or8 stereotype annotations
&Service
&#epositor$ &'ontroller
&'onfiguration
&'omponent
Service classes
!ata access classes #eb classes $Spring %&C'
(ava Config)ration
2t0er Spring pro8ects provide t0eir o)n stereot$pe annotations
*Spring 7S= Spring ntegration...+
5
"eta-annotations
Annotation /+i%+ %an $e used to annotate ot+er
annotations
e.g. all servi%e $eans s+ould $e %onfigura$le using
%o,ponent s%anning and $e transa%tional
&#etention*#etention1olic$.*+,TI%+
&Target*.lementT$pe.TYP+
@"ervice
&Transactional*timeout=FG+
public &interface #$%ransactional"ervice (
String value*+ default CC,
-
&#etention*#etention1olic$.*+,TI%+
&Target*.lementT$pe.TYP+
@"ervice
&Transactional*timeout=FG+
public &interface #$%ransactional"ervice (
String value*+ default CC,
-
@#$%ransactional"ervice
public class TransferServicempl
implements TransferService (...-
@#$%ransactional"ervice
public class TransferServicempl
implements TransferService (...-
<conte/t3component"scan
base"pac4age=com.springsource%!
<conte/t3component"scan
base"pac4age=com.springsource%!
scans
recogni-es
C)stom annotation
6
4@alue and syste,Aroperties
9se 4@alue for Sp?# e-pressions in Java %ode
Bn a field or ,et+od or on para,eter of auto/ired
,et+od or %onstru%tor
&Halue*CI( s$stem1roperties?Juser.regionJ@ -C+
private String defaultLocale,
&Halue*CI( s$stem1roperties?Juser.regionJ@ -C+
public void set<efaultLocale*String defaultLocale+ ( 5 -
&Auto)ired
public void configure*Account#epositor$ account#epositor$=
&Halue*CI( s$stem1roperties?Juser.regionJ@ -C+ String defaultLocale+ (
5
-
&Halue*CI( s$stem1roperties?Juser.regionJ@ -C+
private String defaultLocale,
&Halue*CI( s$stem1roperties?Juser.regionJ@ -C+
public void set<efaultLocale*String defaultLocale+ ( 5 -
&Auto)ired
public void configure*Account#epositor$ account#epositor$=
&Halue*CI( s$stem1roperties?Juser.regionJ@ -C+ String defaultLocale+ (
5
-
Sp.L3 Spring ./pression Language *available since Spring K.G+
7
*opi%s in t+is Session
Annotation-$ased %onfiguration
Component-scanning
Standard annotations
Java-$ased %onfiguration
"i-ing %onfiguration styles
.+en to use /+at
8
Co,ponent s%anning
Co,ponents are s%anned at startup
Jar dependen%ies also s%anned>
Could result in slo/er startup ti,e if too ,any files
s%anned
?spe%ially for large appli%ations
A fe/ se%onds slo/er in t+e /orst %ase
.+at are t+e $est pra%ti%es:
9
Best pra%ti%es
<conte/t3component"scan base"pac4age=org=com%! <conte/t3component"scan base"pac4age=org=com%!
<conte/t3component"scan base"pac4age=com%! <conte/t3component"scan base"pac4age=com%!
<conte/t3component"scan base"pac4age=com.acme.app%! <conte/t3component"scan base"pac4age=com.acme.app%!
<conte/t3component"scan
base"pac4age=com.acme.app.repositor$=
com.acme.app.service= com.acme.app.controller%!
<conte/t3component"scan
base"pac4age=com.acme.app.repositor$=
com.acme.app.service= com.acme.app.controller%!
Ceally $ad:
Bad:
BD:
Bpti,i;ed:
All org and com
pac4ages in t0e classpat0
)ill be scannedLL
2!
2n%luding E ?-%luding Beans
9sing filtersF possi$ility to in%lude or e-%lude
$eans
Based on type
Based on %lass-level annotation
<conte/t3component"scan base"pac4age=Ccom.acme.appC!
<conte/t3include"filter t$pe=Crege/C e/pression=C.MStub.M#epositor$C%!
<conte/t3e/clude"filter t$pe=CannotationC
e/pression=Corg.springframe)or4.stereot$pe.#epositor$C%!
<%conte/t3component"scan!
<conte/t3component"scan base"pac4age=Ccom.acme.appC!
<conte/t3include"filter t$pe=Crege/C e/pression=C.MStub.M#epositor$C%!
<conte/t3e/clude"filter t$pe=CannotationC
e/pression=Corg.springframe)or4.stereot$pe.#epositor$C%!
<%conte/t3component"scan!
;ased on name
2
*opi%s in t+is Session
Annotation-$ased %onfiguration
Co,ponent s%anning
Standard annotations
Java-$ased %onfiguration
"i-ing %onfiguration styles
.+en to use /+at
22
JSC ))0
Java Spe%ifi%ation Ce<uest ))0
Also 8no/n as 42n3e%t
Joint JCA effort $y Google and SpringSour%e
Standardi;es internal 12 annotations
Au$lis+ed late 200(
Spring is a valid JSC-))0 i,ple,entation
Su$set of fun%tionality %o,pared to SpringHs
4Auto/ired support
42n3e%t +as I0J of /+at you need
Cely on 4Auto/ired for t+e rest
23
JSC ))0 annotations
import 8ava/.in8ect.n8ect,
import 8ava/.in8ect.:amed,
@&amed
public class TransferServicempl implements TransferService (
@'n(ect
public TransferServicempl* @&amed*Caccount#epositor$C+
Account#epositor$ account#epositor$+ ( 5 -
-
import 8ava/.in8ect.n8ect,
import 8ava/.in8ect.:amed,
@&amed
public class TransferServicempl implements TransferService (
@'n(ect
public TransferServicempl* @&amed*Caccount#epositor$C+
Account#epositor$ account#epositor$+ ( 5 -
-
import 8ava/.in8ect.:amed,
@&amed*Caccount#epositor$C+
public class JdbcAccount#epositor$ implements Account#epositor$ (..-
import 8ava/.in8ect.:amed,
@&amed*Caccount#epositor$C+
public class JdbcAccount#epositor$ implements Account#epositor$ (..-
<conte/t3component"scan base"pac4age=com.springsource%! <conte/t3component"scan base"pac4age=com.springsource%!
Also scans JS#"KKG annotations
S0ould be specified for component
scanning *even )it0out a name+
24
Kro, 4Auto/ired to 42n3e%t
Spring 3ava-.in3e%t.L
8ava/.in8ect restrictions
4Auto/ired 42n3e%t
&n8ect 0as no Jre>uiredJ attribute
4Co,ponent 4=a,ed
Spring supports scanning for
&:amed
4S%ope 4S%ope
for meta"annotation and in8ection
points onl$
&Scope
*CsingletonC+
4Singleton
8sr"KKG default scope is li4e SpringJs
Jprotot$peJ
47ualifier 4=a,ed
4@alue
no equivalent
4Ce<uired
no equivalent
4#a;y
no equivalent
25
*opi%s in t+is Session
Annotation-$ased %onfiguration
Co,ponent-s%anning
Standard annotations
!a"a-based coniguration
"i-ing %onfiguration styles
.+en to use /+at
26
*+e Java-$ased Approa%+
Spring ).0 introdu%es Java-$ased %onfiguration
9sed to $e a separate pro3e%t %alled Spring JavaConfig
4Configuration-annotated %lasses are t+e 8ey artifa%t
4Bean ,et+ods instead of M$ean0N ele,ents
9se Java %ode to define and %onfigure $eans
Configuration still e-ternal to ABJB %lasses to $e
%onfigured
"ore %ontrol over $ean instantiation and %onfiguration
"ore type-safety
27
4Configuration ?-a,ple
@)onfi*uration
public class #e)ards'onfig (
@+ean
public TransferService transferService*+ (
TransferServicempl service = ne) TransferServicempl*+,
service.setAccount#epositor$*account#epositor$*++,
return service,
-
@+ean
public Account#epositor$ account#epositor$*+ (
%%...
-
-
@)onfi*uration
public class #e)ards'onfig (
@+ean
public TransferService transferService*+ (
TransferServicempl service = ne) TransferServicempl*+,
service.setAccount#epositor$*account#epositor$*++,
return service,
-
@+ean
public Account#epositor$ account#epositor$*+ (
%%...
-
-
bean id
T0is met0od produces a bean definition
<ependenc$ in8ection
28
?na$ling 4Configuration %lass
pro%essing
2 /ays:
9se %o,ponent s%anning
9se AnnotationConfigAppli%ationConte-t
no !"# re<uired at all
<conte/t3component"scan base"pac4age=com.springsource%! <conte/t3component"scan base"pac4age=com.springsource%!
scans &'onfiguration
annotated classes
Application'onte/t conte/t =
ne) 'lass1at0XmlApplication'onte/t*application"config./ml+,
Application'onte/t conte/t =
new AnnotationConfigApplicationContext(AppConfig.class);
29
2,ple,enting 4Bean "et+ods
Configuration in Java: %all any %ode you /ant
=ot 3ust %onstru%tors and property setters
"ay not $e private
"et+od na,e $e%o,es $ean id
Call &;ean ,et+od to refer to $ean in sa,e %lass
.eHll s+o/ +o/ to refer to e-ternal $eans later
Sa,e defaults as !"#: $eans are singletons
9se &Scope annotation to %+ange s%ope
&;ean @"cope,-protot$pe-.
public StatefulService service*+ (
5
&;ean @"cope,-protot$pe-.
public StatefulService service*+ (
5
3!
2,ple,enting 4Configuration
Classes
"ust +ave default %onstru%tor
2,pli%it or not
"ultiple &'onfiguration %lasses ,ay e-ist
@)onfi*uration
public class #e)ards'onfig (
%%..
-
@)onfi*uration
public class #e)ards'onfig (
%%..
-
@)onfi*uration
public class Securit$'onfig ( %%.. -
@)onfi*uration
public class Securit$'onfig ( %%.. -
3
4Configuration internals 516
By defaultF Spring %reates singletons out of
4Bean annotated ,et+ods
Ho/ is it possi$le:
@+ean
public TransferService transferService*+ (
TransferServicempl service = ne) TransferServicempl*+,
service.setAccount#epositor$*account#epositor$*++,
return service,
-
@+ean
public Account#epositor$ account#epositor$*+ (
Account#epositor$mpl repo = ne) Account#epositor$mpl*+,
%%...
return repo,
-
@+ean
public TransferService transferService*+ (
TransferServicempl service = ne) TransferServicempl*+,
service.setAccount#epositor$*account#epositor$*++,
return service,
-
@+ean
public Account#epositor$ account#epositor$*+ (
Account#epositor$mpl repo = ne) Account#epositor$mpl*+,
%%...
return repo,
-
T0is is a singletonLL
32
4Configuration internals 526
public class Proxy,ame e/tends #e)ard'onfig (
public TransferService transferService*+ (
%% c0ec4 if bean is in t0e application'onte/t
%% if not= call super.transferService*+ and store bean in application 'onte/t
-
-
public class Proxy,ame e/tends #e)ard'onfig (
public TransferService transferService*+ (
%% c0ec4 if bean is in t0e application'onte/t
%% if not= call super.transferService*+ and store bean in application 'onte/t
-
-
@)onfi*uration
public class #e)ard'onfig (
@+ean
public TransferService transferService*+ ( %%... -
-
@)onfi*uration
public class #e)ard'onfig (
@+ean
public TransferService transferService*+ ( %%... -
-
Aro-y %reated at startup ti,e
1oes all t+e ,agi%
Stores $eans in Appli%ationConte-tF %reates singletons...
1ro/$ generation uses
'NLib b$ default
33
#ife%y%le
;eanDac11
XML
config
Annotation
config
;ean
detection
;ean instantiation and
dependenc$ in8ection
;ean11
&'omponent
scanning
nstantiation %
&Auto)ired
on constructor
n8ection of
&Auto)ired
met0ods and fields
Load /ml
definitions
nstantiation
% constr. in8ection
1ropert$
in8ection
Java
config
#ead &;ean
met0od
signatures
'all &;ean met0od implementations
;eanDac11 E ;eanDactor$1ost1rocessor
;ean11 E ;ean1ost1rocessor
34
*opi%s in t+is Session
Annotation-$ased %onfiguration
Co,ponent-s%anning and $est pra%ti%es
Standard annotations
Java-$ased %onfiguration
#ixing coniguration styles
.+en to use /+at
35
"i-ing %onfiguration styles:
.+y:
Bne single appli%ation %an ,i- and ,at%+
in3e%tion styles
!"#-$ased
=o ,a3or te%+ni%al li,itation $ut ,ore ver$ose
Annotation-$ased
Can only annotate t+e %lasses you /rite
Java-$ased
does not +ave na,espa%es 5%onte-tF t-F se%urity...6
36
9sing annotations /it+out
%o,ponent s%anning 516
9se of M%onte-t:annotation-%onfig0N
Aro%esses all 12 annotations
1oes not perfor, %o,ponent-s%anning
Beans s+ould $e de%lared e-pli%itely
<beans ...!
/conte0t1annotation2confi*34
<bean id=transferService class=transfer.TransferService%!
<bean id=account#epositor$ class=transfer.JdbcAccount#epositor$%!
<%beans!
<beans ...!
/conte0t1annotation2confi*34
<bean id=transferService class=transfer.TransferService%!
<bean id=account#epositor$ class=transfer.JdbcAccount#epositor$%!
<%beans!
<propert$ %! or <constructor"arg%! are not needed an$ more
because classes use &Auto)ired
37
9sing annotations /it+out
%o,ponent s%anning 526
=o 4Co,ponent annotation any,ore
.it+out 7ualifier
.it+ 7ualifier
public class TransferServicempl implements TransferService (
@Autowired
public TransferServicempl*Account#epositor$ account#epositor$+ ( 5 -
-
public class TransferServicempl implements TransferService (
@Autowired
public TransferServicempl*Account#epositor$ account#epositor$+ ( 5 -
-
public class JdbcAccount#epositor$ implements Account#epositor$ (
public JdbcAccount#epositor$*@Qualifier*Cm$s>l<atasourceC+
Account#epositor$ account#epositor$+ ( 5 -
-
public class JdbcAccount#epositor$ implements Account#epositor$ (
public JdbcAccount#epositor$*@Qualifier*Cm$s>l<atasourceC+
Account#epositor$ account#epositor$+ ( 5 -
-
public class JdbcAccount#epositor$ implements Account#epositor$ (...- public class JdbcAccount#epositor$ implements Account#epositor$ (...-
public class JdbcAccount#epositor$ implements Account#epositor$ (...- public class JdbcAccount#epositor$ implements Account#epositor$ (...-
#efers to
declared bean id
38
9sing annotations /it+out
%o,ponent s%anning 5)6
Java-$ased %onfiguration: use of 42,port
?<uivalent to Mi,port0N in !"#
"eans in%luded %lasses donHt +ave to $e defined as
Spring $eans any ,ore
&'onfiguration
@'mport,5"ecurit$)onfi*6class7 8m0)onfi*6class9.
public class #e)ards'onfig (
5
-
&'onfiguration
@'mport,5"ecurit$)onfi*6class7 8m0)onfi*6class9.
public class #e)ards'onfig (
5
-
&'onfiguration
public class Securit$'onfig (
5
-
&'onfiguration
public class Securit$'onfig (
5
-
39
"i-ing %onfiguration styles:
4Configuration e-a,ple
Bean datasour%e de%lared in !"#
9sed in 4Configuration %lass
@)onfi*uration
public class Application'onfig (
@Autowired
private <ataSource datasource,
@+ean
public Account#epositor$ account#epositor$*+ (
Account#epositor$mpl repositor$ = new Account#epositor$mpl*+,
repositor$.set<ataSource*t0is.datasource+,
return service,
-
-
@)onfi*uration
public class Application'onfig (
@Autowired
private <ataSource datasource,
@+ean
public Account#epositor$ account#epositor$*+ (
Account#epositor$mpl repositor$ = new Account#epositor$mpl*+,
repositor$.set<ataSource*t0is.datasource+,
return service,
-
-
<conte/t3component"scan base"pac4age=com.springsource%!
<bean id=dataSource class=...%!
<conte/t3component"scan base"pac4age=com.springsource%!
<bean id=dataSource class=...%!
<ependenc$ n8ection
<eclaration
4!
*opi%s in t+is Session
Annotation-$ased %onfiguration
Co,ponent s%anning
Standard annotations
Java-$ased %onfiguration
"i-ing %onfiguration styles
$hen to use what
4
.+en to use /+at:
Annotations:
=i%e for fre<uently %+anging $eans
Start using for s,all isolated parts of your appli%ation
5e.g. Spring 4"@C %ontrollers6
Aros:
Single pla%e to edit 53ust t+e %lass6
Allo/s for very rapid develop,ent
Cons:
Configuration spread a%ross your %ode $ase
Bnly /or8s for your o/n %ode
42
.+en to use /+at:
!"#:
Kor infrastru%ture and ,ore Hstati%H $eans
Aros:
2s %entrali;ed in one 5or a fe/6 pla%es
"ost fa,iliar %onfiguration for,at for ,ost people
Can $e used for all %lasses 5not 3ust your o/n6
Cons:
#i,ited %onfiguration options
So,e people 3ust donHt li8e !"#>
43
.+en to use /+at:
4Configuration %lasses:
Kor full %ontrol over instantiation and
%onfiguration
As alternative to i,ple,enting Ka%toryBean
Aros:
Configuration still e-ternal to %ode
2ntegrates /ell /it+ lega%y %ode
Can %all ,et+ods su%+ as addDataSource(DataSource d)
Cons:
.iring /onHt s+o/ up in S*S
=o e<uivalent to t+e !"# na,espa%es
44
Su,,ary
SpringOs %onfiguration dire%tives %an $e /ritten
in !"#F using Java or using annotations
Pou %an ,i- and ,at%+ !"#F Java and
annotations as you please
Auto/iring /it+ 4Co,ponent or 4Configuration
allo/s for al,ost e,pty !"# %onfiguration files
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
#AB
9sing SpringOs annotations to Configure and
test an appli%ation
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Testing Spring Applications
Unit Testing without Spring,
and Integration Testing with Spring
2
Topics in this session
Test Drien Deelopment
Unit Testing vs. Integration Testing
Unit Testing with Stubs
Unit Testing with Mocks
Integration Testing with Spring
3
What is TDD
TDD Test Driven Develop!ent
Is it writing tests be"ore the code# Is it writing
tests at the sa!e ti!e as the code#
$ That is not what is !ost i!portant
TDD is about%
$ writing auto!ated tests that veri"& code actuall&
works
$ Driving develop!ent with well de"ined re'uire!ents
in the "or! o" tests
4
()ut I Don*t +ave Ti!e to
Write Tests,-
.ver& develop!ent process includes testing
$ .ither auto!ated or !anual
Auto!ated tests result in a "aster develop!ent
c&cle overall
$ /our ID. is better at this than &ou are
0roperl& done TDD is faster than develop!ent
without tests
5
TDD and Agilit&
1o!prehensive test coverage provides
con"idence
1on"idence enables re"actoring
2e"actoring is essential to agile develop!ent
6
TDD and Design
Testing !akes &ou think about &our design
I" &our code is hard to test then the design
should be reconsidered
7
TDD and 3ocus
A test case helps &ou "ocus on what !atters
It helps &ou not to write code that &ou don4t
need
3ind proble!s earl&
8
)ene"its o" 1ontinuous Integration
The cost to "i5 a bug grows e5ponentiall& in proportion
to the ti!e be"ore it is discovered
1ontinuous Integration 61I7 "ocuses on reducing the
ti!e be"ore the bug is discovered
.""ective 1I re'uires auto!ated tests
time
to fix
time until discovered
9
Test Driven Develop!ent
!nit Testing s. "ntegr#tion Testing
Unit Testing with Stubs
Unit Testing with Mocks
Integration Testing with Spring
Topics in this session
10
Unit Testing vs.
Integration Testing
Unit Testing
$ Tests one unit o" "unctionalit&
$ 8eeps dependencies !ini!al
$ Isolated "ro! the environ!ent 6including Spring7
Integration Testing
$ Tests the interaction o" !ultiple units working
together
$ Integrates in"rastructure
11
Unit Testing
9eri"& a unit works in isolation
$ I" A depends on ), A*s tests should not "ail because
o" a bug in )
$ A*s test should not pass because o" a bug in )
Stub or !ock out dependencies i" needed
+ave each test e5ercise a single scenario
$ A path through the unit
12
.5a!ple Unit to be Tested
public class AuthenticatorImpl implements Authenticator {
private AccountDao accountDao;
public AuthenticatorImpl(AccountDao accountDao) {
this.accountDao = accountDao;
}
public boolean authenticate(String username, String passwor) {
Account account = accountDao.getAccount(username);
i! (account.get"asswor().e#uals(passwor)) {
return true;
} else {
return !alse;
}
}
}
public class AuthenticatorImpl implements Authenticator {
private AccountDao accountDao;
public AuthenticatorImpl(AccountDao accountDao) {
this.accountDao = accountDao;
}
public boolean authenticate(String username, String passwor) {
Account account = accountDao.getAccount(username);
i! (account.get"asswor().e#uals(passwor)) {
return true;
} else {
return !alse;
}
}
}
$%ternal epenenc&
'nit business logic (( paths)
13
Test Driven Develop!ent
Unit Testing vs. Integration Testing
!nit Testing with Stubs
Unit Testing with Mocks
Integration Testing with Spring
Topics in this session
14
I!ple!enting a Stub
class StubAccountDao implements AccountDao {
public Account getAccount(String user) {
return )lisa*.e#uals(user) + new Account()lisa*, )secret*) , null;
}
}
class StubAccountDao implements AccountDao {
public Account getAccount(String user) {
return )lisa*.e#uals(user) + new Account()lisa*, )secret*) , null;
}
}
Simple state
15
Testing with a Stub
public class AuthenticatorImpl-ests {
private AuthenticatorImpl authenticator;
./e!ore public voi set'p() {
authenticator = new AuthenticatorImpl(new StubAccountDao());
}
.-est public voi success!ulAuthentication() {
assert-rue(authenticator.authenticate()lisa*, )secret*));
}
.-est public voi invali"asswor() {
assert0alse(authenticator.authenticate()lisa*, )invali*));
}
}
public class AuthenticatorImpl-ests {
private AuthenticatorImpl authenticator;
./e!ore public voi set'p() {
authenticator = new AuthenticatorImpl(new StubAccountDao());
}
.-est public voi success!ulAuthentication() {
assert-rue(authenticator.authenticate()lisa*, )secret*));
}
.-est public voi invali"asswor() {
assert0alse(authenticator.authenticate()lisa*, )invali*));
}
}
Stub is con!igure
Scenarios are e%ercise
base on the state o! stub
16
Stub 1onsiderations
Advantages
.as& to i!ple!ent and understand
2eusable
Disadvantages
A change to the inter"ace re'uires the stub to be
updated
/our stub !ust i!ple!ent all !ethods, even those
not used b& a speci"ic scenario
I" a stub is reused re"actoring can break other tests
17
Test Driven Develop!ent
Unit Testing vs. Integration Testing
Unit Testing with Stubs
!nit Testing with $oc%s
Integration Testing with Spring
Topics in this session
18
Steps to Testing with a Mock
:. Use a !ocking librar& to generate a !ock
ob;ect
I!ple!ents the dependent inter"ace on<the<"l&
=. 2ecord the !ock with e5pectations o" how it
will be used "or a scenario
What !ethods will be called
What values to return
>. .5ercise the scenario
?. 9eri"& !ock e5pectations were !et
19
Mock @ibraries
.as&Mock
$ ver& popular
$ used e5tensivel& in Spring
A!ock
$ nice A0I, ver& suitable "or co!ple5 state"ul logic
Mockito
$ uses a Test Sp& instead o" a true !ock, !aking it
easier to use !ost o" the ti!e
20
.5a!ple < Testing with .as&Mock
Bn setup
1 1reate
!ock6s7
1 1reate unit
3or each test
1 2ecord
e5pected
!ethod calls
and set !ock
return values
1 1all repla&
1 .5ercise test
scenario
1 1all veri"&
import static org.eas&moc2.classe%tensions.$as&3oc2.4;
public class AuthenticatorImpl-ests {
private AccountDao accountDao
= createMock(AccountDao.class);
private AuthenticatorImpl authenticator
= new AuthenticatorImpl(accountDao);
.-est
public voi vali'ser5ith6orrect"asswor() {
expect(accountDao.getAccount()lisa*)).
an7eturn(new Account()lisa*, )secret*));
replay(accountDao);
assert-rue(authenticator.authenticate()lisa*, )secret*));
verify(accountDao);
}
}
import static org.eas&moc2.classe%tensions.$as&3oc2.4;
public class AuthenticatorImpl-ests {
private AccountDao accountDao
= createMock(AccountDao.class);
private AuthenticatorImpl authenticator
= new AuthenticatorImpl(accountDao);
.-est
public voi vali'ser5ith6orrect"asswor() {
expect(accountDao.getAccount()lisa*)).
an7eturn(new Account()lisa*, )secret*));
replay(accountDao);
assert-rue(authenticator.authenticate()lisa*, )secret*));
verify(accountDao);
}
}
21
Mock 1onsiderations
Advantages
Co additional class to !aintain
/ou onl& need to setup what is necessar& "or
the scenario &ou are testing
Test behavior as well as state
Disadvantages
A little harder to understand at "irst
22
Mocks or Stubs#
/ou will probabl& use both
Deneral reco!!endations
$ 3avor !ocks "or non<trivial inter"aces
$ Use stubs when &ou have si!ple inter"aces with
repeated "unctionalit&
$ Alwa&s consider the speci"ic situation
2ead (Mocks Aren*t Stubs- b& Martin 3owler
$ http%EEwww.!artin"owler.co!EarticlesE!ocksArentStubs.ht!l
23
Test Driven Develop!ent
Unit Testing vs. Integration Testing
Unit Testing with Stubs
Unit Testing with Mocks
"ntegr#tion Testing with Spring
Topics in this session
24
Integration Testing
Tests the interaction o" !ultiple units
Tests application classes in the conte5t o" their
surrounding in"rastructure
In"rastructure !a& be (scaled down-
e.g. use Apache D)10 connection pool instead o"
container<provider pool obtained through ACDI
25
0ackaged as a separate !odule
$ spring<test.;ar
1onsists o" several AUnit test support classes
1entral support class is SpringAUnit?Test2unner
$ 1aches a shared Application1onte5t across test !ethods
Spring*s Integration Test
Support
26
Annotations "or Integration
Testing
Annotate the test with F1onte5t1on"iguration
Bptionall& pass a String<arra& o" con"ig "ile
locations
$ b& de"ault Spring loads GHclassna!eI<conte5t.5!l
"ro! the sa!e package
Use FAutowired annotations as be"ore
@ContextConfiguration(89trans!er:con!ig.%ml8)
@RunWith(Spring;'nit<6lass7unner.class)
public class Authenticator-ests {
@uto!ire"
pri$ate Authenticator authenticator;
}
@ContextConfiguration(89trans!er:con!ig.%ml8)
@RunWith(Spring;'nit<6lass7unner.class)
public class Authenticator-ests {
@uto!ire"
pri$ate Authenticator authenticator;
}
27
Using Spring4s test support
.7un5ith(Spring;'nit<6lass7unner.class)
.6onte%t6on!iguration()classpath,s&stem:test:con!ig.%ml*})
public !inal class Authenticator-ests {
.Autowire
private Authenticator authenticator;
.-est
public voi success!ulAuthentication() {
authenticator.authenticate(...);
...
}
}
.7un5ith(Spring;'nit<6lass7unner.class)
.6onte%t6on!iguration()classpath,s&stem:test:con!ig.%ml*})
public !inal class Authenticator-ests {
.Autowire
private Authenticator authenticator;
.-est
public voi success!ulAuthentication() {
authenticator.authenticate(...);
...
}
}
7un with Spring support
"oint to s&stem test
con!iguration !ile
De!ine a epenenc&
-est the s&stem as normal
28
Multiple test !ethods
.7un5ith(Spring;'nit<6lass7unner.class)
.6onte%t6on!iguration()classpath,s&stem:test:con!ig.%ml*)
public !inal class Authenticator-ests {
.Autowire
private Authenticator authenticator;
.-est
public voi success!ulAuthentication() {
...
}
.-est
public voi !ailureAuthentication() {
...
}
}
.7un5ith(Spring;'nit<6lass7unner.class)
.6onte%t6on!iguration()classpath,s&stem:test:con!ig.%ml*)
public !inal class Authenticator-ests {
.Autowire
private Authenticator authenticator;
.-est
public voi success!ulAuthentication() {
...
}
.-est
public voi !ailureAuthentication() {
...
}
}
-he Application6onte%t is
instantiate onl& once !or
all tests that use the same
set o! con!ig !iles
(even across test classes)
Annotate test metho with .Dirties6onte%t to !orce recreation o! the
cache Application6onte%t i! metho changes the containe beans
29
)ene"its o" Integration
Testing with Spring
Co need to deplo& to an e5ternal container to
test application "unctionalit&
2un ever&thing 'uickl& inside &our ID.
Allows reuse o" &our con"iguration between test
and production environ!ents
Application con"iguration logic is t&picall& reused
In"rastructure con"iguration is environ!ent<speci"ic
DataSources
AMS Jueues
30
Su!!ar&
Testing is an essential part o" any develop!ent
Unit testing tests a class in isolation where
e5ternal dependencies should be !ini!iKed
1onsider creating stubs or !ocks to unit test
/ou don*t need Spring to unit test
Integration testing tests the interaction o"
!ultiple units working together
Spring provides good integration testing support
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
@A)
Testing Spring Applications
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Developing Aspects with
Spring AOP
Aspect-Oriented Programming for
Declarative Enterprise Services
2
Topics in this session
What roblem !oes "# Sol$e%
Core AOP Concepts
Quic Start
Defining Pointcuts
!mplementing Advice
Advanced topics
" #amed Pointcuts
" Conte$t selecting pointcuts
" %oring with annotations
3
%hat Pro&lem Does AOP
Solve'
Aspect-Oriented Programming (AOP) ena&les
modulari*ation of cross-cutting concerns
4
%hat are Cross-Cutting
Concerns'
+eneric functionalit, that is needed in man,
places in ,our application
E$amples
" -ogging and Tracing
" Transaction .anagement
" Securit,
" Caching
" Error /andling
" Performance .onitoring
" Custom 0usiness 1ules
5
An E$ample 1e2uirement
Perform a role-&ased securit, chec
&efore ever, application method
A sign this requirement is a cross-cutting concern
6
!mplementing Cross Cutting
Concerns %ithout .odulari*ation
3ailing to modulari*e cross-cutting concerns
leads to two things
45 Code tangling
A coupling of concerns
65 Code scattering
The same concern spread across modules
7
S,mptom 748 Tangling
public class RewardNetworkImpl implements RewardNetwork {
public RewardConfirmation rewardAccountFor(Dining dining) {
if (!as!ermission("ecurit#Conte$t%get!rincipal()) {
trow new AccessDenied&$ception()'
(
Account a ) accountRepositor#%find*#CreditCard(+
Restaurant r ) restaurantRepositor#%find*#,ercantNumber(+
,onetar#Amount amt ) r%calculate*enefitFor(account- dining)'
+
(
(
,i$ing of concerns
8
S,mptom 768 Scattering
public class .ibernateAccount,anager implements Account,anager {
public Account getAccountFor&diting(/ong id) {
if (!as!ermission("ecurit#Conte$t%get!rincipal()) {
trow new AccessDenied&$ception()'
(
+
public class .ibernate,ercantReporting"er0ice implements
,ercantReporting"er0ice {
public /ist1Dining"ummar#2 findDinings("tring mercantNumber-
DateInter0al inter0al) {
if (!as!ermission("ecurit#Conte$t%get!rincipal()) {
trow new AccessDenied&$ception()'
(
+
Duplication
9
&an'Ser$ice
S,stem Evolution %ithout
.odulari*ation
Code
tangling
Transactions
Securit,
-ogging
CustomerSer$ice (eportingSer$ice
Code
scattering
10
Aspect Oriented
Programming (AOP)
Aspect-Oriented Programming (AOP)
ena&les modulari*ation of cross-cutting
concerns
" To avoid tangling
" To eliminate scattering
11
/ow AOP %ors
45 !mplement ,our mainline application logic
3 3ocusing on the core pro&lem
65 %rite aspects to implement ,our cross-cutting
concerns
3 Spring provides man, aspects out-of-the-&o$
95 %eave the aspects into ,our application
3 Adding the cross-cutting &ehaviours to the right
places
12
S,stem Evolution8 AOP &ased
Transaction
Aspect
Security
Aspect
Logging
Aspect
&an'Ser$ice CustomerSer$ice (eportingSer$ice
13
-eading AOP Technologies
Aspect:
" Original AOP technolog, (first version in 4;;<)
" Offers a full-&lown Aspect Oriented Programming
language
=ses &,te code modification for aspect weaving
Spring AOP
" :ava-&ased AOP framewor with Aspect: integration
=ses d,namic pro$ies for aspect weaving
" 3ocuses on using AOP to solve enterprise pro&lems
" )he *ocus o* this session
14
Topics in this session
%hat Pro&lem Does AOP Solve'
Core "# Concepts
Quic Start
Defining Pointcuts
!mplementing Advice
Advanced topics
" #amed Pointcuts
" Conte$t selecting pointcuts
" %oring with annotations
15
Core AOP Concepts
:oin Point
" A point in the e$ecution of a program such as a
method call or field assignment
Pointcut
" An e$pression that selects one or more :oin Points
Advice
" Code to &e e$ecuted at a :oin Point that has &een
selected &, a Pointcut
Aspect
" A module that encapsulates pointcuts and advice
16
Topics in this session
%hat Pro&lem Does AOP Solve'
Core AOP Concepts
+uic' Start
Defining Pointcuts
!mplementing Advice
Advanced topics
" #amed Pointcuts
" Conte$t selecting pointcuts
" %oring with annotations
17
AOP Quic Start
Consider this &asic re2uirement
/ow can ,ou use AOP to meet it'
/og a message e0er# time a propert# is about to cange /og a message e0er# time a propert# is about to cange
18
An Application O&>ect %hose
Properties Could Change
public class "impleCace implements Cace- *eanNameAware {
pri0ate int cace"i4e'
pri0ate Data"ource data"ource'
pri0ate "tring name'
public 0oid setCace"i4e(int si4e) { cace"i4e ) si4e' (
public 0oid setData"ource(Data"ource ds) { data"ource ) ds' (
public 0oid set*eanName("tring beanName) { name ) beanName' (
public "tring to"tring() { return name' (
+
(
public class "impleCace implements Cace- *eanNameAware {
pri0ate int cace"i4e'
pri0ate Data"ource data"ource'
pri0ate "tring name'
public 0oid setCace"i4e(int si4e) { cace"i4e ) si4e' (
public 0oid setData"ource(Data"ource ds) { data"ource ) ds' (
public 0oid set*eanName("tring beanName) { name ) beanName' (
public "tring to"tring() { return name' (
+
(
19
!mplement the Aspect
5Aspect
public class !ropert#Cange6racker {
pri0ate /ogger logger ) /ogger%get/ogger(getClass())'
5*efore(7e$ecution(0oid set8(8))9)
public 0oid trackCange() {
logger%info(7!ropert# about to cange+9)'
(
(
20
Configure the Aspect as a
0ean
1beans2
1aop:aspect;<autopro$#2
1aop:include name)7propert#Cange6racker9 =2
1=aop:aspect;<autopro$#2
1bean id)7propert#Cange6racker9 class)7e$ample%!ropert#Cange6racker9 =2
1=beans2
Configures "pring to appl# te
5Aspect to #our beans
aspects<config%$ml
21
!nclude the Aspect
Configuration
1beans2
1import resource) 7aspects<config%$ml9=2
1bean name)7cace<A9 class)7e$ample%"impleCace9 %%=2
1bean name)7cace<*9 class)7e$ample%"impleCace9 %%=2
1bean name)7cace<C9 class)7e$ample%"impleCace9 %%=2
1=beans2
application<config%$ml
22
Test the Application
ApplicationConte$t conte$t )
new Class!at>mlApplicationConte$t(7application<config%$ml9)'
Cace cace ) (Cace) conte$t%get*ean(7cace<A9)'
cace%setCace"i4e(?@AA)'
INFB: !ropert# about to cange+ INFB: !ropert# about to cange+
23
"pring AB! !ro$# (tis)
/ow Aspects are Applied
"impleCace
(target)
!ropert#Cange
6racker (aspect)
11interface22
Cace
setCace"i4e(?@AA)
C% "pring creates a pro$# tat brings
te aspect and target togeter
?% 6e pro$# implements
te business interface
of te target
D% ,atcing ad0ice is e$ecuted
E% All calls routed troug pro$#
24
Tracing Propert, Changes "
%ith Conte$t
Conte$t is provided &, the JoinPoint method
parameter
5Aspect
public class !ropert#Cange6racker {
pri0ate /ogger logger ) /ogger%get/ogger(getClass())'
5*efore(7e$ecution(0oid set8(8))9)
public 0oid trackCange(Foin!oint point) {
"tring name ) point%get"ignature()%getName()'
Bb;ect newGalue ) point%getArgs()HAI'
logger%info(name J 7 about to cange to 9 J newGalue J
7 on 9 J point%get6arget())'
(
(
Conte$t about te intercepted point
INFB: setCace"i4e about to cange to ?@AA on cace<A INFB: setCace"i4e about to cange to ?@AA on cace<A
25
Topics in this session
%hat Pro&lem Does AOP Solve'
Core AOP Concepts
Quic Start
!e*ining ointcuts
!mplementing Advice
Advanced topics
" #amed Pointcuts
" Conte$t selecting pointcuts
" %oring with annotations
26
Defining Pointcuts
%ith Spring AOP ,ou write pointcuts using
Aspect:?s pointcut e$pression language
" 3or selecting where to appl, advice
Complete e$pression language reference
availa&le at
" http8@@www5eclipse5org@aspect>
27
Common Pointcut Designator
e$ecution(Amethod patternB)
" The method must match the pattern
Can chain together to create composite
pointcuts
" CC (and)D EE (or)D F (not)
.ethod Pattern
" G.odifiersH 1eturnT,pe GClassT,peH
.ethod#ame (GArgumentsH) Gthrows
E$ceptionT,peH
28
%riting e$pressions
e$ecution(8 rewards%restaurant%8"er0ice%find8(%%))
return t#pe
package
t#pe params
metod designator
29
E$ecution E$pression
E$amples
e$ecution(0oid send8("tring))
" An, method starting with send that taes a single String
parameter and has a void return t,pe
e$ecution(8 send(8))
" An, method named send that taes a single parameter
e$ecution(8 send(int- %%))
" An, method named send whose first parameter is an int (the
I55J signifies K or more parameters ma, follow)
30
E$ecution E$pression
E$amples
e$ecution(0oid e$ample%,essage"er0iceImpl%8(%%))
" An, visi&le void method in the .essageService!mpl class
e$ecution(0oid e$ample%,essage"er0iceJ%send(8))
" An, void method named send in an, o&>ect of t,pe
MessageService (that include possi&le child classes or
implementors of .essageService)
e$ecution(5;a0a$%annotation%securit#%RolesAllowed 0oid send8(%%))
" An, void method starting with send that is annotated with
the L1olesAllowed annotation
31
E$ecution E$pression E$amples
woring with pacages
e$ecution(8 rewards%8%restaurant%8%8(%%))
" There is one director, &etween rewards and restaurant
e$ecution(8 rewards%%restaurant%8%8(%%))
" There ma, &e several directories &etween rewards and
restaurant
e$ecution(8 8%%restaurant%8%8(%%))
" An, su&-pacage called restaurant
32
Topics in this session
%hat Pro&lem Does AOP Solve'
Core AOP Concepts
Quic Start
Defining Pointcuts
,mplementing "d$ice
Advanced topics
" #amed Pointcuts
" Conte$t selecting pointcuts
" %oring with annotations
33
Advice T,pes8 0efore
*eforeAd0ice !ro$# 6arget
34
0efore Advice E$ample
=se @Before annotation
" !f the advice throws an e$ceptionD target will not &e
called
5Aspect
public class !ropert#Cange6racker {
pri0ate /ogger logger ) /ogger%get/ogger(getClass())'
5*efore(7e$ecution(0oid set8(8))9)
public 0oid trackCange() {
logger%info(7!ropert# about to cange+9)'
(
(
6rack calls to all setter metods
35
Advice T,pes8After 1eturning
AfterReturningAd0ice !ro$# 6arget
"uccessful return
36
After 1eturning Advice -
E$ample
5AfterReturning(0alue)7e$ecution(8 ser0ice%%8%8(%%))9-
returning)7reward9)
public 0oid audit(Foin!oint ;p- Reward reward) {
audit(;p%get"ignature() J 7 returns a reward ob;ect 9)'
(
Audit all operations in te service package tat return a Reward
ob;ect
=se @AfterReturning annotation with the
returning attri&ute
37
Advice T,pes8 After Throwing
After6rowingAd0ice !ro$# 6arget
Exception
38
After Throwing Advice -
E$ample
5After6rowing(0alue)7e$ecution(8 8%%Repositor#J%8(%%))9- trowing)7e9)
public 0oid report(Foin!oint ;p- DataAccess&$ception e) {
mail"er0ice%emailFailure(7&$ception in repositor#9- ;p- e)'
(
"end an email e0er# time a Repositor# class trows an e$ception of
t#pe DataAccess&$ception
=se @AfterThrowing annotation with the
throwing attri&ute
39
After Throwing Advice -
Propagation
5After6rowing(0alue)7e$ecution(8 8%%Repositor#J%8(%%))9- trowing)7e9)
public 0oid report(Foin!oint ;p- DataAccess&$ception e) {
mail"er0ice%emailFailure(7&$ception in repositor#9- ;p- e)'
trow new Rewards&$ception(e)'
(
The LAfterThrowing advice will not stop the
e$ception from propagating
" .owe0er it can trow a different t#pe of e$ception
If #ou wis to stop te e$ception from propagating an# furter- #ou can
use an 5Around ad0ice (see later)
If #ou wis to stop te e$ception from propagating an# furter- #ou can
use an 5Around ad0ice (see later)
40
Advice T,pes8 After
AfterAd0ice !ro$# 6arget
"uccessful return or &$ception
41
After Advice E$ample
=se @After annotation
" Called regardless of whether an e$ception has &een
thrown &, the target or not
5Aspect
public class !ropert#Cange6racker {
pri0ate /ogger logger ) /ogger%get/ogger(getClass())'
5After(7e$ecution(0oid update8(8))9)
public 0oid trackCange() {
logger%info(7An update as been made+9)'
(
(
6rack calls to all update metods
42
Advice T,pes8 Around
AroundAd0ice !ro$# 6arget
proceed()
43
Around Advice E$ample
5Around(7e$ecution(5e$ample%Caceable 8 rewards%ser0ice%%8%8(%%))9)
public Bb;ect cace(!roceedingFoin!oint point) throws 6rowable {
Bb;ect 0alue ) cace"tore%get(caceKe#(point))'
if (0alue )) null) {
0alue ) point%proceed()'
cace"tore%put(caceKe#(point)- 0alue)'
(
return 0alue'
(
Cace 0alues returned b# caceable ser0ices
!roceed onl# if not alread# caced
=se @Around annotation
" ProceedingJoinPoint parameter
" !nherits from JoinPoint and adds the proceed() method
44
Alternative Spring AOP
S,nta$ - M.-
Annotation s,nta$ is :ava <N onl,
M.- s,nta$ wors on :ava 45O
Approach
" Aspect logic defined :ava
" Aspect configuration in M.-
=ses the aop namespace
45
Tracing Propert, Changes -
:ava Code
public class !ropert#Cange6racker {
public 0oid trackCange(Foin!oint point) {
+
(
(
Aspect is a !lain Fa0a Class wit no Fa0a @ annotations
46
Tracing Propert, Changes -
M.- Configuration
1aop:config2
1aop:aspect ref)7propert#Cange6racker92
1aop:before pointcut)7e$ecution(0oid set8(8))9 metod)7trackCange9=2
1=aop:aspect2
1=aop:config2
1bean id)7propert#Cange6racker9 class)7e$ample%!ropert#Cange6racker9 =2
M.- configuration uses the aop namespace
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
-A0
Developing Aspects with Spring AOP
48
Topics in this session
%hat Pro&lem Does AOP Solve'
Core AOP Concepts
Quic Start
Defining Pointcuts
!mplementing Advice
"d$anced topics
" -amed ointcuts
" Conte$t selecting pointcuts
" %oring with annotations
" -imitations of Spring AOP
49
Allow to reuse and com&ine pointcuts
5Aspect
public class !ropert#Cange6racker {
pri0ate /ogger logger ) /ogger%get/ogger(getClass())'
5*efore(7ser0ice,etod() LL repositor#,etod()9)
public 0oid monitor() {
logger%info(7A business metod as been accessed+9)'
(
5!ointcut(7e$ecution(8 rewards%ser0ice%%8"er0ice%8(%%))9)
public 0oid ser0ice,etod() {(
5!ointcut(7e$ecution(8 rewards%repositor#%%8Repositor#%8(%%))9)
public 0oid repositor#,etod() {(
(
#amed pointcuts
50
#amed pointcuts
E$pressions can &e e$ternali*ed
5Aspect
public class "er0ice,etodIn0ocation,onitor {
pri0ate /ogger logger ) /ogger%get/ogger(getClass())'
5*efore(7com%acme%"#stemArcitecture%ser0ice,etods()9 )
public 0oid monitor() {
logger%info(7A ser0ice metod as been accessed+9)'
(
(
public class "#stemArcitecture {
5!ointcut(7e$ecution(8 rewards%ser0ice%%8"er0ice%8(%%))9)
public 0oid ser0ice,etods() {(
(
Full#<Mualified pointcut name
51
+ive the possi&ilit, to &rea one complicated
e$pression into several su&-e$pressions
Allow pointcut e$pression reusa&ilit,
0est practice8 consider e$ternali*ing e$pressions
into one dedicated class
" %hen woring with man, pointcuts
" %hen writing complicated e$pressions
#amed pointcuts - Summar,
52
Topics in this session
%hat Pro&lem Does AOP Solve'
Core AOP Concepts
Quic Start
Defining Pointcuts
!mplementing Advice
"d$anced topics
" #amed Pointcuts
" Context selecting pointcuts
" %oring with annotations
" -imitations of Spring AOP
53
Conte$t Selecting Pointcuts
Pointcuts ma, also select useful >oin point
conte$t
" The currentl, e$ecuting o&>ect (pro$,)
" The target o&>ect
" .ethod arguments
" Annotations associated with the methodD targetD or
arguments
Allows for simple PO:O advice methods
" Alternative to woring with a :oinPoint o&>ect directl,
54
Conte$t Selecting E$ample
Consider this &asic re2uirement
/og a message e0er# time "er0er is about to start /og a message e0er# time "er0er is about to start
public interface "er0er {
public 0oid start(,ap input)'
public 0oid stop()'
(
public interface "er0er {
public 0oid start(,ap input)'
public 0oid stop()'
(
In te ad0ice- ow do we access "er0erN ,apN In te ad0ice- ow do we access "er0erN ,apN
55
%ithout conte$t selection
5*efore(7e$ecution(0oid e$ample%"er0erJ%start(;a0a%util%,ap))9)
public 0oid log"er0er"tartup(Foin!oint ;p) {
"er0er ser0er ) ("er0er) ;p%get6arget()'
Bb;ectHI args) ;p%getArgs()'
,ap map ) (,ap) argsHAI'
+
(
All needed info must &e o&tained from the
JoinPoint o&>ect
56
%ith conte$t selection
5*efore(7e$ecution(0oid e$ample%"er0erJ%start(;a0a%util%,ap))
OO target(ser0er) OO args(input)9)
public 0oid log"er0er"tartup("er0er ser0er- ,ap input) {
+
(
0est practice8 use conte$t selection
" .ethod attri&utes are &ound automaticall,
< target(ser0er) selects te target of te e$ecution (#our ob;ect)
< tis(ser0er) would a0e selected te pro$#
< target(ser0er) selects te target of te e$ecution (#our ob;ect)
< tis(ser0er) would a0e selected te pro$#
57
Conte$t Selection - #amed
Pointcut
5*efore(7ser0er"tart,etod(ser0er- input)9)
public 0oid log"er0er"tartup("er0er ser0er- ,ap input) {
+
(
5!ointcut(7e$ecution(0oid e$ample%"er0erJ%start(;a0a%util%,ap))
OO target(ser0er) OO args(input)9)
public 0oid ser0er"tart,etod ("er0er ser0er- ,ap input) {(
PtargetQ binds te ser0er starting up PargsQ binds te argument 0alue
58
Topics in this session
%hat Pro&lem Does AOP Solve'
Core AOP Concepts
Quic Start
Defining Pointcuts
!mplementing Advice
"d$anced topics
" #amed Pointcuts
" Conte$t selecting pointcuts
" Wor'ing with annotations
" -imitations of Spring AOP
59
Pointcut e$pression e$amples
using annotations
e$ecution(
5org%springframework%transaction%annotation%6ransactional
0oid 8(%%))
" An, method mared with the LTransactional
annotation
3 e$ecution( (5e$ample%6racked 8) 8(%%))
" An, method that returns a value mared with the
LTraced annotation
60
E$ample
5"ecured(allowedRoles){7teller9-9manager9()
public 0oid wai0eFee () {
+
(
equirements:
Run a securit# ceck before an# 5"ecured ser0ice operation
"ecurit# logic depends on:
7ccept1 te6t/$t"l,application/6$t"lG6"l,application/6"l(q=?'@,D/D(q=?'H
Jest available representation will be returned
Java ob'ect bac;ing resource t(picall( the sa$e
Single $odel+ onl( representation change
29
Content #egotiation C
HResponseJod(
HResponseJod( $ethod returns 'ust the $odel
)ow to choose correct )ttpMessageConverter for
re!uested representationM
#ot controller7s responsibilit(
#o ViewResolver involved either
Remember to use <mvc:annotation-driven! or to register custom
converters to have HttpMessageConverters defined at all!
30
5uto$atic Content
#egotiation
)ttpMessageConverter selected auto$aticall( for
HResponseJod(6annotated $ethods
Jased on 5ccept header in re!uest
Each converter has list of supported $edia t(pes
5llows $ultiple representations for a single
controller $ethod
&ithout affecting controller i$ple$entation
5lternative for content6based View selection as used
without HResponseJod(
31
Content #egotiation Sa$ple
@RequestMapping(value="/orders/#id&", "et$od=RequestMet$od'GET)
@Response!tatus(ttp!tatus'OK) // 2??
public @Response,od- .'de' getOrder(@;at$<aria-le("id") long id) #
'etu'n orderRepositor,'%indOrder5,*d(id)(
&
33;/1'1 2?? OI
=ate1 :
0ontentB.engt$1 1>JK
/ontent01-pe2 !pplic!tion&)ml
Aorder id=L123LC
:
A/orderC
M93 /store/orders/123
ost1 +++'",s$op'co"
3ccept2 !pplic!tion&)ml, '''
:
33;/1'1 2?? OI
=ate1 :
0ontentB.engt$1 NJK
/ontent01-pe2 !pplic!tion&4son
#
"order"1 #"id"1 123, "ite"s"1 O : P, : &
&
M93 /store/orders/123
ost1 +++'",s$op'co"
3ccept2 !pplic!tion&4son, '''
:
32
Topics in this Session
REST introduction
REST and Java
Spring MVC support for RESTful applications
Re!uest"Response Processing
Using MessageConverters
Content #egotiation
)utting it !ll together
RESTful clients with the RestTe$plate
Conclusion
33
Retrieving a Representation=
1ET
M93 /store/orders/123
ost1 +++'",s$op'co"
7ccept1 application/6"l, '''
:
@RequestMapping(value="/orders/#id&", "et$od=RequestMet$od'GET)
@Response!tatus(ttp!tatus'OK) // 2??1 t$is is t$e de%ault
public @Response,od- .'de' getOrder(@;at$<aria-le("id") long id) #
'etu'n orderRepositor,'%indOrder5,*d(id)(
&
33;/1'1 2?? OI
=ate1 :
0ontentB.engt$1 1>JK
0ontentB3,pe1 application/6"l
Aorder id=L123LC
:
A/orderC
34
Creating a new Resource=
P2ST
;O!3 /store/orders/123/ite"s
ost1 +++'",s$op'co"
0ontentB3,pe1 application/6"l
Aite"C
:
A/ite"C
@RequestMapping(value="/orders/#id&/ite"s", "et$od=RequestMet$od'POST)
@Response!tatus(ttp!tatus'CRE"TE#) // 2?1
public void create*te"(@;at$<aria-le("id") long id,
@Request5od, *te" ne+*te",
ttp!ervletRequest request,
ttp!ervletResponse response) #
orderRepositor,'%indOrder5,*d(id)'add*te"(ne+*te")( // adds id to *te"
response'addeader(".ocation",
get.ocation/or0$ildResource(request, ne+*te"'get*d()))(
&
33;/1'1 2?1 0reated
=ate1 :
0ontentB.engt$1 ?
.ocation1
$ttp1//+++'",s$op'co"/store/orders/123/ite"s/a-c
35
Updating e*isting Resource=
PUT
;)3 /store/orders/123/ite"s/a-c
ost1 +++'",s$op'co"
0ontentB3,pe1 application/6"l
Aite"C
:
A/ite"C
@RequestMapping(value="/orders/#order*d&/ite"s/#ite"*d&",
"et$od=RequestMet$od'PUT)
@Response!tatus(ttp!tatus'NO_CONTENT) // 2?>
public void update*te"(@;at$<aria-le("order*d") long order*d,
@;at$<aria-le("ite"*d") !tring ite"*d
@Request5od, *te" ite") #
orderRepositor,'%indOrder5,*d(order*d)'update*te"(ite"*d, ite")(
&
33;/1'1 2?> 8o 0ontent
=ate1 :
0ontentB.engt$1 ?
36
3eleting a Resource=
3E4ETE
=9.939 /store/orders/123/ite"s/a-c
ost1 +++'",s$op'co"
'''
@RequestMapping(value="/orders/#order*d&/ite"s/#ite"*d&",
"et$od=RequestMet$od'#ELETE)
@Response!tatus(ttp!tatus'NO_CONTENT) // 2?>
public void delete*te"(@;at$<aria-le("order*d") long order*d,
@;at$<aria-le("ite"*d") !tring ite"*d) #
orderRepositor,'%indOrder5,*d(order*d)'delete*te"(ite"*d)(
&
33;/1'1 2?> 8o 0ontent
=ate1 :
0ontentB.engt$1 ?
37
Topics in this Session
REST introduction
REST and Java
Spring MVC support for RESTful applications
Re!uest"Response Processing
Using MessageConverters
Content #egotiation
Putting it all together
RES&ul clients with the Restempl!te
Conclusion
38
Provides access to RESTful services
Supports UR% te$plates+ )ttpMessageConverters
and custo$ e*ecute.0 with callbac;s
Map or !tring''' for vars+ 4ava'net')R* or !tring for UR4
RestTe$plate %ntroduction
#115 Method Rest1empl!te Method
=9.939 delete(!tring url, !tring: url<aria-les)
M93 get/orO-4ect(!tring url, 0lassA3C response3,pe, !tring: url<aria-les)
97= $ead/oreaders(!tring url, !tring: url<aria-les)
O;3*O8! options/or7llo+(!tring url, !tring: url<aria-les)
;O!3 post/or.ocation(!tring url, O-4ect request, !tring: url<aria-les)
post/orO-4ect(!tring url, O-4ect request, 0lassA3C response3,pe,
!tring: uri<aria-les)
;)3 put(!tring url, O-4ect request, !tring:url<aria-les)
39
3efining a RestTe$plate
Just call constructor in (our code
Rest3e"plate te"plate = ne( Rest3e"plate()(
)as default )ttpMessageConverters
Sa$e as on the server+ depending on classpath
2r use e*ternal configuration
To use 5pache Co$$ons )TTP Client+ for e*a$ple
A-ean id="4sonRest3e"plate" class="org's%+'+e-'client'Rest3e"plate"C
Apropert, na"e="request/actor,"C
A-ean class="org's%+'$ttp'client'0o""ons0lientttpRequest/actor,"/C
A/propert,C
A/-eanC
40
RestTe$plate Usage E*a$ples
Rest3e"plate te"plate = ne( Rest3e"plate()(
!tring uri = "$ttp1//e6a"ple'co"/store/orders/#id&/ite"s"(
// M93 all order ite"s %or an e6isting order +it$ *= 11
Order*te"OP ite"s = te"plate'get/orO-4ect(uri, Order*te"OP'cl!ss, "1")(
// ;O!3 to create a ne+ ite"
Order*te" ite" = // create ite" o-4ect
)R* ite".ocation = te"plate'post/or.ocation(uri, ite", "1")(
// ;)3 to update t$e ite"
ite"'set7"ount(2)(
te"plate'put(ite".ocation, ite")(
// =9.939 to re"ove t$at ite" again
te"plate'delete(ite".ocation)(
S$rin% &'(') introd*ce+ ,tt$Entit-. /0ic0 ma1e+ addin% 0eader+ to t0e
,TTP re2*e+t ver- ea+- a+ /e33
41
Topics in this Session
REST introduction
REST and Java
Spring MVC support for RESTful applications
Re!uest"Response Processing
Using MessageConverters
Content #egotiation
Putting it all together
RESTful clients with the RestTe$plate
Conclusion
42
Conclusion
REST is an architectural st(le that can be applied
to )TTP6based applications
Useful for supporting diverse clients and building
highl( scalable s(ste$s
Java provides J596RS as standard specification
Spring6MVC adds REST support using a fa$iliar
progra$$ing $odel
E*tended b( HRe!uest6"HResponseJod(
Use RestTe$plate for accessing RESTful apps
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
45J
RESTful applications with Spring MVC
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Web Application Security with
Spring
Addressing Common Web Application
Security Requirements
2
Topics in this Session
High-Leel Security !eriew
Motivations of Spring Security
Spring Security in a Web nvironment
Configuring Web Authentication
!sing Spring Security"s Tag #ibraries
Method security
Advanced security$ wor%ing with filters
3
Security Concepts
&rincipal
' !ser( device or system that performs an action
Authentication
' stablishing that a principal)s credentials are valid
Authori*ation
' +eciding if a principal is allowed to perform an action
Secured item
' Resource that is being secured
4
Authentication
There are many authentication mechanisms
' e,g, basic( digest( form( -,./0
There are many storage options for credential
and authority information
' e,g, +atabase( #+A&( in1memory 2development3
5
Authori*ation
Authori*ation depends on authentication
' 4efore deciding if a user can perform an action( user
identity must be established
The decision process is often based on roles
' A+M56 can cancel orders
' MM4R can place orders
' 7!ST can browse the catalog
6
Topics in this Session
8igh1#evel Security 9verview
"oti#tions o$ Spring Security
Spring Security in a Web nvironment
Configuring Web Authentication
!sing Spring Security"s Tag #ibraries
Method security
Advanced security$ wor%ing with filters
7
Motivations$ &ortability
Servlet1Spec security is not portable
' Requires container specific adapters and role
mappings
Spring Security is portable across containers
' Secured archive 2e,g, WAR3 can be deployed as1is
' Also runs in standalone environments
8
Motivations$ :le;ibility
Supports all common authentication
mechanisms
' 4asic( :orm( -,./0( Coo%ies( Single1Sign19n( etc,
&rovides configurable storage options for user
details 2credentials and authorities3
' R+4MS( #+A&( &roperties file( custom +A9s( etc,
!ses Spring for configuration
9
Motivations$ ;tensibility
Security requirements often require
customi*ation
With Spring Security( all of the following are
e;tensible
' 8ow a principal is defined
' Where authentication information is stored
' 8ow authori*ation decisions are made
' Where security constraints are stored
10
Motivations$ Separation of
Concerns
4usiness logic is decoupled from security
concerns
' #everages Servlet :ilters and Spring A9& for an
interceptor1based approach
Authentication and Authori*ation are decoupled
' Changes to the authentication process have no
impact on authori*ation
11
Motivations$ Consistency
The goal of authentication is always the same
regardless of the mechanism
' stablish a security conte;t with the authenticated
principal)s information
The process of authori*ation is always the same
regardless of resource type
' Consult the attributes of the secured resource
' 9btain principal information from security conte;t
' 7rant or deny access
12
Spring Security$ the 4ig
&icture
Security Context
Authentication
(Principal + Authorities)
Secured
Resource
Authentication
Manager
populates
thread of
execution
obtains
AccessDecision
Manager
delegates
Config
Attributes
describes
consults protects
Security Interceptor
oters
polls
13
Topics in this Session
8igh1#evel Security 9verview
Motivations of Spring Security
Spring Security in # %eb &nironment
Configuring Web Authentication
!sing Spring Security"s Tag #ibraries
Method security
Advanced security$ wor%ing with filters
14
Configuration in the
Application Context
Spring configuration
!sing Spring Security"s <Security< namespace
!beans """#
!security$http#
!security$intercept%url pattern&'(accounts())'
access&'IS*A+,-./,ICA,.D*0+112' (#
!security$for3%login login%page&'(login"ht3'(#
!security$logout (#
!(security$http#
!(beans#
Match all +R1s starting 4ith
(accounts( (A/,%style path)
15
Configuration in 4eb"x3l
+efine the single pro;y filter
' springSecurity:ilterChain is a mandatory name
' 5t refers to an e;isting Spring bean with the same
name
!filter#
!filter%na3e#springSecurity0ilterChain!(filter%na3e#
!filter%class#
org"springfra3e4or5"4eb"filter"Delegating0ilterProxy
!(filter%class#
!(filter#
!filter%3apping#
!filter%na3e#springSecurity0ilterChain!(filter%na3e#
!url%pattern#()!(url%pattern#
!(filter%3apping#
16
intercept1url
intercept1urls are evaluated in the order listed
' The first match will be used
' specific matches should be put on top
!security$intercept%url pattern&'(accounts(login"ht3' filters&'none' (#
!security$intercept%url pattern&'(accounts(edit)'
access&'R61.*+S.R7 R61.*ADMI/' (#
!security$intercept%url pattern&'(accounts(account)' access&'R61.*+S.R' (#
!security$intercept%url pattern&'(accounts())'
access&'IS*A+,-./,ICA,.D*0+112' (#
17
Topics in this Session
8igh1#evel Security 9verview
Motivations of Spring Security
Spring Security in a Web nvironment
Con$iguring %eb 'uthentic#tion
!sing Spring Security"s Tag #ibraries
Method security
Advanced security$ wor%ing with filters
18
An ;ample #ogin &age
!for3 action&8!c$url 9alue&:;*spring*security*chec5:(#< 3ethod&8P6S,<#
!input type&8text< na3e&8;*userna3e<(#
!br(#
!input type&8pass4ord< na3e&8;*pass4ord<(#
!br(#
!input type&8sub3it< na3e&8sub3it< 9alue&816=I/<(#
!(for3#
,he expected 5eys
for generation of
an authentication
re>uest to5en
+R1 that indicates an
authentication re>uest
19
Configure Authentication
+A9 Authentication provider is default
&lug1in specific !ser+etailsService
implementation to provide credentials and
authorities
' 4uilt1in$ =+4C( in1memory
' Custom
!security$authentication%3anager#
!security$authentication%pro9ider#
"""
!(security$authentication%pro9ider#
!security$authentication%3anager#
20
The 5n1Memory user ser9ice (?(@)
!seful for development and testing
' Without encoding
' With encoding
!security$authentication%3anager#
!security$authentication%pro9ider#
!security:user-service properties&'(A.B%I/0(users"properties' (#
!(security$authentication%pro9ider#
!security$authentication%3anager#
!security$authentication%3anager#
!security$authentication%pro9ider#
!security:password-encoder hash&'3dC' (#
!security:user-service properties&'(A.B%I/0(users"properties' (#
!(security$authentication%pro9ider#
!security$authentication%3anager#
admin=secret,ROLE_ADMIN
testuser1=pass,ROLE_MEMBER
21
The 5n1Memory +serDetailsSer9ice
(@(@)
The properties file
admin=secret,ROLE_ADMIN,ROLE_MEMBER
testuser1=pass,ROLE_MEMBER
testuser2=pass,ROLE_MEMBER
guest=guest,ROLE_GUEST,ROLE_MEMBER
login pass4ord 1ist of roles separated by co33as
22
The =+4C user service 2>?@3
Aueries R+4MS for users and their authorities
&rovides default queries
' S#CT username( password( enabled :R9M users
W8R username B C
' S#CT username( authority :R9M authorities
W8R username B C
23
The =+4C user service 2@?@3
Configuration$
!security$authentication%3anager#
!security$authentication%pro9ider#
!security$;dbc%user%ser9ice data%source%ref&'3yDatasource' (#
!(security$authentication%pro9ider#
!security$authentication%3anager#
possibility to custo3iDe >ueries using
attributes such as
authorities%by%userna3e%>uery
24
9ther Authentication 9ptions
5mplement a custom +serDetailsSer9ice
' +elegate to an e;isting !ser repository or +A9
#+A&
-,./0 Certificates
=AAS #ogin Module
Single1Sign19n
' SiteMinder
' Derberos
' =A1S57 Central Authentication Service
AuthoriDation is not affected by changes to AuthenticationE
25
Topics in this Session
8igh1#evel Security 9verview
Motivations of Spring Security
Spring Security in a Web nvironment
Configuring Web Authentication
(sing Spring Security)s *#g Libr#ries
Method security
Advanced security$ wor%ing with filters
26
Tag library declaration
The Spring Security tag library can be declared
as follows
!FG taglib prefix&'security'
uri&'http$((444"springfra3e4or5"org(security(tags' F#
!FG taglib prefix&'security'
uri&'http$((444"springfra3e4or5"org(security(tags' F#
a9ailable since Spring Security @"H
27
Spring Security)s Tag #ibrary
+isplay properties of the Authentication obEect
8ide sections of output based on R9#
2ou are logged in as$
!security$authentication property&8principal"userna3e<(#
!security$authoriDe ifAny=ranted&8R61.*ADMI/<#
,6P%S.CR., I/06RMA,I6/
Clic5 !a href&8(ad3in(deleteAll<#-.R.!(a# to delete all records"
!(security$authoriDe#
,his +R1 should be protected by
the intercept%url tag alsoE
28
Topics in this Session
8igh1#evel Security 9verview
Motivations of Spring Security
Spring Security in a Web nvironment
Configuring Web Authentication
!sing Spring Security"s Tag #ibraries
"ethod security
Advanced security$ wor%ing with filters
29
Method security
Spring Security uses A9& for security at the
method level
' ;ml configuration with the Spring Security
namespace
' annotations based on Spring annotations or =SR1@./
annotations
30
Method security with
-M# config
Allows to apply security to many beans with
only a simple declaration
!security$global%3ethod%security#
!security$protect%pointcut
expression&'execution() co3"springsource"")Ser9ice")(""))'
access&'R61.*+S.R' (#
!(security$global%3ethod%security#
31
Method security with Spring
annotations
Spring Security annotations should be enabled
!security$global%3ethod%security secured%annotations&'enabled' (#
on the =ava level$
import org.springramewor!.security.annotation."ecured#
pu$%ic c%ass Ite3Manager I
GSecured('R61.*M.MB.R')
pu$%ic Ite3 findIte3(long ite3/u3ber) I
"""
J
J
32
Method security with =SR @./
annotations
=SR1@./ annotations should be enabled
!security$global%3ethod%security ;sr@CH%annotations&'enabled' (#
!security$global%3ethod%security ;sr@CH%annotations&'enabled' (#
on the =ava level$
import &ava'.annotation.security.(o%es)%%owed#
pu$%ic c%ass Ite3Manager I
GRolesAllo4ed('R61.*M.MB.R')
pu$%ic Ite3 findIte3(long ite3/u3ber) I
"""
J
J
import &ava'.annotation.security.(o%es)%%owed#
pu$%ic c%ass Ite3Manager I
GRolesAllo4ed('R61.*M.MB.R')
pu$%ic Ite3 findIte3(long ite3/u3ber) I
"""
J
J
33
Topics in this Session
8igh1#evel Security 9verview
Motivations of Spring Security
Spring Security in a Web nvironment
Configuring Web Authentication
!sing Spring Security"s Tag #ibraries
Method security
'd#nced security+ wor,ing with $ilters
34
Spring Security in a Web
nvironment
springSecurity:ilterChain is declared in web,;ml
This single pro;y filter delegates to a chain of
Spring1managed filters
' +rive authentication
' nforce authori*ation
' Manage logout
' Maintain SecurityContext in -ttpSession
' and more
35
Web Security :ilter
Configuration
*e$
+ser
Ser9let
Ser9let Container
Spring ApplicationContext
0ilter
@ K
0ilter
/
Delegating0ilterProxy
spring"ecurity,i%ter-.ain
0ilter
?
36
The :ilter chain
With AC75 Security >,;
' :ilters were manually configured as individual
FbeanG elements
' #ed to verbose and error1prone -M#
Since Spring Security @,/
' :ilters are initiali*ed with correct values by default
' Manual configuration is not required unless you
w#nt to customi-e Spring Security)s beh#ior
' 5t is still important to understand how they wor%
underneath
37
Access !nsecured Resource &rior
to #ogin
Aeb Bro4ser
+nsecuredResource
0ilterSecurityInterceptor
.xception,ranslation0ilter
AuthenticationProcessing0ilter
-ttpSessionContextIntegration0ilter
1ogout0ilter
/o context in session
/sta$%is.es empty
security conte't
/ot a logout re>uest
does nothing
/ot an authentication
re>uest does nothing
Does nothing on
re>uest side
Resource has no
security attributes
does nothing
Resource has no
security attributes
does nothing
/o exceptions thro4n
does nothing
Does nothing on
response side
Does nothing on
response side
Context did not
change so no need to
store in session
-%ears conte't
38
Access Secured Resource &rior to
#ogin
Aeb Bro4ser
SecuredResource
0ilterSecurityInterceptor
.xception,ranslation0ilter
AuthenticationProcessing0ilter
-ttpSessionContextIntegration0ilter
1ogout0ilter
/o context in session
/sta$%is.es empty
security conte't
Does nothing
Does nothing
Does nothing
Resource is secured
01(2*" 320
)+01/304-)0/5
/6-/70423
Authentication
exceptionE
L "aves current
re8uest in session
L-%ears conte't
L(edirects to
aut.entication entry
point
'
1ogin 0or3
39
Submit #ogin Request
Aeb Bro4ser
SecuredResource
0ilterSecurityInterceptor
.xception,ranslation0ilter
AuthenticationProcessing0ilter
-ttpSessionContextIntegration0ilter
1ogout0ilter
/o context in session
/sta$%is.es empty
security conte't
Does nothing
Creates re>uest and
delegates to the
Authentication
Manager
L"+--/""
populates context
redirects to target url
L,)49+(/
redirects to failure url
40
Access Resource With
Required Role
Aeb Bro4ser
SecuredResource
0ilterSecurityInterceptor
.xception,ranslation0ilter
AuthenticationProcessing0ilter
-ttpSessionContextIntegration0ilter
1ogout0ilter
,inds conte't in
session and sets
or current t.read
Does nothing
Does nothing
Does nothing
Consults attributes7
obtains context7 and
delegates to access
decision 3anager
Does nothing
Does nothing
"tores conte't $ac!
into session
Does nothing
Does nothing
41
Access Resource Without
Required Role
Aeb Bro4ser
SecuredResource
0ilterSecurityInterceptor
.xception,ranslation0ilter
AuthenticationProcessing0ilter
-ttpSessionContextIntegration0ilter
1ogout0ilter
,inds conte't in
session and sets
or current t.read
Does nothing
Does nothing
Does nothing
0.rows )--/"" 5/34/5 /6-/70423
'
Consults attributes7
obtains context7 and
delegates to access
decision 3anager
Access Denied
.xceptionE
L 7uts e'ception in
re8uest scope
L ,orwards to t.e
error page
.rror Page
42
Submit #ogout Request
Aeb Bro4ser
SecuredResource
0ilterSecurityInterceptor
.xception,ranslation0ilter
AuthenticationProcessing0ilter
-ttpSessionContextIntegration0ilter
1ogout0ilter
,inds conte't in
session and sets
or current t.read
L -%ears conte't
L (edirects to
%ogout success ur%
1ogout Success
43
The :ilter Chain$ Summary
. /ilter 0#me "#in 1urpose
>
8ttpSessionConte;t
5ntegration:ilter
stablishes SecurityConte;t and
maintains between 8TT& requests
@ #ogout:ilter
Clears SecurityConte;t8older when
logout requested
H
Authentication
&rocessing :ilter
&uts Authentication into the
SecurityConte;t on login request
I
;ception
Translation:ilter
Converts SpringSecurity e;ceptions
into 8TT& response or redirect
.
:ilterSecurity
5nterceptor
Authori*es web requests based on
on config attributes and authorities
44
Custom :ilter Chain
9ne filter on the stac% may be repl#ced by a
custom filter
!security$http#
!custo3%filter position&'06RM*16=I/*0I1,.R' ref&'3y0ilter< (#
!(security$http#
!bean id&'3y0ilter' class&'co3"3yco3pany"MySpecialAuthentication0ilter'(#
!security$http#
!custo3%filter after&'06RM*16=I/*0I1,.R' ref&'3y0ilter< (#
!(security$http#
!bean id&'3y0ilter' class&'co3"3yco3pany"MySpecial0ilter'(#
9ne filter can be #dded to the chain
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
#A4
Applying Security to a Web Application
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Introduction to Spring Remoting
Simplifying Distributed Applications
2
Topics in this Session
Goals o Spring !emoting
Spring Remoting Overview
Supported Protocols
R!I
"ttpInvo#er
"essian$%urlap
3
&oals of Spring Remoting
"ide 'plumbing( code
)onfigure and e*pose services declaratively
Support multiple protocols in a consistent way
4
The Problem with Plumbing )ode
Remoting mechanisms provide an abstraction
over transport details
These abstractions are often lea#y
The code must conform to a particular model
+or e*ample, with R!I-
Service interface e*tends Remote
Service class e*tends UnicastRemoteObject
)lient must catch RemoteExceptions
"iolates a separation o concerns
Couples business logic to remoting
inrastructure
5
"iding the Plumbing with Spring
Spring provides exporters to handle server.
side re/uirements
%inding to registry or e*posing an endpoint
)onforming to a programming model if necessary
Spring provides FactoryBeans that generate
proxies to handle client.side re/uirements
)ommunicate with the server.side endpoint
)onvert remote e*ceptions to a runtime hierarchy
6
The Declarative Approach
Spring0s abstraction uses a configuration.based
approach
On the server side
1*pose e*isting services with 2O code changes
On the client side
Invo#e remote methods from e*isting code
Ta#e advantage of polymorphism by using
dependency in3ection
7
)onsistency across Protocols
Spring0s e*porters and pro*y FactoryBeans bring
the same approach to multiple protocols
Provides fle*ibility
Promotes ease of adoption
On the server side
1*pose a single service over multiple protocols
On the client side
Switch easily between protocols
!igrate between remote vs4 local deployments
8
Topics in this Session
&oals of Spring Remoting
Spring !emoting #$er$iew
Supported Protocols
R!I
"ttpInvo#er
"essian$%urlap
9
Service 1*porters
Spring provides service e*porters to enable
declarative e*posing of e*isting services
transfer(..)
transfer(..)
Spring
ServiceExporter
<<interface>>
TransferService
TransferServiceImpl
Teller
Controller
Accessile from remote clients
10
)lient Pro*ies
Dynamic pro*ies generated by Spring
communicate with the service e*porter
Spring
ServiceExporter
Server !rocess
TransferServiceImpl
"enerate# y a Spring FactoryBean
<<interface>>
TransferService
transfer(..)
Spring
!roxy
Client !rocess
<<interface>>
TransferService
Teller
$es%top
&I
11
Topics in this Session
&oals of Spring Remoting
Spring Remoting Overview
Supported %rotocols
R!I
"ttpInvo#er
"essian$%urlap
12
The R!I Protocol
Standard 5ava remoting protocol
Server.side e*poses a skeleton
)lient.side invo#es methods on a stub 6pro*y7
5ava seriali8ation is used for marshalling
13
Traditional R!I
The R!I model is invasive . server and client
code is coupled to the framewor#
transfer(..)
S%eleton
Server !rocess
TransferServiceImpl
St'
Client !rocess
(emote &nicast(emote)*ect
<<interface>>
TransferService
Teller
$es%top
&I
Client m'st catc+
RemoteExceptions
(e,'ire# to exten# (-I
interface.class
14
Spring0s R!I Service 1*porter
Transparently e*pose an e*isting PO5O service
to the R!I registry
2o need to write the binding code
Avoid traditional R!I re/uirements
Service interface does not e*tend Remote
Service class is a PO5O
15
)onfiguring the R!I Service 1*porter
Start with an e*isting PO5O service
Define a bean to e*port it
<ean i#/0transferService1 class/0foo.TransferServiceImpl1>
<property name/0acco'nt(epository1 ref/0acco'nt(epository1.>
<.ean>
<ean i#/0transferService1 class/0foo.TransferServiceImpl1>
<property name/0acco'nt(epository1 ref/0acco'nt(epository1.>
<.ean>
<ean class/0org.springframe2or%.remoting.rmi.(miServiceExporter1>
<property name/0service3ame1 val'e/0transferService1.>
<property name/0serviceInterface1 val'e/0foo.TransferService1.>
<property name/0service1 ref/0transferService1.>
<.ean>
Can also specify 4registry!ort5 (#efa'lt is 6788)
<property name/0registry!ort1 val'e/067891.>
Bin#s to rmi(egistry as 0transferService1
16
Spring0s R!I Pro*y &enerator
Spring provides a FactoryBean implementation
that generates an R!I client.side pro*y
It is simpler to use than a traditional R!I stub
)onverts chec#ed (emoteExceptions into Spring0s
runtime hierarchy of (emoteAccessExceptions
Dynamically implements the business interface
Proxy is a rop!in rep"acement #or a "oca" imp"ementation
$especia""y con%enient &it' epenency injection(
17
)onfiguring the R!I Pro*y
Define a factory bean to generate the pro*y
In3ect it into the client
<ean i#/0transferService1
class/0org.springframe2or%.remoting.rmi.(mi!roxyFactoryBean1>
<property name/0serviceInterface1 val'e/0foo.TransferService1.>
<property name/0service&rl1 val'e/0rmi:..foo:6788.transferService1.>
<.ean>
<ean i#/0teller$es%top&I1 class/0foo.Teller$es%top&I1>
<property name/0transferService1 ref/0transferService1.>
<.ean>
Teller$es%top&I only #epen#s on t+e TransferService
interface
18
Spring0s "ttpInvo#er
A lightweight "TTP.based remoting protocol
!ethod invocation is converted to an "TTP POST
!ethod result is returned as an "TTP response
!ethod parameters and return values are marshalled
with standard 5ava seriali8ation
;TT! !)ST re,'est
;ttpInvo%er
ServiceExporter
Server !rocess
;ttpInvo%er
!roxy
Client !rocess
;TT! response
<ava seriali=ation
19
)onfiguring the "ttpInvo#er
Service 1*porter
Start with an e*isting PO5O service
Define a bean to e*port it
<ean i#/0transferService1 class/0foo.TransferServiceImpl1>
<property name/0acco'nt(epository1 ref/0acco'nt(epository1.>
<.ean>
<ean name /0.transfer1
class/0org.springframe2or%.remoting.+ttpinvo%er.
;ttpInvo%erServiceExporter1>
<property name/0serviceInterface1 val'e/0foo.TransferService1.>
<property name/0service1 ref/0transferService1.>
<.ean>
en#point for ;TT! re,'est
+an#ling
20
)onfiguring the "ttpInvo#er
Pro*y
Define a factory bean to generate the pro*y
In3ect it into the client
<ean i#/0transferService1
class/0org.springframe2or%.remoting.+ttpinvo%er.
;ttpInvo%er!roxyFactoryBean1>
<property name/0serviceInterface1 val'e/0foo.TransferService1.>
<property name/0service&rl1 val'e/0+ttp:..foo:>7>7.services.transfer1.>
<.ean>
<ean i#/0teller$es%top&I1 class/0foo.Teller$es%top&I1>
<property name/0transferService1 ref/0transferService1.>
<.ean>
;TT! !)ST re,'ests 2ill e sent to t+is
&(?
21
"essian and %urlap
)aucho created these two lightweight protocols
for sending 9!: over "TTP
"essian uses binary 9!: 6more efficient7
Implementations for many languages
%urlap uses te*tual 9!: 6human readable7
The Ob3ect$9!: seriali8ation$deseriali8ation
relies on a proprietary mechanism
%etter performance than 5ava seriali8ation
:ess predictable when wor#ing with comple* types
22
"essian and %urlap
)onfiguration
Service e*porter configuration is identical to
;ttpInvo%erServiceExporter e*cept class names
@ org.springframe2or%.remoting.ca'c+o.;essianServiceExporter
@ org.springframe2or%.remoting.ca'c+o.B'rlapServiceExporter
Pro*y configuration is identical to
;ttpInvo%er!roxyFactoryBean e*cept class names
@ org.springframe2or%.remoting.ca'c+o.;essian!roxyFactoryBean
@ org.springframe2or%.remoting.ca'c+o.B'rlap!roxyFactoryBean
23
)hoosing a Remoting
Protocol 6;7
Spring on server and client<
"ttpInvo#er
5ava environment but no web server<
R!I
Interop with other languages using "TTP<
"essian 6wor#able, but not ideal7
Interop with other languages without "TTP<
R!I.IIOP 6)OR%A7
24
)hoosing a Remoting
Protocol 6=7
Also consider the relationship between server and client
All of the protocols discussed here are based upon
Remote Procedure )alls 6RP)7
)lients need to #now details of method invocation
2ame, parameters, and return value
>hen using 5ava seriali8ation
)lasses$interfaces must be available on client
?ersions must match
If serving public clients beyond your control, >eb
Services are usually a better option
Document.based messaging promotes loose coupling
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
:A%
Simplifying Distributed Applications with Spring
Remoting
Copyright 2006-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Spring JMS
Simplifying Messaging Applications
2
Topics in this Session
Introduction to JS
Apache ActiveMQ
Configuring JMS Resources with Spring
Springs JmsTemplate
Sending Messages
Receiving Messages
3
Java Message Service JMS!
The JMS A"# provides an a$straction for
accessing Message %riented Middleware
& Avoid vendor loc'(in
& #ncrease porta$ility
4
JMS Core Components
Message
)estination
Connection
Session
Message"roducer
MessageConsumer
5
JMS Message Types
#mplementations of the Message interface
TextMessage
ObjectMessage
MapMessage
BytesMessage
StreamMessage
6
JMS )estination Types
#mplementations of the Destination interface
Queue
"oint(to(point messaging
Topic
"u$lish*su$scri$e messaging
7
The JMS Connection
A JMS Connection is o$tained from a factory
#n a typical enterprise application+ the
Connection,actory is a managed resource and
$ound to J-)#
Connection conn = connectionFactorycreateConnection!"#
$roperties en% = new $roperties!"#
&& pro%i'e J(D) en%ironment properties
Context ctx = new )nitialContext!en%"#
ConnectionFactory connectionFactory =
!ConnectionFactory" ctxloo*up!+connFactory+"#
8
The JMS Session
A Session is created from the Connection
& Represents a unit(of(wor'
& "rovides transactional capa$ility
Session session = conncreateSession!
boolean transacte', int ac*no-le'geMo'e"#
&& use session
if !e%eryt.ingO*ay" /
session.commit();
0 else /
session.rollback();
0
9
Creating Messages
The Session is responsi$le for the creation of
various JMS Message types
sessioncreateTextMessage!+Some Message Content+"#
sessioncreateObjectMessage!someSeriali1ableObject"#
MapMessage message = sessioncreateMapMessage!"#
messageset)nt!+some2ey+, 345"#
BytesMessage message = sessioncreateBytesMessage!"#
message-riteBytes!someByte6rray"#
10
"roducers and Consumers
The Session is also responsi$le for creating
instances of Message$ro'ucer and
MessageConsumer
pro'ucer = sessioncreate$ro'ucer!someDestination"#
consumer = sessioncreateConsumer!someDestination"#
11
Topics in this Session
#ntroduction to JMS
!p"che !cti#e$
Configuring JMS Resources with Spring
Springs JmsTemplate
Sending Messages
Receiving Messages
12
JMS "roviders
Most providers of Message %riented Middleware
MoM! support JMS
& .e$Sphere MQ+ Ti$co /MS+ %racle /MS+ J$oss A"+
SwiftMQ+ etc0
& Some are %pen Source+ some commercial
& Some are implemented in Java themselves
The la$ for this module uses Apache ActiveMQ
13
Apache ActiveMQ
%pen source message $ro'er written in Java
Supports JMS and many other A"#s
& #ncluding non(Java clients1
Can $e used stand(alone in production
environment
& 2activem32 script in download starts with default config
& SpringSource provides support
Can also $e used em$edded in an application
& Configured through ActiveMQ or Spring 4ml files
& .hat we use in the la$s
14
Apache ActiveMQ ,eatures
Support for5
Many cross language clients 6 transport protocols
& #ncl0 /4cellent Spring integration
,le4i$le 6 powerful deployment configuration
& Clustering incl0 load($alancing 6 failover+ 000
Advanced messaging features
& Message groups+ virtual 6 composite destinations+
wildcards+ etc0
/nterprise #ntegration "atterns when com$ined with
Spring #ntegration or Apache Camel
& from the $oo' $y 7regor 8ohpe 6 9o$$y .oolf
15
Topics in this Session
#ntroduction to JMS
Apache ActiveMQ
Con%iguring JS &esources with Spring
Springs JmsTemplate
Sending Messages
Receiving Messages
16
Configuring JMS Resources with
Spring
Spring ena$les decoupling of your application
code from the underlying infrastructure
& The container provides the resources
& The application is simply coded against the A"#
This provides deployment fle4i$ility
& use a standalone JMS provider
& use an ApplicationServer to manage JMS resources
17
Configuring a
ConnectionFactory
The ConnectionFactory may $e standalone
%r it may $e retrieved from J-)#
7bean i'=+connectionFactory+
class=+orgapac.eacti%em86cti%eMQConnectionFactory+9
7property name=+bro*er:;<+ %alue=+tcp=&&local.ost=>3>3>+&9
7&bean9
7jee=jn'i?loo*up i'=+connectionFactory+
jn'i?name=+jms&ConnectionFactory+&9
18
Configuring Destinations
The Destinations may $e standalone
%r they may $e retrieved from J-)#
7bean i'=@or'erQueueA
class=@orgapac.eacti%em8comman'6cti%eMQQueueA9
7constructor?arg %alue=@8ueueor'erA&9
7&bean9
7jee=jn'i?loo*up i'=@or'erQueueA
jn'i?name=@jms&Or'erQueueA&9
19
Topics in this Session
#ntroduction to JMS
Apache ActiveMQ
Configuring JMS Resources with Spring
Spring's JmsTemlate
Sending Messages
Receiving Messages
20
Springs JmsTemplate
The template simplifies usage of the A"#
& Reduces $oilerplate code
& Manages resources transparently
& 8andles e4ceptions properly
& Converts chec'ed e4ceptions to runtime e3uivalents
& "rovides convenience methods and call$ac's
21
JmsTemplate Strategies
The JmsTemplate delegates to colla$orators to
handle some of the wor'
& MessageConverter
& )estinationResolver
22
MessageConverter
The JmsTemplate uses a MessageCon%erter to
convert $etween o$:ects and messages
The default SimpleMessageConverter handles
$asic types
String to TextMessage
Seriali1able to ObjectMessage
Map to MapMessage
byteBC to BytesMessage
23
#mplementing
MessageConverter
#t is sometimes desira$le to provide your own
conversion strategy
& Reuse e4isting code
& )elegate to an o$:ect(to(;M< translator
#mplement the two necessary methods
"rovide the implementation to JmsTemplate via
dependency in:ection
Message toMessage!Object o, Session session"
Object DromMessage!Message message"
24
)estinationResolver
#t is often necessary to resolve destination
names at runtime
JmsTemplate uses DynamicDestination;esol%er as
a default
The Jn'iDestination;esol%er is also availa$le
The interface only re3uires one method
Destination resol%eDestination(ame!Session session,
String 'estination(ame,
boolean pubSubDomain"
t!rows JMSException#
25
)efining a JmsTemplate 9ean
"rovide a reference to the ConnectionFactory
%ptionally provide other references
& MessageConverter
& )estinationResolver
& )efault )estination or default )estination name!
7bean i'=@jmsTemplateA
class=@orgspringDrame-or*jmscoreJmsTemplateA9
7property name=@connectionFactoryA reD=@connectionFactoryA&9
7property name=@'eDaultDestinationA reD=@or'erQueueA&9
7&bean9
26
CachingConnection,actory
JmsTemplate aggressively closes and reopens
JMS resources li'e Sessions and Connections
& Assumes these are cached $y Connection,actory
.ithout caching this causes lots of overhead
& Resulting in poor performance
=se CachingConnection,actory to add caching
within the application if needed
7bean i'=+connectionFactory+
class=+or".srin"framework.#ms.connection.$ac!in"$onnection%actor&+9
7property name=+tar"et$onnection%actor&+9
7bean class=+orgapac.eacti%em86cti%eMQConnectionFactory+9
7property name=+bro*er:;<+ %alue=+%m=&&embe''e'Fbro*erpersistent=Dalse+&9
7&bean9
7&property9
7&bean9
27
Topics in this Session
#ntroduction to JMS
Apache ActiveMQ
Configuring JMS Resources with Spring
Springs JmsTemplate
Sending ess"ges
Receiving Messages
28
Sending Messages
The template provides options
& %ne line methods that leverage the templates
MessageConverter
& Call$ac'(accepting methods that reveal more of the
JMS A"#
=se the simplest option for the tas' at hand
29
Sending Messages with
Conversion
<everaging the templates MessageConverter
'blic (oi) con%ert6n'Sen'!Object message"#
'blic (oi) con%ert6n'Sen'!Destination 'estination,
Object message"#
'blic (oi) con%ert6n'Sen'!String 'estination(ame
Object message"#
30
Sending Messages with
Call$ac's
.hen more control is needed+ use call$ac's
'blic (oi) sen'!MessageCreator messageCreator"#
'blic Object execute!$ro'ucerCallbac*7T9 action"#
'blic Object execute!SessionCallbac*7T9 action"#
Message createMessage!Session session" /G0
31
Creating the 3ueue reference
yourself using a call$ac'
jmsTemplateexecute!new SessionCallbac*7Object9!" /
'blic Object 'o)nJms!Session session" t!rows JMSException /
Queue 8ueue = sessioncreateQueue!+someQueue+"#
Message$ro'ucer pro'ucer =
sessioncreate$ro'ucer!8ueue"#
Message message =
sessioncreateTextMessage!+Hello QueueI+"#
pro'ucersen'!message"#
ret'rn n'll#
0
0"#
32
Topics in this Session
#ntroduction to JMS
Apache ActiveMQ
Configuring JMS Resources with Spring
Springs JmsTemplate
Sending Messages
&ecei#ing ess"ges
33
Synchronous Message
Reception
JmsTemplate can also receive messages+ $ut
methods are $loc'ing with optional timeout!
recei%e!"
recei%e!Destination 'estination"
recei%e!String 'estination(ame"
The MessageCon%erter can $e leveraged for
message reception as well
Object someSeriali1able =
jmsTemplaterecei%e6n'Con%ert!someDestination"#
34
The JMS Message<istener
The JMS A"# defines this interface for
asynchronous reception of messages
public %oi' onMessage!Message" /
&& .an'le t.e message
0
35
Springs Message<istener
Containers
Traditionally+ use of Message<istener
implementations re3uired an /J9 container
Spring provides lightweight alternatives
& SimpleMessage<istenerContainer
=ses plain JMS client A"#
Creates a fi4ed num$er of Sessions
& )efaultMessage<istenerContainer
Adds transactional capa$ility
Advanced scheduling and endpoint management
options availa$le for each container option
36
)efining a plain
JMS Message <istener
)efine listeners using :ms5listener elements
<istener needs to implement Message<istener or
SessionAwareMessage<istener
:ms5listener(container allows for twea'ing of
tas' e4ecution strategy+ concurrency+ container
type+ transaction manager and more
7jms=listener?container connection?Dactory=+myConnectionFactory+9
7jms=listener 'estination=+8ueueor'er+ reD=+myOr'er<istener+&9
7jms=listener 'estination=+8ueueconD+ reD=+myConD<istener+&9
7&jms=listener?container9
37
Spring2s message(driven o$:ects
Spring also allows you to specify a plain Java
o$:ect that can serve as a listener
"arameter automatically converted using a
MessageConverter
Return value sent to response(destination
7jms=listener reD=+mySimpleObject+
met.o'=+or'er+
'estination=+8ueueor'ers+
response?'estination=+8ueueconDirmation+&9
'blic class Or'erSer%ice /
'blic Or'erConDirmation or'er!Or'er o" /0
0
1
1
2
2
3
3
Copyright 2006-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
<A9
Sending and Receiving Messages in a Spring
/nvironment
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Performance and Operations with
Spring
Management and Monitoring of Java
Applications
2
Topics in this Session
Introduction
JMX
Introducing Spring JMX
Eplicitl! eporting "eans with Spring
Automaticall! eporting eisting M#eans
Spring Insight
3
Overall $oals
$ather information a"out application during
runtime
%!namicall! reconfigure app to align to eternal
occasions
Trigger operations inside the application
Even adapt to "usiness changes in smaller
scope
4
Topics in this Session
Introduction
J!
Introducing Spring JMX
Eplicitl! eporting "eans with Spring
Automaticall! eporting eisting M#eans
Spring Insight
5
&hat is JMX'
The Java Management Etensions specification
aims to create a standard API for adding
management and monitoring to Java
applications
Management
( )hanging configuration properties at runtime
Monitoring
( *eporting cache hit+miss ratios at runtime
6
,ow JMX &or-s
To add this management and monitoring
capa"ilit!. JMX instruments application
components
JMX introduces the concept of the M#ean
( An o"/ect with management metadata
7
JMX Architecture
MBeanServer
MBean MBean MBean
JSR-160
Connector
JSR-160
Connector
8
JMX Architecture
An M#eanServer acts as a "ro-er for
communication "etween
( Multiple local M#eans
( *emote clients and M#eans
An M#eanServer maintains a -e!ed reference to
all M#eans registered with it
Man! generic clients availa"le
( /console. /visualvm. ,!peric
9
JMX Architecture
An M#ean is an o"/ect with additional
management metadata
( Attri"utes 0 properties1
( Operations 0 methods1
The management metadata can "e defined
staticall! with a Java interface or defined
d!namicall! at runtime
( Simple M#ean or %!namic M#ean respectivel!
10
Plain JMX ( Part I
public class JmxCounter implements JmxCounterMBean {
public int getCount() {}
public void increment() {}
}
public interface JmxCounterMBean {
int getCount(); becomes !ttribute named "Count"
void increment(); becomes #peration named "increment"
}
11
Plain JMX ( Part II
MBean$erver server % Management&actor'(get)latformMBean$erver();
JmxCounter bean % ne* JmxCounter();
tr' {
#b+ect,ame name % ne* #b+ect,ame(-ourapp.name%counter-);
server(registerMBean(bean/ name);
} catc0 (1xception e) {
e(print$tac23race();
}
12
Topics in this Session
Introduction
JMX
Introducing Spring J!
Eplicitl! eporting "eans with Spring
Automaticall! eporting eisting M#eans
Spring Insight
13
$oals of Spring JMX
2sing the raw JMX API is difficult and comple
The goal of Spring3s JMX support is to simplif!
the use of JMX while hiding the compleit! of
the API
14
$oals of Spring JMX
)onfiguring JMX infrastructure
( %eclarativel! using contet namespace or
4actor!#eans
Eposing Spring "eans as M#eans
( Annotation "ased metadata
( %eclarativel! using Spring "ean definitions
)onsuming JMX managed "eans
( Transparentl! using a pro!5"ased mechanism
15
)reating an M#eanServer
To locate or create an M#eanServer
declarativel!. use the contet namespace
6 or declare it eplicitl!
4context.mbean5server 6
4bean id%-mbean$erver-
class%-org(springframe*or2(+mx(support(
MBean$erver&actor'Bean-6
4propert' name%-locate1xisting$erver7f)ossible- value%-true-6
4bean6
16
Topics in this session
Introduction
JMX
Introducing Spring JMX
"xplicitly exporting be#ns with Spring
Automaticall! eporting eisting M#eans
Spring Insight
17
Eport "ean as JMX M#ean
using Annotations
8Managed9esource(description%:! simple JM; counter<)
public class JmxCounter7mpl implements JmxCounter {
8Managed!ttribute(description%:30e counter value<)
public int getCount() {}
8Managed#peration(description%:7ncrements t0e counter value<)
public void increment() {}
}
4context.mbean5export6
Annotate !our class and methods to "e eposed
Activate eporter
O"/ect7ame derived from full! 8ualified class name
( or passed as attri"ute to 9Managed*esource
18
Spring3s M#eanEporter
Transparentl! epose an eisting POJO "ean to
the M#eanServer
( 7o need to write the registration code
#! default avoids the need to create an eplicit
management interface or create an O"/ect7ame
instance
( 2ses reflection to manage all properties and methods
( 2ses map -e! as the O"/ect7ame
19
Eporting a "ean as an
M#ean
Start with an eisting POJO "ean
2se the M#eanEporter to eport it
4bean id%-message$ervice- class%-example(Message$ervice-6
4bean class%-org(springframe*or2(+mx(export(MBean1xporter-6
4propert' name%-beans-6
4map6
4entr' 2e'%-service.name%message$ervice-
value5ref%-message$ervice-6
4map6
4propert'6
4bean6
20
Spring in the JMX architecture
$pring
MBean1xporter
$erver )rocess
JmxCounter7mpl
$pring
)rox'
Client )rocess
Client
MBean
$erver
9egistration
at startup
44interface66
JmxCounter
44interface66
JmxCounter
44interface66
JmxCounter
MBean
=enerated
at startup
21
Topics in this session
Introduction
JMX
Introducing Spring JMX
Eplicitl! eporting "eans with Spring
$utom#tic#lly exporting existing %e#ns
Spring Insight
22
Automaticall! eporting
pre5eisting M#eans
Some "eans are M#eans themselves
( e:g: ,i"ernate StatisticsService
Spring can easil! autodetect those and eport
them for !ou
4context.mbean5export6
4bean id%-statistics$ervice-
class%-org(0ibernate(+mx($tatistics$ervice-6
4propert' name%-session&actor'- ref%-session&actor'-6
4bean6
23
Automaticall! eporting
pre5eisting M#eans
;og</ 5 ;ogger%!namicM#ean
4context.mbean5export6
4bean class%-org(apac0e(log>+(+mx(?ogger@'namicMBean-6
4constructor5arg6
4bean class%-org(apac0e(log>+(?ogger-
factor'5met0od%-get?ogger-6
4constructor5arg value%-org(springframe*or2(+mx- 6
4bean6
4constructor5arg6
4bean6
24
Summar!
Spring JMX allows !ou to easil! eport
Spring5managed "eans to a JMX M#eanServer
( Simple value5add now that !our "eans are managed
2se =contet>m"ean5server? to create M#ean
server
2se Spring annotations to declare JMX metadata
2se =contet>m"ean5eport? to automaticall!
eport pre5eisting M#eans
25
Topics in this session
Introduction
JMX
Introducing Spring JMX
Eplicitl! eporting "eans with Spring
Automaticall! eporting eisting M#eans
Spring Insight
26
Spring Insight Overview
Part of tc Server %eveloper Edition
Monitors we" applications deplo!ed into
tc Server
4ocuses on what3s relevant
( esp: performance related parts of the application
%etects performance issues during development
27
Spring Insight Overview
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
What's next?
Certification
Other courses
Resources
Evaluation
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 2
Certification
Computer-based exam
5 multiple-choice !uestions
" minutes
#assin$ score% &'( )*+ !uestions ans,ered
successfull-.
Where?
/n an- #earson 01E 2est Center
2here are some in most bi$ or medium-si3ed cities
4ee http%55,,,6pearsonvue6com5vtclocator5
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 3
Certification )7.
8o, to prepare for the exam?
4ee the Core 4prin$ *6x certification $uide here%
http%55,,,6sprin$source6com5trainin$5certification5sprin$professional
Revie, all the slides
Redo the labs
8o, to re$ister?
9t the end of the class: -ou ,ill receive a voucher b-
email
;or an- further in!uir-: -ou can ,rite to
sprin$sourceuniversit-<vm,are6com
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 4
Other courses
=an- courses available
Rich Web 9pplications ,ith 4prin$
Enterprise /nte$ration ,ith 4prin$
8ibernate ,ith 4prin$
>roov- and >rails
tc 4erver: 2omcat: 8-peric
?
=ore details here%
http%55,,,6sprin$source6com5trainin$5curriculum
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 5
Rich Web 9pplications ,ith 4prin$
@-da- ,orAshop
=aAin$ the most of 4prin$ in the ,eb la-er
4prin$ =0C and 4prin$ Web ;lo,
Rich 1ser /nterfaces: 4prin$ Bava4cript: CoDo
B4; ,ith 4prin$ ;aces
;lex clients ,ith 4prin$ Ela3eC4
#roductivit- ,ith Roo and >rails
4prin$ Web 9pplication Ceveloper certification
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 6
Enterprise /nte$ration ,ith 4prin$
@ da- course that ,ill $ive -ou the opportunit- to%
Ciscover 4prin$ Eatch
Ciscover 4prin$ /nte$ration
WorA ,ith advanced transaction mana$ement
Fearn ho, to ,orA ,ith concurrenc-
Fearn Web 4ervices best practices
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 7
8ibernate ,ith 4prin$
* da- course that ,ill $ive -ou the opportunit- to%
Confi$ure 8ibernate applications ,ith 4prin$ and
4prin$ 2ransactions )overlaps this course.
/mplement inheritance and relationships ,ith B#9
and 8ibernate
Ciscover ho, 8ibernate mana$es obDects
>o more in depth on locAin$ ,ith 8ibernate
9dvanced features such as interceptors: cachin$
and batch updates
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 8
Consultin$ Offerin$s
GuicA 4can
Expert revie,s proDect or architecture and sho,s ho,
to improve
8-peric Bump 4tart
8elps -ou startin$ ,ith 8-peric to monitor -our
environment
Bava EE to tc 4erver =i$ration
2omcat to tc 4erver =i$ration
=i$rate -our application and production environment
to tc 4erver
9nd custom consultin$ en$a$ements that fits
-our specific needs
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 9
Resources
2he 4prin$ reference documentation
http%55,,,6sprin$source6or$5documentation
9lread- +H pa$esI
2he official technical blo$
http%55blo$6sprin$source6com5
2he 4prin$ communit- forums
http%55forum6sprin$frame,orA6or$5
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 10
Resources )7.
Jou can re$ister issues on our Bira repositor-
http%55Dira6sprin$frame,orA6or$5
2he source code is available here
https%55src6sprin$source6or$5svn5sprin$-frame,orA
=ore information on ho, to build 4prin$%
http%55blo$6sprin$source6com57"5*5*5buildin$-sprin$-*5
;ollo, 4prin$ development via R44
https%55fishe-e6sprin$source6or$5bro,se5sprin$-frame,orA5trunA
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 11
2hanA JouI
We hope -ou enDo-ed the course
#lease fill out the evaluation form at
http://www.springsource.com/training/evaluation
Copyright2006-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Object/Relational Mapping with
Spring and Java Persistence API
2
Topics in this session
Introduction to J!
eneral !oncepts
Mapping
"#er$ing
!on%ig#ring an &ntit$Manager in Spring
I'ple'enting JPA (AOs
3
JPA eneral !oncepts
The "ntity#$n$ger represents a #nit o% wor)
Also )nown as PersistenceContext
!orresponds at a higher*level to a !onnection
Manages persistent objects within the #nit*o%*wor)
4
JPA eneral !oncepts +,-
An "ntity#$n$ger%$ctory is a thread*sa%e.
shareable object that represents a single data
so#rce
Provides access to a transactional &ntit$Manager
A ersistence&nit describes a gro#p o%
persistent classes
(e%ines providers
(e%ines transactional t$pes +local vs JTA-
M#ltiple /nits per application are allowed
5
Persistence !onte0t and
&ntit$Manager
6
The &ntit$Manager API
!reate a JP"1 2#er$
flush()
persist(Object o)
Adds the entit$ to the Persistence
!onte0t3
SQL: insert into table
remove(Object o)
Re'oves the entit$ %ro' the Persistence
!onte0t3
SQL: delete from table
find(Class entity, Object primaryKey)
4ind b$ pri'ar$ )e$3
SQL: select * from table where id = ?
Query createQuery(String jpqlString)
4orce entit$ state to be written to
database i''ediatel$
lus other methods !!!
7
JPA Providers