Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
r
u
o
S
g Spring
y e
l
Welcome toin
Core
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
A 4-day bootcamp
that
trains iyou
how to use the
i
c
i
ato createt Dwell-designed, testable
f
Spring fFramework
r
Tbusinessoapplications
O
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S nprofessionals
Access to SpringSource
g trib
l
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Learn to use Spring for web and other
applications
Gain hands-on experience
50/50 presentation and labs
Logistics
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
Other questions?
o
D
Participants list
Working hours
Lunch
Toilets
Fire alarms
Emergency exits
Internet access
e
c
r
u
Agenda
o
SpringSource, a division ofS
VMware
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
4
e
c
r
Introduction to Spring
u
o
Using Spring to configure an
application
S
g
y e
l
Simplifying XML-basediconfiguration
n
n
r
t
O
Annotation-based dependency
injection
p
u
S ninjection
g trib
Java-based dependency
l
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
5
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
e
c
r
u
Agenda
o
SpringSource, a divisionS
of VMware
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
9
SpringSource, a division of
VMware
e
c
r
u
o
acquired by VMware in Oct 2009
S
g
y
Spring projects key to VMware's
cloud
strategy
l
n
i
e
n
r
t
Virtualize your Java Apps
O
p
u
S ng rib
l
t
i
a
i
s
n
i
Deploy to c
private, public,
hybrid
clouds
i
i
a tD
f
r
f
T o
O
N
o
D
10
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
b
S Spring
g
i
l
r
n
t
i
a
i
Framework
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Spring MVC
Spring
Dynamic
Modules
Spring
WebFlow
Spring ROO
Spring Web
Services
Spring
Security
Spring
Integration
Spring Batch
Spring Data
Spring Social
Spring
Android
And many
more...
11
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Spring Data
Spring
Insight
Spring
AMQP
Spring
Gemfire
e
c
r
VMware develops 95% of the code of
the Spring framework
u
o
Also leaders on the other Spring
projects
(Batch, Security,
S
g
Web Flow...)
y
l
n
i
e
n
Tomcat
r
t
O
p
u
60% of code commits
in
the
past
2
years
b
S
g
i
l
r
n
80% of bug fixes
t
i
a
i
s
n
i
i
c
Apache httpd
i
a
D
f
r
f
t
Hyperic
T
O
o
N
Groovy/Grails
o
Rabbit MQ
D
Spring technologies
...
13
e
c
r
u
Agenda
o
SpringSource, a division ofS
VMware
g
y
l
n
i
e
n
r
t
O
p
u
Let's getSon with g
the course..!
b
i
l
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
14
e
c
r
u
o
S
Overview of the
Spring
g
y
l
n
i
e
n
r
t
Framework
O
p
u
S ng rib
l
t
i
a
i
Introducing Spring in
the context
of enterprise
s
n
i
i
c
i
application
architecture
a
D
f
r
f
t
T
O
o
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
Goal of the Spring Framework u
o
Springs role in enterprise S
application
g
y
l
architecture
n
i
e
n
r
t
Core support
O
p
u
b
Web application S
development
support
g
i
l
n str support
i
a
Enterprise iapplication
development
n
i
i
c
i
Spring Framework
history
a
D
f
r
f
t
T
O
o
N
o
D
2
e
c
r
u
Provide comprehensive infrastructural
support
o
for developing enterprise Java
applications
S
g
y
Spring deals with the plumbing
l
n
i the ndomain problem
e
r
t
So you can focus on solving
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
3
e
c
r
u
Core support
o
Application Configuration
S
y
Enterprise Integration ng
l
i
e
n
r
t
Testing
O
p
u
Data Access
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
4
Application Configuration
e
c
r
u
A typical application system consists
of several
o
parts working together to carry
out a use case
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Component A
Component B
Component C
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
TransferService
transfer(
300.00,
1, 2)
e
c
AccountRepository
loadAccount(1);
a1
loadAccount(2);
a2
new
new
Account 1
Account 2
debit(300.00)
credit(300.00)
updateAccount(a1);
confirmation
updateAccount(a2);
Springs Configuration
Support
e
c
r
u
Spring provides support for assembling
such an
o
application system from itsS
parts
g each
y
Parts do not worry aboutnfinding
other
l
i
e
n
t
Any part can easily berswapped out
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
7
e
c
r
u
o
S
Part 2
g
y
l
n
i
e
n
r
t
O
Assembly
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
Part 1
a
D
f
r
f
t
T
O(1) new JdbcAccountRepository();
o
N
(2) new TransferServiceImpl();
o
(3) service.setAccountRepository(repository);
D
Spring
TransferServiceImpl
JdbcAccountRepository
e
c
r
u
public class JdbcAccountRepository implements
o
AccountRepository {
Part 1
S
g
Implements a service
interface
y
l
}
n
i
e
n
r
t
O
p
u
b
S implements
g
public class TransferServiceImpl
TransferService
{
i
l
r
n
t
private AccountRepository
accountRepository;
i
a
i
s
n
i
i
c
fi ra t D
public void f
setAccountRepository(AccountRepository
ar) {
Part 2
T
accountRepository
= ar;
O
o
}
N
o
on service interface;
}
D Depends
conceals complexity of implementation;
allows for swapping out implementation
9
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Spring
TransferServiceImpl
JdbcAccountRepository
StubAccountRepository
JpaAccountRepository
For Jdbc
Jpa
For For
Unit
Testing
(1)new
new StubAccountRepository();
JdbcAccountRepository();
(1)
JpaAccountRepository();
(2)new
newTransferServiceImpl();
TransferServiceImpl();
(2)
(3)service.setAccountRepository(repository);
service.setAccountRepository(repository);
(3)
10
Enterprise Integration
e
c
r
u
Enterprise applications do not work
in isolation
o
S
They require enterprise services
and resources
g
y
l
Database Transactions n
i
e
n
r
t
Security
O
p
u
S ng rib
Messaging
l
t
i
a
Remote Access
i
s
n
i
i
c
Caching
i
a tD
f
r
f
T o
O
N
o
D
11
e
c
r
u
Spring helps you integrate powerful
enterprise
o
services into your application
S
g
y
While keeping your application
code
simple and
l
n
i
e
n
testable
r
t
O
p
u
Plugs into all Java
EE application
servers
b
S
g
i
l
r
n
While capable
of standalone
usage
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
12
Testing
e
c
r
Automated testing is essential u
o
S
Spring enables unit testability
g
y
l
Decouples objects from their
environment
n
i
e
n
r
t
Making it easier to test
each piece
of your
application
O
p
u
in isolation
S ng rib
l
t
i
a
Spring provides
system
testing
support
i
s
n
i
i
c
i
Helps you
test
all
the
pieces
together
a tD
f
r
f
T o
O
N
o
D
13
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
14
Accessing Data
e
c
r
u
Most enterprise applications access
data stored
o
in a relational database
S
g
y
To carry out business functions
l
n
i
e
n
r
t
To enforce business rules
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
15
e
c
r
u
Spring makes data access easier
to do
o
effectively
S
g
y
Manages resources for you
l
n
i
e
n
t
Provides API helpers r
O
p
u
Supports all major
data access
technologies
b
S
g
i
l
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
JDBC
Hibernate
JPA (versions 1 and 2)
MyBatis (iBATIS)
...
16
e
c
r
u
Web application development support
o
Struts integration
S
g
y
JSF Integration
l
n
i
e
n
r
t
Spring MVC and Web Flow
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
17
e
c
r
u
Enterprise application development
support
o
Developing web services
S
y
Adding manageability ng
l
i
e
n
r
t
Integrating messaging infrastructures
O
p
u
Securing servicesS
and providing
object
access control
b
g
i
l
r
n
Tasks and Job
Scheduling
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Spring Batch (not this course)
18
e
c
r
u
o
S
g
y 3.0.7)
l
Spring 3.0 (released Decin
2009, currently
e
n
r
t
O
p
u
S ng rib
l
t
i
Spring 2.5 (released
Nov
2007, currently
2.5.6)
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
e
c
r
u
o
S
g
y
l
LAB
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Developing an Application
from
Plain Java
s
n
i
i
c
i
ObjectsD
a
f
r
f
t
T
O
o
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
o
S y
DependencygInjection
l
n
i
e
n
using
XML
r
t
O
p
u
S ng rib
l
t
i
a
i
Introducing the Spring
Application
Context and
s
n
i
i
c
i
Springs
XML-based
configuration
language
a
D
f
r
f
t
T
O
o
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibit
e
c
r
u
Spring quick start
o
S
Writing bean definitions
g
y
l
n
Creating an application
context
i
e
n
r
t
O
p
u
Bean scope and FactoryBean
elements
b
S
g
i
l
r
Lab
n
t
i
a
i
s
i
Advancedic
Topics in
a tD
f
r
f
T o
O
N
o
D
2
e
c
r
Your Application Classes u
(POJOs)
o
S
g
y
l
n
i
e
n
r
t
Spring
Configuration
O
p
u
ApplicationContext
S ng rib
Instructions
l
t
i
a
i
s
n
i
i
c
i
Creates
a
D
f
r
f
t
T
O
o
N
Fully
configured
application system
o
D Ready for use
3
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
public class JdbcAccountRepository
implements AccountRepository {
i
a
D
f
r
f
public JdbcAccountRepository(DataSource
ds) {
t
O = Tds; No
this.dataSource
}
o
D
}
between accounts
}
Configuration Instructions
<beans>
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
e
c
r
u
// Create the application from the configuration
o
S
ApplicationContext context =
g
y
new ClassPathXmlApplicationContext(application-config.xml);
l
n
i
e
n
r
t
O
p
// Look up the application service
interface
u
b
g
TransferService service = S
i
l
r
n
t
(TransferService) context.getBean(transferService);
i
a
i
s
n
i
i
c
i
a tD
f
// Use the application
r
f
T o
service.transfer(new
1, 2);
O MonetaryAmount(300.00),
N
o
D
6
Accessing a bean
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Multiple ways
e
c
r
u
o
S
g
y
l
n
i Context n te
Application
r
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
transferService
TransferServiceImpl
accountRepository
JdbcAccountRepository
dataSource
OracleDataSource
e
c
r
u
o
All beans are fully initialized before
use
S
g
y
l
n
i in then right torder
e
Beans are always created
r
O
p
u
Based on their dependencies
S ng rib
l
t
i
a
i
s id
i
Each beanic
is boundin
to a unique
a t Dor role the bean
The idff
reflects r
the service
T o
O to clients
provides
Bean id should notN
contain implementation
o
details
D
e
c
r
u
Spring quick start
o
Writing bean definitionsS
g
y
l
n
Creating an application
context
i
e
n
r
t
O
p
u
Bean scope and FactoryBean
elements
b
S
g
i
l
r
Lab
n
t
i
a
i
s
i
Advancedic
Topics in
a tD
f
r
f
T o
O
N
o
D
10
Constructor Injection
configuration
e
c
r
u
One parameter
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
Multiple parameters
c
i
a tD
f
r
f
T o
O
N
o
D
Constructor Injection
under the hood
e
c
r
u
o
S
g
y
l
n
i
e
n
<bean id=repository class=com.acme.RepositoryImpl/>
r
t
O
p
u
S ng rib
Equivalent to:
l
t
i
a
i
RepositoryImpl repository = new
RepositoryImpl();
s
n
i
i
c
i
ServiceImpl service
= newa
ServiceImpl(repository);
D
f
r
f
t
T
ApplicationContext
O
o
service -> instanceN
of ServiceImpl
o
repository -> instance
of RepositoryImpl
D
<bean id=service class=com.acme.ServiceImpl>
<constructor-arg ref=repository/>
</bean>
12
Setter Injection
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
<bean id=repository class=com.acme.RepositoryImpl/>
S ng rib
l
t
i
a
i
s
n
i
Equivalent to:
i
c
i
a tD
f
f
RepositoryImpl
repositoryr= new RepositoryImpl();
T ServiceImpl();
Oservice = new
o
ServiceImpl
N
service.setRepository(repository);
o
DApplicationContext
<bean id=service class=com.acme.ServiceImpl>
<property name=repository ref=repository/>
</bean>
13
e
c
r
u
Spring supports both
o
S
You can mix and match
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
14
e
c
r
u
Enforce mandatory dependencies
o
S
Promote immutability
g
y
l
n
Assign dependenciesi to finaln
fields e
r
t
O
p
Concise for programmatic
u
usage
b
S
g
i
l
Creation and injectionn
in one line
of code
r
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
15
e
c
r
u
Allow optional dependencies and
defaults
o
S
Have descriptive names
g
y
l
n
Inherited automatically
i
e
n
r
t
O
u
Cyclic references p
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
16
General Recommendations
e
c
r
u
Follow standard Java design guidelines
o
Use constructors to set required
properties
S
g
Use setters for optional
or
thosely
with default
n
i
e
n
r
t
values
O
p
u
b
Sdesigned
Some classes are
for aiparticular
g
l
r
n
t
i
a
injection strategy
i
s
n
i
i
c
In thatficase go a
with it, do
not fight it
D
r
f
t
T
Be consistent
above
all
O
o
N
o
D
17
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
<bean id=required class=com.acme.RequiredImpl
/>
O
p
u
<bean id=optional class=com.acme.OptionalImpl
/>
b
S
g
i
l
r
n
t
i
a
i
s
n
i
i
c
i
a tD
Equivalent
to:
f
r
f
T= new RequiredImpl();
RequiredImpl
required
O
o
OptionalImpl optional = newN
OptionalImpl();
ServiceImpl service = new
ServiceImpl(required);
o
service.setOptional(optional);
D
<bean id=service class=com.acme.ServiceImpl>
<constructor-arg ref=required />
<property name=optional ref=optional />
</bean>
18
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
Equivalent to: a
t
i
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
ApplicationContext
o
D
19
e
c
r
u
o
S
g
y
public class ServiceImpl {
l
n
e
n
public void setIntProperty(intri)i{ ... }
t
O
p
u
// ...
S ng rib
}
l
t
i
a
i
s
Equivalent to:
n
i
i
c
aServiceImpl();
D
fi = new
ServiceImpl f
service
r
t
int value O
= 29;
T
o
service.setIntProperty(value);
N
o
ApplicationContext
D
service -> instance of ServiceImpl
<bean id=service class=com.acme.ServiceImpl>
<property name=intProperty value=29 />
</bean>
20
e
c
r
u
Spring quick start
o
S
Writing bean definitions
g
y
l
n
Creating an application
context
i
e
n
r
t
O
p
u
Bean scope and FactoryBean
elements
b
S
g
i
l
r
Lab
n
t
i
a
i
s
i
Advancedic
Topics in
a tD
f
r
f
T o
O
N
o
D
21
e
c
r
Spring application contexts canube
o
bootstrapped in any environment,
including
S
g
y
JUnit system test
l
n
i
e
n
r
t
Web application
O
p
u
Standalone application
S ng rib
l
t
i
Loadable with
bean definitions
from files
a
i
s
n
i
i
c
In the f
class
path a
i
D
r
f
On the local file
system t
T
O
o
At an environment-relative
N resource path
o
D
22
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
e
c
r
u
A context can be configured from
multiple files
o
Can partition bean definitionsS
into logical groups
g
y
l
Best practice: separate
out
application
beans
n
i
e
n
r
t
from infrastructure
beans
O
p
u
b
S changes
Infrastructure often
between
environments
g
i
l
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Service beans
Repository beans
Datasource
Service beans
Repository beans
Datasource
application
infrastructure
24
Mixed Configuration
<beans>
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Partitioning Configuration
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a substitutable
D
f
Now
for other environments
r
f
t
T o
O
N
o
D
<beans>
<bean id=transferService class=com.acme.TransferServiceImpl>
<constructor-arg ref=accountRepository />
</bean>
<beans>
<bean id=dataSource class=org.apache.commons.dbcp.BasicDataSource>
<property name=driverClassName value=org.postgresql.Driver />
<property name=URL value=jdbc:postgresql://localhost/transfer />
<property name=user value=transfer-app />
<property name=password value=secret45 />
</bean>
</beans>
test-infrastructure-config.xml
26
Bootstrapping in Each
Environment
e
c
r
u
// Create the application from the configuration
o
S
ApplicationContext context =
g
y
new ClassPathXmlApplicationContext(
l
n
i
e
n
application-config.xml, test-infrastructure-config.xml
);
r
t
O
p
u
S ng rib
In the production environment
l
t
i
a
i
s
// Create the application
fromin
the configuration
i
c
i
a= t D
f
ApplicationContext
context
r
f
new ClassPathXmlApplicationContext(
T
O
o
application-config.xml,N
prod-infrastructure-config.xml);
o
D
In the test environment
From Spring 3.1, Bean Profiles provide more options when working
with various environments (to be discussed later in this course)
27
e
c have
ApplicationContext implementations
r
default resource loading rulesou
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
new ClassPathXmlApplicationContext(com/acme/application-config.xml);
$CLASSPATH/com/acme/application-config.xml
new FileSystemXmlApplicationContext(C:\\etc\\application-config.xml);
// absolute path: C:\etc\application-config.xml
new FileSystemXmlApplicationContext(./application-config.xml);
// path relative to the JVM working directory
28
e
c
r
u
// Create the application from the configuration
o
ApplicationContext context =
S
g
y
new ClassPathXmlApplicationContext(
l
n
i
e
config/ -config.xml, config/
-config.xml,
n
r
t
O
file:oracle-infrastructure-config.xml
);
p
u
S ng rib
prefix
l
t
i
a
i
s
Various prefixes
n
i
i
c
i
a tD
f
classpath:
r
f
T o
O
file:
N
http:
o
D
Default rules can be overridden
dao
service
e
c
r
u
Spring quick start
o
S
Writing bean definitions
g
y
l
n
Creating an application
context
i
e
n
r
t
O
p
u
Bean scope and FactoryBean
elements
b
S
g
i
l
r
Lab
n
t
i
a
i
s
i
Advancedic
Topics in
a tD
f
r
f
T o
O
N
o
D
30
e
c
r
Default scope is singleton u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
service1 == service2
<bean id=accountService
class="com.acme.AccountServiceImpl">
</bean>
<bean id=accountService
Spring config
class="com.acme.AccountServiceImpl"
scope=singleton>
</bean>
Spring config
One single instance
AccountService service1 = (AccountService) context.getBean(accountService);
AccountService service2 = (AccountService) context.getBean(accountService);
31
e
c
r
u
scope="prototype"
o
S
New instance created every
time bean is
g
y
l
referenced
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
service1 != service2
Spring config
32
Available Scopes
e
c
r
u
singleton A single instance is o
used
S
g
y
A new instance
is created
each time
l
n
prototype
i
e
n
t
the bean is rreferenced
O
p
u
b
S
g
A newl instance
is created
once per
i
r
session
n
t
i
a
user
session
web
environment
i
s
n
i
i
c
i
a
D
f
A
new rinstance
is created once per
f
request
t
T - web
environment
O request
o
N
custom
o
You define
your own rules and a new
scope
D
scope name - advanced feature
name
33
e
c
r
How can Spring instantiate u
the following?
o
S
Classes with private constructors
(such as
g
y e
l
Singleton pattern) in
n
r
t
Objects from Factories
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
34
Implementing a FactoryBean
e
c
r
u
2 ways
o
S
XML declaration
g
y
l
Use factory-method attribute
n
i
e
n
r
t
No need to update
Java class
O
p
u
b
S ng interface
i
Implement FactoryBean
l
r
t
i
a
i
Spring can
auto-detect
that s
FactoryBean interface is
n
i
i
c
i
implemented
a tD
f
r
f
T
O
o
FactoryBean interface
is widely used within the
N
Spring framework
o
D
Bean is declared as a regular bean in xml config
35
e
c
r
u
Useful for existing Singletonso
or Factories
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Non-intrusive
service1 == service2
36
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
b
S
g
i
l
r
//...
n
t
i
a
i
s
n
i
i
c
i
a
D
f
r
f
//...
t
T
O
o
N
<bean id=accountService
o
D
class=com.acme.AccountServiceFactoryBean
/>
return accountService;
37
e
c
r
u
Beans implementing FactoryBean
are
o
auto-detected
S
g
y ebean id
Dependency injection iusing
the lfactory
n
n
r
t
causes getObject() to
be
invoked
transparently
O
p
u
b
S
g
i
l
r
n
<bean id=accountService
t
i
a
i
s
class=com.acme.AccountServiceFactoryBean/>
n
i
i
c
i
a
D
f
r
f
t
<bean id=customerService
class=com.acme.CustomerServiceImpl>
T
O
o
<property name=service ref=accountService
/>
N
</bean>
o
D
getObject() called
by Spring
automatically
38
EmbeddedDatabaseFactoryBean
e
c
r
u
Common example of a FactoryBean
o
Part of the Spring framework
S
g
y
l
Used to create an in-memory
database
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
FactoryBeans in Spring
e
c
r
EmbeddedDatabaseFactoryBean u
o
JndiObjectFactoryBean
S
g
y
One option for looking up
JNDI
objects
l
n
i
e
n
r
t
FactoryBeans for creating
remoting
proxies
O
p
u
b
S ng data raccess
FactoryBeans forl configuring
i
t
i
a
technologies ilike
JPA, Hibernate
or
MyBatis
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
40
Dependency Injection
Summary
e
c
r
u
Frees it from the burden of resolving
its
o
S
dependencies
g
y
l
n
Simplifies your code, improves
code reusability
i
e
n
r
t
O
p
u
Promotes programming
to
interfaces
b
S
g
i
l
r
n
Conceals implementation
details
of dependencies
t
i
a
i
s
n
i
i
c
Improvesfitestability
a tD
r
f
Teasily ostubbed out for unit testing
Dependencies
O
N control over object lifecycle
Allows for centralized
o
D for new possibilities
Opens the door
Your object is handed what it needs to work
41
e
c
r
u
o
S
g
y
l
LAB
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
Using
Spring
to
Configure
an
Application
i
c
i
a tD
f
r
f
T o
O
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibit
e
c
r
u
Spring quick start
o
S
Writing bean definitions
g
y
l
n
Creating an application
context
i
e
n
r
t
O
p
u
Bean scope and FactoryBean
elements
b
S
g
i
l
r
Lab
n
t
i
a
i
s
n
i
i
c
Advanced
Topics
i
a
D
f
r
f
t
Constructor
Args
T
O
o
N
o
D
43
e
c
r
Constructor args matched byu
type
o
<constructor-arg> elements
can be in any order
S
g
y
l
When ambiguous: indicate
order
with
index
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
class MailService {
public MailService(int maxEmails, String email) { }
44
e
c
r
Constructor args can have names
u
o
Since Spring 3.0 they can be
used for arg matching
S
g
y
l
BUT: need to compile with
debug-symbols
enabled
n
i
e
n
r
t
OR: Use @java.beans.ConstructorProperties
O
p
u
S ng rib
l
t
i
a
i
Specify
arg names in order
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
class MailService {
@ConstructorProperties( { maxEmails, email } )
public MailService(int maxEmails, String email) { }
45
e
c
r
u
o
XML Dependency
Injection
S
g
y
l
Advanced features
and
n
i
e
n
r
t
O
p
u
Best
Practices
S ng rib
l
t
i
a
i
Techniques for
Creatingis
Reusable and
n
i
c
i
Concise
Bean D
Definitions
a
f
r
f
t
T
O
o
N
o
D
1
e
c
r
u
Best Practices
o
Making the best use of XML
namespaces
S
g
y
l
n
i properties
n
Externalizing values into
files te
r
O
p
u
Working with a high
number
of
conf.
Files
S ng rib
l
t
i
a
i
s
n
Using Bean
definition
inheritance
i
i
c
i
a tD
f
r
f
Lab
T
O
o
Advanced FeaturesN
o
Inner beans, collections,
SpEL
D
Default namespace
e
c
r
u
o
commonly used as the defaultS
namespace in Spring
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
dozens of other namespaces are available!
Other namespaces
e
c
r
u
o
aop (Aspect Oriented Programming)
S
g
tx (transactions)
y
l
n
i
e
n
security
r
t
O
p
u
jms
b
S
g
i
l
r
mvc
n
t
i
a
i
s
n
i
i
c
i
aof actual
D
f
r
f
They allow
hiding
bean definitions
t
T bean files (see next slide)
O
Greatly reduce size of o
N
o
D
Power of Namespaces
e
c
r
u
o
Many advanced features of Spring
need to declare a
S
large number of beans
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
tx and aop namespaces will be discussed later
e
c
r
u
o
Use the dedicated STS wizard!S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
xsi:schemaLocation="..."
e
c
r
?
u
o
S
Common practice: do not use
a version number
g
y
l
Triggers use of most recent
schema
version
n
i
e
n
r
t
Easier migration
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
spring-beans-3.1.xsd
OR
spring-beans.xsd
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
After
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D introduced in Spring 3.1
c namespace was
Before
e
c
r
u
o
Use '-ref' suffix for referencesS
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<beans xmlns:c="http://www.springframework.org/schema/c"
xmlns:p="http://www.springframework.org/schema/p"
...>
No schemaLocation needed
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
10
e
c
r
u
o
More concise
S
g
y
Well supported in STS
l
n
i
e
n
r
t
O
p
u
Cons
S ng rib
l
Fairly new feature
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T thatothe usual XML configuration
Owidely known
Less
N
syntax
o
D
Pros
11
e
c
r
u
Best Practices
o
Making the best use of XML namespaces
S
g
y
l
n
i
e
n
Externalizing valuesr into properties
files
t
O
p
u
Working with a high
number
of
conf.
Files
S ng rib
l
t
i
a
i
s
n
Using Bean
definition
inheritance
i
i
c
i
a tD
f
r
f
Lab
T
O
o
Advanced FeaturesN
o
Inner beans, collections,
SpEL
D
12
Externalizing values to a
properties file (1)
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Namespace declaration
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd" ...>
<context:property-placeholder ... />
</beans>
Context namespace
13
Externalizing values to a
properties file (2)
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<beans ...>
<context:property-placeholder location="db-config.properties" />
<bean id="dataSource" class="com.oracle.jdbc.pool.OracleDataSource">
<property name="URL" value="${db.url}" />
<property name="user" value="${db.user.name}" />
</bean>
</beans>
db.url=jdbc:oracle:...
db.user.name=moneytransfer-app
db-config.properties
Resolved at
<bean id="dataSource"
startup time
class="com.oracle.jdbc.pool.OracleDataSource">
<property name="URL" value="jdbc:oracle:..." />
<property name="user" value="moneytransfer-app" />
</bean>
14
e
c
r
u
Best Practices
o
Making the best use of XML namespaces
S
g
y
l
n
i properties
n
Externalizing values into
files te
r
p g O bu Files
Working with aS
high number of conf.
i
l
r
n
t
i
a
i
s
n
Using Bean
definition
inheritance
i
i
c
i
a tD
f
r
f
Lab
T
O
o
Advanced FeaturesN
o
Inner beans, collections,
SpEL
D
15
e
c
r
u
o
S
g
y
ApplicationContext context =
l
n
i
e
n
new ClassPathXmlApplicationContext(
r
t
u
"config/ -config.xml",p
"config/ O -config.xml"
);
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T
O
o
2 main ways to improve
configuration
N
Importing configuration
files
o
D
Using wildcards
dao
service
16
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
b
S ng riapplication-config.xml
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
system-test-config.xml
o
D
<beans>
<import resource="accounts/account-config.xml" />
<import resource="restaurant/restaurant-config.xml" />
<import resource="rewards/rewards-config.xml" />
</beans>
<beans>
<import resource="application-config.xml"/>
<bean id="dataSource" class="example.TestDataSourceFactory" />
</beans>
new ClassPathXmlApplicationContext("system-test-config.xml");
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
This can be
overridden
using
prefixes
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<beans>
<import resource="account-config.xml" />
<import resource="rewards-config.xml" />
...
</beans>
In same folder/package
as the current file
<beans>
<import resource="classpath:com/springsource/account-config.xml" />
...
</beans>
Path starts from the
classpath root
18
Using wildcards
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
e
c
r
u
Best Practices
o
Making the best use of XML namespaces
S
g
y
l
n
i properties
n
Externalizing values into
files te
r
O
p
u
Working with a high
number
of
conf.
Files
S ng rib
l
t
i
a
i
s
n
Using Bean
definition
inheritance
i
i
c
i
a tD
f
r
f
Lab
T
O
o
Advanced FeaturesN
o
Inner beans, collections,
SpEL
D
20
e
c
r
Sometimes several beans needu
to be
o
configured in the same wayS
g
y
l
Use bean definition inheritance
to
define the
n
i
e
n
r
t
common configuration
onceO
p
u
S ng rib
Inherit it where needed
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
21
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<beans>
<bean id="pool-A" class="com.oracle.jdbc.pool.OracleDataSource">
<property name="URL" value="jdbc:oracle:thin:@server-a:1521:BANK" />
<property name="user" value="moneytransfer-app" />
</bean>
<bean id="pool-B" class="com.oracle.jdbc.pool.OracleDataSource">
<property name="URL" value="jdbc:oracle:thin:@server-b:1521:BANK" />
<property name="user" value="moneytransfer-app" />
</bean>
<bean id="pool-C" class="com.oracle.jdbc.pool.OracleDataSource">
<property name="URL" value="jdbc:oracle:thin:@server-c:1521:BANK" />
<property name="user" value="moneytransfer-app" />
</bean>
</beans>
Can you find the duplication?
22
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<beans>
<bean id="abstractPool"
class="com.oracle.jdbc.pool.OracleDataSource" abstract="true">
<property name="user" value="moneytransfer-app" />
</bean>
Will not be instantiated
<bean id="pool-A" parent="abstractPool">
<property name="URL" value="jdbc:oracle:thin:@server-a:1521:BANK" />
</bean>
<bean id="pool-B" parent="abstractPool">
<property name="URL" value="jdbc:oracle:thin:@server-b:1521:BANK" />
</bean>
<bean id="pool-C" parent="abstractPool">
<property name="URL" value="jdbc:oracle:thin:@server-c:1521:BANK" />
<property name="user" value="bank-app" />
Can override
</bean>
</beans>
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<bean id=
"rewardsRepo" />
<bean id=
"orderRepo" />
<bean id=
"rewardsService" />
<bean id=
"orderService" />
25
e
c
r
u
o
S
g
y
l
LAB
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
Using
Bean
definition
inheritance
i
c
i
a
D
f
f
and r
Property tPlaceholders
T o
O
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
Best Practices
o
Making the best use of XML namespaces
S
g lfiles
y
Externalizing values inton
properties
i
e
n
r
Working with a high number of conf.
Filest
O
p
u
Using Bean definition
inheritance
b
S
g
i
l
r
n
t
i
a
Lab
i
s
n
i
i
c
i
Advanced
Features
a tD
f
r
f
Inner
beansT
O
o
Nof dependencies
Injecting a collection
o
Spring Expression
Language
D
27
Inner beans
e
c
r
u
o
<bean id="restaurantRepository"
S
g
class="rewards.internal.restaurant.JdbcRestaurantRepository">
y
l
n
<property name="benefitAvailabilityPolicy">
i
e
n
r
t
<bean class="rewards...DefaultBenefitAvailabilityPolicy"
/>
O
p
u
</property>
b
S
g
i
l
r
n
</bean>
t
i
a
i
s
n
i
i
c
i
a
D
f
r
f
Cannot be accessed
from
the applicationContext
t
T
O
o
N
applicationContext.getBean(RestaurantRepository.class);
o
applicationContext.getBean(DefaultBenefitAvailabilityPolicy.class);
D
Inner bean only visible from surrounding bean
No bean id
OK
NoSuchBeanDefinitionException!!
28
e
c
r
u
o
<bean id="restaurantRepository"
S
g
class="rewards.internal.restaurant.JdbcRestaurantRepository">
y
l
n
<property name="dataSource"iref="dataSource"
/> e
n
r
t
<property name="benefitAvailabilityPolicyFactory"
ref="factory"
/>
O
p
u
</bean>
S ng rib
l
t
i
a
i
s
<bean id="factory"
n
i
i
c
i
class="rewards.internal.restaurant.availability.
a
D
f
r
f
t
DefaultBenefitAvailabilityPolicyFactory">
T
O
o
<constructor-arg ref="rewardHistoryService"
/>
N
</bean>
o
D
</beans>
<beans>
29
e
c
r
u
o
<bean id="restaurantRepository"
S
g
class="rewards.internal.restaurant.JdbcRestaurantRepository">
y
l
n
<property name="dataSource"iref="dataSource"
/> e
n
r
t
<property name="benefitAvailabilityPolicyFactory">
O
p
u
b
<bean class="rewards.internal.restaurant.availability.
S
g
i
l
r
n
DefaultBenefitAvailabilityPolicyFactory">
t
i
a
i
s
n
<constructor-arg
ref="rewardHistoryService"
/>
i
i
c
a
</bean> fi
D
r
f
t
</property>
T
O
o
</bean>
N has no id (it is anonymous)
Inner bean
o
Cannot
be referenced outside this scope
</beans>
D
<beans>
30
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<beans>
<bean id="restaurantRepository"
class="rewards.internal.restaurant.JdbcRestaurantRepository">
<property name="dataSource" ref="dataSource" />
<property name="benefitAvailabilityPolicyFactory">
<bean class="rewards.internal.restaurant.availability.
DefaultBenefitAvailabilityPolicyFactory">
<constructor-arg>
<bean class="rewards.internal.rewards.JdbcRewardHistory">
<property name="dataSource" ref="dataSource" />
</bean>
</constructor-arg>
</bean>
</property>
</bean>
</beans>
31
e
c
r
u
o
You only expose what needs to
be
exposed
S
g
y
Cons
l
n
i
e
n
r
t
Harder to read
O
p
u
S ng rib
General recommendation
l
t
i
a
Use them sparingly
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Pros
32
e
c
r
u
Best Practices
o
Making the best use of XML namespaces
S
g lfiles
y
Externalizing values inton
properties
i
e
n
r
Working with a high number of conf.
Filest
O
p
u
Using Bean definition
inheritance
b
S
g
i
l
r
n
t
i
a
Lab
i
s
n
i
i
c
i
Advanced
Features
a tD
f
r
f
Inner
beans T
O
o
N of dependencies
Injecting a collection
o
Spring Expression
Language
D
33
e
c
r
u
o
From the default beans namespace
S
g
y
Simple and easy
l
n
i
e
n
r
t
util collections
O
p
u
From the util namespace
S ng rib
l
t
i
a
i
s
n
i
i
c
More features
available
i
a tD
f
r
f
T o
O
N
o
Both offer support for
set, map, list and properties collections
D
beans collections
34
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
Equivalent
to:
f
r
f
T o
O
N
o
D ApplicationContext
e
c
r
u
o
eg. for java.util.List the implementation
is ArrayList
S
g
y
Collection has no bean id
l
n
i
e
n
r
t
Can't be accessed from the ApplicationContext
O
p
u
Only valid as inner
beans g
b
S
i
l
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Can't specify the collection type
OK
NoSuchBeanDefinitionException!!
36
e
c
r
u
Set
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
Map (through
map / entry / key elements)
i
a tD
f
r
f
T o
O
N
o
D
<property name="customerPolicies">
<set>
<ref bean="privateBankingCustomerPolicy"/>
<ref bean="retailBankingCustomerPolicy"/>
</set>
</property>
<property name="customerPolicies">
<map>
<entry key="001-pbcp" value-ref="privateBankingCustomerPolicy"/>
<entry key-ref="keyBean" value-ref="retailBankingCustomerPolicy"/>
</map>
</property>
Key can use primitive
type or ref to bean
37
e
c
r
u
o
S
g
y
Use when property values are
unlikely
to change
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<property name="properties">
<props>
<prop key="server.host">mailer</prop>
<prop key="server.port">1010</prop>
</props>
</property>
38
util collections
e
c
r
u
o
specifying collection implementation-type
and scope
S
g
y
declaring a collection as a top-level
bean
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
39
e
c
r
u
o
In most cases, the default beans
collections will
S
suffice
g
y
l
n
i features
n
Just remember the additional
ofte
collections
r
O
p
from the <util/> namespace
in case u
you would
S ng rib
need them
l
t
i
a
i
s
Declare accollectionin
as a top-level
bean
i
i
aimplementation-type
D
f
Specify
collection
r
f
t
T
O
o
N
o
D
40
e
c
r
u
Best Practices
o
Making the best use of XML namespaces
S
g lfiles
y
Externalizing values inton
properties
i
e
n
r
Working with a high number of conf.
Filest
O
p
u
Using Bean definition
inheritance
b
S
g
i
l
r
n
t
i
a
Lab
i
s
n
i
i
c
i
Advanced
Features
a tD
f
r
f
Inner
beans T
O
o
Nof dependencies
Injecting a collection
o
Spring Expression
Language
D
41
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D in Spring 3.0
SpEL was introduced
42
SpEL examples
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<bean class="com.acme.RewardsTestDatabase">
<property name="keyGenerator"
value="#{strategyBean.databaseKeyGenerator}" />
</bean>
Can refer a
nested property
43
SpEL
e
c
r
u
o
Named Spring beans
S
g
y
Implicit references
l
n
i
e
n
r
t
O
p
u
SpEL allows to create
custom
functions
and
b
S
g
i
l
r
n
references
t
i
a
i
s
n
i
Widely used
in
Spring
projects
i
c
i
a tD
f
r
f
T o
O
N
o
D
EL Attributes can be:
Spring
Spring
Spring
Spring
...
Security
WebFlow
Batch
Integration
44
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
In Spring Batchl
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
Spring Security will D
be discussed later in this course. Spring Batch is
In Spring Security
<security:intercept-url pattern="/accounts/**"
access="isAuthenticated() and hasIpAddress('192.168.1.0/24')" />
45
Summary
e
c
r
Spring offers many techniques u
to simplify
o
configuration
S
g
y
We've seen just a few here
l
n
i and elegance,
e
n
r
t
It's about expressiveness
just
like code
O
p
u
b
S discussed
Best practices we've
can
be used
g
i
l
r
n projects
t
i
daily in mostia
Spring XML
s
n
i
i
c
Imports,i Bean inheritance,
imports...
a
D
f
r
f
t
Advanced
features
are
more specialized
T
O
o
N
o
D
46
e
c
r
u
o
S
g
y
l
Annotations
in
Spring
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Annotations for n
Dependency
Injection and
s
i
i
c
i
interceptors
a
D
f
r
f
t
T
O
o
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
Fundamentals
o
Annotation-based Configuration
S
g
y
Best practices for component-scanning
l
n
i
e
r
t
XML versus annotations: when tonuse what?
O
p
u
Mixing XML and annotations
for Dependency
Injection
b
S
g
i
l
r
n
@PostConstruct
and @PreDestroy
t
i
a
i
s
n
i
i
c
Stereotypes
and
meta
annotations
i
a
D
f
r
f
Lab O
T ot
Advanced featuresN
o
Standard annotations
(JSR 330)
D
2
XML/Annotation DI
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
Annotation-based Configuration
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
XML-based dependency injection
@Component
public class TransferServiceImpl implements TransferService {
@Autowired
public TransferServiceImpl(AccountRepository repo) {
this.accountRepository = repo;
Annotations embedded
}
with POJOs
}
<context:component-scan base-package=com.springsource/>
Minimal xml config
3
Usage of @Autowired:
many ways
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
method-injection
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
field-injection
o
D
constructor-injection
@Autowired
public TransferServiceImpl(AccountRepository a) {
this.accountRepository = a;
}
@Autowired
public void setAccountRepository(AccountRepository a) {
this.accountRepository = a;
}
@Autowired
private AccountRepository accountRepository;
One constructor
must be
autowired
Usually not
recommended
to create a
getter method
@Autowired dependencies:
required or not?
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
b
S
g
i
l
r
n
Use required attribute
to override
default
behavior
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Autowired
public void setAccountRepository(AccountRepository a) {
this.accountRepository = a;
}
@Autowired(required=false)
public void setAccountRepository(AccountRepository a) {
this.accountRepository = a;
}
Exception if no
dependency found
Only inject if
dependency exists
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Component
public class TransferServiceImpl implements TransferService {
@Autowired
public TransferServiceImpl(
AccountRepository accountRepository)
{}
@Component
public class JdbcAccountRepository implements AccountRepository {..}
Which one should get injected?
@Component
public class HibernateAccountRepository implements AccountRepository {..}
At startup: NoSuchBeanDefinitionException, no unique bean of type
[AccountRepository] is defined: expected single bean but found 2...
6
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Component("transferService")
public class TransferServiceImpl implements TransferService {
@Autowired
public TransferServiceImpl( @Qualifier("jdbcAccountRepository")
AccountRepository accountRepository) { }
qualifier
@Component("jdbcAccountRepository")
public class JdbcAccountRepository implements AccountRepository {..}
@Component("hibernateAccountRepository")
public class HibernateAccountRepository implements AccountRepository {..}
@Qualifier can also be used with method injection and field injection
Component names should not show implementation details unless there
are 2 implementations of the same interface (as it is the case here)
7
Component names
e
c
r
u
o
Names are auto-generated S
g
y
l
n
i
e
n
r
t
O
p
u
Recommendation: never
rely on
generated
names!
b
S
g
i
l
r
When specified
n
t
i
a
i
s
n
i
Allow disambiguation
when 2 bean
classes implement
i
c
i
a tD
f interface
the same
r
f
T o
O
N
o
D
When not specified
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
e
c
@Value("#{limits.max}")
public void setMaxTransfers(int max) ...
annotations
<bean
id="transferService"
scope="prototype"
lazy-init="false"
class="TransferServiceImpl">
<property id="accountRepo"
ref="accountRepository"/>
<property id="maxTransfers"
ref="#{limits.max}"/>
</bean>
xml
e
c
r
u
Fundamentals
o
Annotation-based Configuration
S
g
y
Best practices for component-scanning
l
n
i
e
r
t
XML versus annotations: when tonuse what?
O
p
u
Mixing XML and annotations
for Dependency
Injection
b
S
g
i
l
r
n
@PostConstruct
and @PreDestroy
t
i
a
i
s
n
i
i
c
Stereotypes
and
meta
annotations
i
a
D
f
r
f
Lab O
T ot
Advanced featuresN
o
Standard annotations
(JSR 330)
D
10
Component scanning
e
c
r
u
o
Jar dependencies also scanned!
S
g
Could result in slower startup
time ifly
too many files
n
i
e
n
scanned
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
apractices?
D
f
r
f
What are
the best
t
T
O
o
N
o
D
Components are scanned at startup
11
Best practices
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
Still bad:
O
p
u
S ng rib
l
t
i
a
OK:
i
s
n
i
i
c
i
a tD
f
r
f
T
O
o
Optimized:
N
o
D
Really bad:
<context:component-scan base-package=org,com/>
<context:component-scan base-package=com/>
<context:component-scan base-package=com.acme.app/>
<context:component-scan
base-package=com.acme.app.repository,
com.acme.app.service, com.acme.app.controller/>
12
e
c
r
u
Using filters, possibility to include
or exclude
o
beans
S
g
y
Based on type
l
n
i
e
n
r
t
Based on class-level annotation
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<context:component-scan base-package="com.acme.app">
</context:component-scan>
13
e
c
r
u
Fundamentals
o
Annotation-based Configuration
S
g
y
Best practices for component-scanning
l
n
i
e
n
r
XML versus annotations: when
to usetwhat?
O
p
u
Mixing XML and annotations
for Dependency
Injection
b
S
g
i
l
r
n
@PostConstruct
and @PreDestroy
t
i
a
i
s
n
i
i
c
Stereotypes
and
meta
annotations
i
a
D
f
r
f
Lab O
T ot
Advanced featuresN
o
Standard annotations
(JSR 330)
D
14
e
c
r
XML
u
o
For infrastructure and moreS
'static' beans
g
y
l
Pros:
n
i
e
n
r
t
Is centralized in onep
(or a few)O
places u
b
S ngformat for
Most familiar configuration
most people
i
l
r
t
i
Can be usedia
for all classes
(nots
just
your own)
n
i
i
c
i
Cons: ff
a tD
r
T don'tolike XML!
Some
O people just
N
o
More verbose than
annotations
D
But the STS bean-file editor makes it a lot easier
15
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
Single place to edit (just
the class)
O
p
u
b
S development
Allows for very rapid
g
i
l
r
n
t
i
a
Cons:
i
s
n
i
i
c
i
Configuration
spread
acrossD
your code base
a
f
r
f
t
T
O
o
Only works for yourN
own code
o
Merges configuration
and code (bad sep. of concerns)
D
Annotations
Nice for frequently changing beans
Pros:
Harder to debug/maintain
16
e
c
r
u
Fundamentals
o
Annotation-based Configuration
S
g
y
Best practices for component-scanning
l
n
i
e
r
t
XML versus annotations: when tonuse what?
O
p
u
Mixing XML andS
annotations
for Dependency
b
g
i
l
r
Injection a
n
t
i
i
s
n
i
@PostConstruct
and
@PreDestroy
i
c
i
a tD
f
Stereotypes
andr meta annotations
f
T
O
o
Lab
N
o
Advanced features
D
Standard annotations (JSR 330)
17
e
c
r
u
o
S
y
Use annotations for Spring g
MVC beans
and use XML for
l
n
i
e
n
Service and Repositoryrbeans
t
O
p
Use annotations when
possible,
but still u
use XML for
b
S
g tri
legacy code that
can't benchanged
l
i
a
i
Use @Autowired
annotations
without
component
s
n
i
i
c
i
scanning
a tD
f
r
f
T o
O
N
o
D
18
e
c
r
u
o
Processes all DI annotations S
g
y
Does not perform component-scanning
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Use of <context:annotation-config/>
<beans ...>
<context:annotation-config/>
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
With Qualifier
i
c
i
a tD
f
r
f
T o
O
N
o
D
{}
20
e
c
r
u
Fundamentals
o
Annotation-based Configuration
S
g
y
Best practices for component-scanning
l
n
i
e
r
t
XML versus annotations: when tonuse what?
O
p
u
Mixing XML and annotations
for Dependency
Injection
b
S
g
i
l
r
n
@PostConstruct
and i@PreDestroy
t
a
i
s
n
i
i
c
Stereotypes
and
meta
annotations
i
a
D
f
r
f
Lab O
T ot
Advanced featuresN
o
Standard annotations
(JSR 330)
D
21
Introduction to @PostConstruct
and @PreDestroy
e
c
r
u
o
S
g
y
public class JdbcAccountRepository
{
l
n
i
e
n
@PostConstruct
r
t
O
p
u
void populateCache()
{
}
S ng rib
l
t
i
a
i
s
@PreDestroy
n
i
i
c
i
D
f
void clearCache()
{r}a
f
t
T
} O
o
N
}
o
D
@PostConstruct and
@PreDestroy configuration
e
c
r
u
Not needed if <component-scano
/> already enabled
S
g
y
l
public class JdbcAccountRepository
{
n
i
e
n
r
t
@PostConstruct void populateCache()
{ }
O
p
u
@PreDestroy void clearCache()
{
}
b
S
g
i
l
r
n
}
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
<beans>
T o
O
<bean id=accountRepository
N
class=app.impl.JdbcAccountRepository
/>
o
<context:annotation-config/>
D
</beans>
<context:annotation-config />
JSR-250 annotations
EJB3 also uses them
Enables processing of
@PostConstruct and @PreDestroy
23
@PostConstruct
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
Constructor D
@PostConstruct
public void populateCache()
{ Connection conn = dataSource.getConnection(); //... }
}
called
Setter(s) called
@PostConstruct
method(s) called
24
@PreDestroy
e
c
r
u
o
Useful for releasing resources S
and 'cleaning up'
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
}
25
e
c
r
u
init-method and destroy-method
attributes
o
The way to go for third-partyS
beans
g
message brokers, data
sources l
y
n
i if you nprefer XMLteover
r
Use them for other beans
O
p
u
annotations
S ng rib
l
t
i
a
<bean id=accountRepository
i
s
n
i
i
c
i
class=app.impl.JdbcAccountRespository
a
D
f
r
f
t
init-method=populateCache
T
O
o
destroy-method=clearCache>
N
o
D
</bean>
26
e
c
r
u
Fundamentals
o
Annotation-based Configuration
S
g
y
Best practices for component-scanning
l
n
i
e
r
t
XML versus annotations: when tonuse what?
O
p
u
Mixing XML and annotations
for Dependency
Injection
b
S
g
i
l
r
n
@PostConstruct
and @PreDestroy
t
i
a
i
s
n
i
i
c
Stereotypes
and
meta
annotations
i
a
D
f
r
f
Lab O
T ot
Advanced featuresN
o
Standard annotations
(JSR 330)
D
27
Stereotype annotations
e
c
r
u
o
S
g
So-called stereotype annotations
y
l
n
i
e
n
r
t
Example:
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<context:component-scan
base-package=app.impl/>
scans
@Service("transferService")
public class TransferServiceImpl
implements TransferService {...}
Declaration of the
@Service annotation
@Target({ElementType.TYPE})
...
@Component
public @interface Service {...}
28
Stereotype annotations
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Component
@Service
@Configuration
Service classes
Java Configuration
@Repository
@Controller
Meta-annotations
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
recognizes
@MyTransactionalService
public class TransferServiceImpl
implements TransferService {...}
Custom annotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Service
@Transactional(timeout=60)
public @interface
MyTransactionalService {
String value() default "";
}
30
e
c
r
u
o
S
g
y
l
LAB
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Using Spring
Annotations
s
n
i
i
c
i
a andttestD an application
f
to configure
r
f
T o
O
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
Fundamentals
o
Annotation-based Configuration
S
g
y
Best practices for component-scanning
l
n
i
e
r
t
XML versus annotations: when tonuse what?
O
p
u
Mixing XML and annotations
for Dependency
Injection
b
S
g
i
l
r
n
@PostConstruct
and @PreDestroy
t
i
a
i
s
n
i
i
c
Stereotypes
and
meta
annotations
i
a
D
f
r
f
Lab O
T ot
N
Advanced features
o
Standard annotations
(JSR 330)
D
32
JSR 330
e
c
r
Java Specification Request 330u
o
Also known as @Inject
S
g
y
Joint JCP effort by Google
and
SpringSource
l
n
i
e
n
r
t
Standardizes internal DI annotations
O
p
u
Published late 2009
S ng rib
l
t
i
a
i
s
n
i
i
c
Subset ofifunctionality
compared to Spring's
a
D
f
r
f
@Autowired support
t
T
O
o
@Inject has 80% ofN
what you need
Rely on @Autowired
for the rest
o
D
Spring is a valid JSR-330 implementation
33
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<context:component-scan base-package=app.impl/>
import javax.inject.Inject;
import javax.inject.Named;
@Named
public class TransferServiceImpl implements TransferService {
@Inject
public TransferServiceImpl( @Named("accountRepository")
AccountRepository accountRepository) { }
}
import javax.inject.Named;
@Named("accountRepository")
public class JdbcAccountRepository implements
AccountRepository {..}
34
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
JSR 330
Comments
@Autowired
@Inject
@Component
@Named
@Scope
@Scope
@Scope
(singleton)
@Singleton
@Qualifer
@Named
@Value
@Required
@Lazy
No equivalent
SpEL specific
Redundant
No equivalent
35
Summary
e
c
r
u
Springs configuration directives
can be written
o
in XML, using Java or usingSannotations
g
y
l
You can mix and match
XML,
Java
and
n
i
e
n
r
t
annotations as youp
please O
u
b
S ng allows
Autowiring withl @Component
for almost
i
r
t
i
a
empty XML configuration
files
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
36
e
c
r
u
o
S y
DependencygInjection
l
n
i
e
n
using JavaprConfiguration
t
O
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Introduction
e
c
r
u
o
After XML and Annotations
S
g
y
Was introduced in Spring
3.0
l
n
i
e
n
r
t
External configuration
as with
XML u
O
p
b
g
Uses Java syntax S
instead of
XML
i
l
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Configuration Comparison
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<beans>
bean id
<bean id=transferService
@Bean
class=com.acme.TransferServiceImpl>
public TransferService transferService()
<property name=repository
{
ref=accountRepository />
TransferService service
= new TransferServiceImpl();
</bean>
service.setRepository(repository());
return service;
Dependency injection
}
bean id <bean id=accountRepository
class=com.acme.JdbcAccountRepository>
@Bean(accountRepository)
...
public AccountRepository repository()
</bean>
{ //... }
}
</beans>
@Configuration Syntax
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Configuration
public class ApplicationConfig {
Configuration class
Bean definition
@Bean
public TransferService transferService() {
TransferService service = new TransferServiceImpl();
service.setRepository(repository());
return service;
}
@Bean @Scope("prototype")
public AccountRepository repository() {
//...
}
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Configuration
public class InfraConfig {
@Bean
public DataSource dataSource() {
...
}
}
@Configuration
public class AppConfig {
@Bean
public TransferService transferService() {
...
}
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Configuration
//component-scanned
public class ApplicationConfig {
@Bean
public TransferService transferService() { }
Java configuration
7
Quiz
e
c is the best
Which
r
u
implementation?
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Bean
public AccountRepository accountRepository()
{ return new JdbcAccountRepository(); }
@Bean
public TransferService transferService1() {
TransferServiceImpl service = new TransferServiceImpl();
service.setAccountRepository(accountRepository());
return service;
}
Method call
@Bean
New instance
public TransferService transferService2() {
return new TransferServiceImpl( new JdbcAccountRepository() );
}
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Bean
public AccountRepository accountRepository() {
return new JdbcAccountRepository(); }
@Bean
public TransferService transferService() {
TransferServiceImpl service = new TransferServiceImpl();
service.setAccountRepository(accountRepository());
return service;
}
@Bean
public AccountService accountService() {
return new TransferServiceImpl( accountRepository() );
}
Singleton??
Method
called twice
HOW IS IT POSSIBLE?
Inheritance-based Proxies
e
c
r
u
For each bean, an instance is cached
in the child class
o
Child class only calls super g
at S
first instantiation
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Configuration
public class AppConfig {
@Bean
public AccountRespository accountRepository() { ... }
@Bean
public TransferService transferService() { ... }
}
10
Inheritance-based Proxies
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Java Configuration uses cglib for inheritance-based proxies
11
Equivalent to namespaces
e
c
r
u
o
S
y
Component-scanning, AOP,g
transactions
...
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Configuration
@ComponentScan("com.acme")
<aop:aspectj-autoproxy />
@EnableAspectJAutoProxy
<tx:annotation-driven />
@EnableTransactionManagement
public class AppConfig {
}
</beans>
e
c
r
u
o
Can use XML dependencies in S
@Configuration
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Dependency Injection
@Autowired
private DataSource datasource;
@Bean
public AccountRepository accountRepository() {
AccountRepositoryImpl repository = new AccountRepositoryImpl();
repository.setDataSource(this.datasource);
Scanner loads
return service;
@Config. bean
}
<context:component-scan base-package=com.acme.app/>
<bean id=dataSource class=.../>
Declaration
13
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Declaration
@Configuration
Load XML config
@ImportResource(classpath:system-config.xml)
@ComponentScan(com.acme.app)
Run scanner Spring 3.1+
public class AppConfig {
@Autowired
private DataSource datasource;
Dependency Injection
@Bean
public AccountRepository accountRepository() { //... as previous slide }
14
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
15
e
c
r
u
o
Annotations and XML are more
common
S
g
y
In some advanced situations,
Java
Configuration
l
n
i
e
n
r
t
is the way to go
O
p
u
Let's discuss is with
some practical
examples
b
S
g
i
l
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
16
Case 1
e
c to a
Inject appropriate dependency according
r
u
specific algorithm
o
eg. injecting a local or remoteS
dependency
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
In that case you canD
mix and match:
- Use XML or annotations for most of the application's configuration
@Bean public TransferService transferService() {
boolean isRemote=...;
if (isRemote) {
clientService.setRepository(remoteRepository());
} else {
clientService.setRepository(localRepository());
}
return service;
}
- Only use Java Configuration for the bean definitions that require
such an algorithm
17
e
c
I do not want to mix code and configuration
r
u
Therefore using annotations is not
an option
o
S
I am considering using XML
config.
However I
g
y
l
n
do not have access to Spring
tooling
i
e
n
r
t
O
Eg: I use Eclipse butp
STS/Spring
IDE hasn't
been
u
S ng rib
installed/approved
l
t
i
a
i
In that case, Java Configuration
is a good choice
s
n
i
i
c
i
a aret D
@Configuration
classes
compiled thus validated
f
r
f
Talways oworks in Java-classes
Auto-complete
O
Refactoring friendly N
in all modern IDEs
o
D
18
Summary
e
c
r
u
Java Configuration is less frequently
used than
o
XML and annotations
S
g
y
l
Extremely helpful in some
specific
situations
n
i
e
n
r
t
Equivalents to XMLpnamespaces
areuavailable
O
S ng rib
as of Spring 3.1
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
19
e
c
r
u
o
S
Understanding
the yBean
g
l
n
i
e
n
Lifecycle
r
t
O
p
u
S ng rib
l
t
i
a
i
An In-depth Look
at Springs
Lifecycle
s
n
i
i
c
i
Management
Features
a
D
f
r
f
t
T
O
o
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
Introduction
o
S
The initialization phase
g
y
l
n
The use phase
i
e
n
r
t
O
p
u
The destruction phase
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
2
r
u
Initialization
Use So
Destruction
g
y
l
n
i
e
n
r
t
O
p
Prepares for use
Used
by clients
u
Shuts down
b
S
g
i
Application
Application
l
Application
r
n
t
i
a
services
services
services
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
Application is not
usable until this D 99.99% of the
time is spent in
Are created
Configured
May allocate
system resources
e
c
phase is complete
Process client
requests
Carry out
application
behaviors
Release any
system resources
Are eligible for
garbage
collection
this phase
e
c
r
u
This lifecycle applies to any class
of application
o
Standalone Java application S
g
y
JUnit System Test
l
n
i
e
t
Java EE (web or fullrprofile) n
O
p
u
b
S ngapplication
Spring fits in to manage
lifecycle
i
l
r
t
i
a
Plays an important
role in all phases
i
s
n
i
i
c
Lifecycle
is the same
in all D
these configurations
i
a
f
r
f
t
Lifecycle
is
the
same
for
all 3 dependency
T
O
o
N
injection styles
o
XML, annotations
and Java Configuration
D
Initialization
Use
Destruction
4
e
c
r
u
Introduction
o
The initialization phase S
g
y
l
n
The use phase
i
e
n
r
t
O
p
u
The destruction phase
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
Use
Initialization
Destruction
o
D
5
e
c
r
u
When a context is created the initialization
o
phase completes
S
g
y
l
n
iconfiguration
// Create the application from the
e
n
r
t
ApplicationContext context =pnew ClassPathXmlApplicationContext(
O
u
S ng rib
application-config.xml,
l
test-infrastructure-config.xml
t
i
a
i
s
n
);
i
i
c
i
a tD
f
r
f
T
O
o
But what exactly happens
N in this phase?
o
D
6
e
c
r
u
Bean Files
Instantiate
o
Loaded
S
Beans
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
Setters
l
t
i
a
Called
i
s
n
i
i
c
i
a tD
f
r
f
T
O
o
Bean
NBPP
Initializer
BPP
BPP
Ready
BPP
o
For Use
D
Bean Post Processors
Post Process
Bean
Definitions
Dependency
Injection
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
a
Load
BeaniDefinitions
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Post Process
Bean
Definitions
Instantiate
Beans
Setters
Called
Bean
Ready
For Use
After
Init
Initializers
Called
Before
Init
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
Each indexed under its id
O
p
u
S ng ribbeans are
Special BeanFactoryPostProcessor
l
t
i
a
invoked
i
s
n
i
i
c
i
Can modify
the definition
ofD
any bean
a
f
r
f
t
T
O
o
NBean Files
o
Loaded
D
Post Process
Bean
Definitions
e
c
r
u
application-config.xml
o
S
g
y
Application
Context
l
n
i
e
n
r
t
BeanFactory
O
p
u
S ng rib
l
t
i
a
i
test-infrastructure-config.xml
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<beans>
<bean id=transferService
<bean id=accountRepository
</beans>
transferService
accountRepository
dataSource
<beans>
<bean id=dataSource
</beans>
postProcess(BeanFactory)
BeanFactoryPostProcessors
10
The BeanFactoryPostProcessor
Extension Point
e
c
r
u
Useful for applying transformations
to groups
o
of bean definitions
S
g
y
Before any objects are actually
created
l
n
i
e
n
r
t
Several useful implementations
areu
provided
O
p
S ng rib
by the framework
l
t
a
You can also
write youri own
i
s
n
i
i
c
the BeanFactoryPostProcessor
interface
Implement
i
a
D
f
r
f
t
T
O
o
N
o
D
public interface BeanFactoryPostProcessor {
public void postProcessBeanFactory
(ConfigurableListableBeanFactory beanFactory);
}
11
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Remember <context:property-placeholder/> ?
<beans ...>
<context:property-placeholder location=db-config.properties />
<bean id=dataSource class=com.oracle.jdbc.pool.OracleDataSource>
<property name=URL value=${dbUrl} />
<property name=user value=${dbUserName} />
</bean>
</beans>
dbUrl=jdbc:oracle:...
dbUserName=moneytransfer-app
<bean id=dataSource
class=com.oracle.jdbc.pool.OracleDataSource>
<property name=URL value=jdbc:oracle:... />
<property name=user value=moneytransfer-app />
</bean>
12
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<bean class="org.springframework...PropertySourcesPlaceholderConfigurer">
<property name="location" value="db-config.properties"/>
</bean>
Implements
BeanFactoryPostProcessor
e
c
r
u
Load bean definitions
o
S
Initialize bean instances
g
y
l
n
i
e
n
r
t
Bean Files
O
p
u
Loaded
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o Create Beans
O
N
o
D
for-each bean
Post Process
Bean
Definitions
Bean
Ready
For Use
After
Init
Initializers
Called
Instantiate
Beans
Setters
Called
Before
Init
Bean Post-Processor(s)
14
e
c
r
u
Each bean is eagerly instantiated
by default
o
Created in right order with its
dependencies injected
S
g
y
l
After dependency injection
each
bean goes
n
i
e
n
r
t
through a post-processing
phase u
O
p
b
S and
Further configuration
initialization
may occur
g
i
l
r
n
t
i
a
After post processing
the bean
is fully
i
s
n
i
i
c
i
initialized
and
ready
for D
use
a
f
r
f
t
Tracked
by
its
id
until
the
context is destroyed
T
O
o
N
o
D
e
c
r
u
There are two types of bean post
processors
o
Initializers
S
g
y
l
n
i
e
n
All the rest!
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o Initializer
O
BPP
BPP
BPP
BPP N
o
D Bean Post Processors
Initialize the bean if instructed
16
e
c
r
u
Initialize the bean if instructed
o
S
Call special BeanPostProcessors
to perform
g
y
l
additional configuration
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o Initializer
O
BPP
BPP
BPP
BPP N
o
D Bean Post Processors
17
e
c
r
u
All init methods are called
o
CommonAnnotationBeanPostProcessor
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
By Annotation
Using XML only
N
o
<context:annotation-config/>
D
public class JdbcAccountRepo {
@PostConstruct
public void populateCache() {
//...
}
<bean id=accountRepository
class=com.acme.JdbcAccountRepo
init-method=populateCache>
</bean>
18
e
c
r
Initialize the bean if instructedu
o
S
Call special BeanPostProcessors
to perform
g
y
l
additional configuration
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o Initializer
O
BPP
BPP
BPP
BPP N
o
D Bean Post Processors
Bean Post Processors
19
The BeanPostProcessor
Extension Point
e
c
Course
r
An important extension point inuSpring
will show
o
several
Can modify bean instances inS
any way
g
BPPs
y
Powerful enabling feature
l
n
i
e
n
r
t
Spring provides several
implementations
O
p
u
b
S your
Not common to write
own
g
i
l
r
n
t
i
a
the BeanPostProcessor interface
Must implement
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Post-processed
bean
Original bean
20
Configuration Lifecycle
XML
config
Annotation
config
Java
config
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Bean
detection
Load xml
definitions
BeanFacPP
Instantiation &
constr. injection
Property
injection
@Component
scanning
Instantiation &
@Autowired
on constructor
Read @Bean
method
signatures
BeanFacPP
BeanPP
BeanPP
Injection of
@Autowired
methods & fields
BeanFactoryPostProcessor
BeanPostProcessor
21
e
c
r
Post Process u
Bean Files
Instantiate
Bean o
Loaded
S
Beans
Definitions
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
Setters
t
i
a
i
Called
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
Bean
Initializer
o
BPP
BPP
Ready
BPP
BPP
D
For Use
Bean Post Processors
Dependency
Injection
e
c
r
u
Introduction
o
S
The initialization phase
g
y
l
n
The use phase
i
e
n
r
t
O
p
u
The destruction phase
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
Initialization
Destruction
D Use
23
e
c
r
u
When you invoke a bean obtained
from the
o
context the application is used
S
g
y e
l
ApplicationContext context = //iget
it from somewhere
n
n
t
// Lookup the entry point into r
the application
O bu
TransferService serviceS
=p
g
i
(TransferService) l
context.getBean(transferService);
r
n
t
i
a
// Use it!
i
s
n
i
i
c
service.transfer(new
MonetaryAmount(50.00),
1, 2);
i
a
D
f
r
f
t
T
O
o
But exactly what happens
N in this phase?
o
D
24
e
c
r
u
The bean is just your raw object
o
it is simply invoked directly (nothing
special)
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng inriabproxy
Your bean has lbeen wrapped
t
i
a
i
s
things become moren
interesting
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Proxy classes are created in the init phase by dedicated
transfer($50, 1, 2)
TransferServiceImpl
transfer($50, 1, 2)
Spring Proxy
TransferServiceImpl
BeanPostProcessors
25
Proxy Power
e
c
r
u
A BeanPostProcessor may wrap your
beans in a
o
dynamic proxy and add behavior
to your
S
g
y
application logic transparently
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Spring Proxy
transfer($50, 1, 2)
Spring
TransactionInterceptor
begin
TransferServiceImpl
commit
TransactionManager
Transaction
management
behavior is added
around your code
26
e
c
r
u
Introduction
o
S
The initialization phase
g
y
l
n
The use phase
i
e
n
r
t
O
p
u
The destruction phase
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
Use
Destruction
Initialization
o
D
27
e
c
r
u
When you close a context the destruction
o
phase completes
S
g
y
l
ConfigurableApplicationContext
context
=
n
i
e
n
r
t
// Destroy the application
O
p
u
context.close();
S ng rib
l
t
i
a
i
s
n
But exactly
what happens
in
this phase?
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
28
e
c
r
u
Destroy bean instances if instructed
o
S
Destroy itself
g
y
l
The context is not usable
again
n
i
e
n
r
t
All destroy methods
are called
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
By Annotation
Using XML
<bean id=accountRepository
class=app.impl.AccountRespository
destroy-method=clearCache>
</bean>
29
Topics Covered
e
c
r
u
Spring Lifecycle
o
The initialization phase
S
g
y
l
n
i
e
n
The use phase
r
t
O
p
u
b
S
g
i
l
r
The destruction phase in
t
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
Use
Destruction
Initialization
o
D
Bean Post Processors for initialization and proxies
30
e
c
r
u
o
S
g
y
l
Testing Spring
Applications
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Unit Testing
without
Spring,
s
n
i
i
c
i
a Testing
D
f
and
Integration
with Spring
r
f
t
T
O
o
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
What is TDD
e
c
r
u
o
S
g
y
l
n
i importantn te
That is not what is most
r
p g O bu
TDD is about: S
i
l
r
n
writing automated
tests
that verify
code actually
t
i
a
i
s
n
works
i
i
c
i
a witht well
D defined requirements
f
Driving
development
r
f
in O
the form ofT
tests o
N
o
D
e
c
r
Every development process includes
testing
u
o
Either automated or manual S
g lydevelopment
Automated tests result n
in a faster
i
e
n
r
t
cycle overall
O
p
u
b
Sat thisnthan
Your IDE is better
g youtrare
i
l
i
a
Properly done
TDD is
faster than
development
i
s
n
i
i
c
i
without tests
a tD
f
r
f
T o
O
N
o
D
4
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
time
O
p
u
to fix
S ng rib
l
t
i
a
i
s
n
i
i
c
i
adiscovered
D
f
r
f
time until
t
T
O
o
N
Continuous Integration
(CI) focuses on
o
reducing the time
D before the bug is discovered
The cost to fix a bug grows exponentially in
proportion to the time before it is discovered
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
r
u
o
Tests one unit of functionality
S
g
y
Keeps dependencies minimal
l
n
i
e
n
r
t
Isolated from the environment
(including
O
p
u
Spring)
S ng rib
l
t
Integration Testing
i
a
i
s
n
i
i
c
Tests the
interaction
of multiple
units working
i
a
D
f
r
f
together
t
T
O
o
Integrates infrastructure
N
o
D
Unit Testing
e
c
10
Unit Testing
r
u
o
The test shouldn't fail because of
external
S
dependencies
g
y
l
n
i as a dependency
Spring is also considered
e
n
r
t
O
p
u
b
S ng rimplementation
i
2 ways to create a
testing-purpose
of
l
t
i
a
i
your dependencies:
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
e
c
11
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T
O
Spring config
JPA config o
N
o
D
Production DB
Production mode
AuthenticatorImpl
Injected
by Spring
JpaAccountRepo
AuthenticatorImpl
JUnit
AccountRepoStub
fake implementation
NO Database!!
12
e
c
r
u
o
S
g
y
l
n
External
dependency
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o Unit business logic
O
2 paths: success or fail
N
o
D
Note: Validation failure paths ignored for simplicity
public
public class
class AuthenticatorImpl
AuthenticatorImpl implements
implements Authenticator
Authenticator {{
private
private AccountRepository
AccountRepository accountRepository;
accountRepository;
public
public AuthenticatorImpl(AccountRepository
AuthenticatorImpl(AccountRepository accountRepository)
accountRepository) {{
this.accountRepository
this.accountRepository == accountRepository;
accountRepository;
}}
public
public boolean
boolean authenticate(String
authenticate(String username,
username, String
String password)
password) {{
Account
Account account
account == accountRepository.getAccount(username);
accountRepository.getAccount(username);
}}
}}
return
return account.getPassword().equals(password);
account.getPassword().equals(password);
13
Implementing a Stub
e
c
r
u
o
Implements Business interface
S
g
y
l
n
i
e
n
r
t
O
p
u
b
S Simple
g
i
l
state tr
n
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
class
class StubAccountRepository
StubAccountRepository implements
implements AccountRepository
AccountRepository {{
public
public Account
Account getAccount(String
getAccount(String user)
user) {{
return
return lisa.equals(user)
lisa.equals(user) ?? new
new Account(lisa,
Account(lisa, secret)
secret) :: null;
null;
}}
}}
AccountRepository
JPA
AccountRepository
Stub
AccountRepository
14
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
import
import org.junit.Before;
org.junit.Before; import
import org.junit.Test;
org.junit.Test; ...
...
public
public class
class AuthenticatorImplTests
AuthenticatorImplTests {{
private
private AuthenticatorImpl
AuthenticatorImpl authenticator;
authenticator;
@Before
@Before public
public void
void setUp()
setUp() {{
authenticator
authenticator == new
new AuthenticatorImpl(
AuthenticatorImpl(
new
new StubAccountRepository());
StubAccountRepository());
}}
}}
@Test
@Test public
public void
void successfulAuthentication()
successfulAuthentication() {{
assertTrue(authenticator.authenticate(lisa,
assertTrue(authenticator.authenticate(lisa, secret));
secret));
}}
OK scenario
@Test
@Test public
public void
void invalidPassword()
invalidPassword() {{
assertFalse(authenticator.authenticate(lisa,
assertFalse(authenticator.authenticate(lisa, invalid));
invalid));
}}
KO scenario
15
e
c
r
u
o
Easy to implement and understand
S
g
y
Reusable
l
n
i
e
n
r
t
Disadvantages
O
p
u
Change to an interface
requires
change
to stub
b
S
g
i
l
r
n
t
Your stub must
implement
all methods
i
a
i
s
n
i
i
c
i
arefactoring
D
f
r
f
If a stub
is reused
can break other tests
t
T o
O
N
o
D
Advantages
16
e
c
r
u
o
S
g
Implements the dependent
interface
on-the-fly
y
l
n
i
e
n
r
t
2. Record the mock with expectations
of
how it
O
p
u
will be used for S
a scenario
b
g
i
l
r
n
What methods
will be icalled
t
a
i
s
n
i
i
c
What values
to return
i
a
D
f
r
f
t
3. Exercise
the
scenario
T
O
o
N were met
4. Verify mock expectations
o
D
1. Use a mocking library to generate a mock
object
17
e
c
r
u
o
A Mock class is created at startup
time
S
g
y
l
n
i
e
n
r
t
O
p
u
static import
b
S
g
i
l
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Implementation of interface
Setup
AccountRepository is created
18
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
Verification
D
e
c
Recording
Recording Playback
playback
mode
verify(accountRepository);
}
Mock Considerations
e
c
r
u
Mockito, JMock, EasyMock
o
S
Advantages
g
y
l
n
i
No additional class to maintain
e
n
r
t
p
u
You only need to setup
what isO
necessary
for the
b
S n
i
scenario you are
testing g
l
r
t
i
a
i
Test behavior
as welln
as state s
i
i
c
i
a tD
f
r
f
T o
Disadvantages
O
N at first
A little harder to understand
o
D
Several mocking libraries available
20
Mocks or Stubs?
e
c
r
u
o
S
g
y
Favor mocks for non-trivial
interfaces
l
n
i simpleninterfacestewith
r
Use stubs when you have
O
p
u
repeated functionality
b
S
g
i
l
r
Always consider the specific
situation
n
t
i
a
i
s
n
i
i
Read Mocks
Arent
Stubs
by
Martin Fowler
c
i
a tD
f
r
f
T o
O
N
o
D
You will probably use both
General recommendations
http://www.martinfowler.com/articles/mocksArentStubs.html
21
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
22
Integration Testing
e
c
r
u
o
S
g
y
l
n
i
e
n
Infrastructure may be r
scaled down
t
O
p
u
e.g. use Apache DBCP
connection
pool
instead
of
b
S
g
i
l
r
container-provider
pool obtained
through
JNDI
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
23
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Production mode
AuthenticatorController
Integration test
AuthenticatorTest
Injected
by Spring
Injected
by Spring
AuthenticatorImpl
AuthenticatorImpl
Injected
by Spring
Injected
by Spring
JpaAccountRepo
Production DB
JpaAccountRepo
Test DB
24
e
c
r
u
o
spring-test.jar
S
g
y
Consists of several JUnit
test support
classes
l
n
i
e
n
r
t
Central support class
is SpringJUnit4ClassRunner
O
p
u
b
Caches a shared S
ApplicationContext
across
test methods
g
i
l
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
25
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
No need for @Before method
D
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classpath:system-test-config.xml)
@ContextConfiguration(classpath:system-test-config.xml)
public
public final
final class
class TransferServiceTests
TransferServiceTests {{
@Autowired
@Autowired
Define bean to test
private
private TransferService
TransferService transferService;
transferService;
@Test
@Test
public
public void
void successfulTransfer()
successfulTransfer() {{
TransferConfirmation
TransferConfirmation conf
conf == transferService.transfer(...);
transferService.transfer(...);
...
...
}}
Test the system as normal
}}
26
@ContextConfiguration config
samples
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@ContextConfiguration
public
public final
final class
class TransferServiceTests
TransferServiceTests {{
}}
Defaults to
${classname}-context.xml
in same package
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classpath:com/acme/system-test-config.xml)
@ContextConfiguration(classpath:com/acme/system-test-config.xml)
public
public final
final class
class TransferServiceTests
TransferServiceTests {{
}}
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({classpath:config-1.xml,
@ContextConfiguration({classpath:config-1.xml, file:db-config.xml})
file:db-config.xml})
public
public final
final class
class TransferServiceTests
TransferServiceTests {{
}}
Multiple files allowed
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={AppConfig.class,
@ContextConfiguration(classes={AppConfig.class, SystemConfig.class})
SystemConfig.class})
public
public final
final class
class TransferServiceTests
TransferServiceTests {{
}}
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classpath:system-test-config.xml)
@ContextConfiguration(classpath:system-test-config.xml)
public
public final
final class
class TransferServiceTests
TransferServiceTests {{
@Autowired
@Autowired
private
private TransferService
TransferService transferService;
transferService;
@Test
@Test
public
public void
void successfulTransfer()
successfulTransfer() {{
...
...
}}
}}
@Test
@Test
public
public void
void failedTransfer()
failedTransfer() {{
...
...
}}
The ApplicationContext is
instantiated only once for
all tests that use the same
set of config files
(even across test classes)
e
c
r
u
o
S
g
y
Run everything quickly inside
your IDE
l
n
i
e
n
r
t
O
p
u
Allows reuse of your
configuration
between test
b
S
g
i
l
r
n
and production
environments
t
i
a
i
s
n
i
i
c
Application
configuration logic is typically reused
i
a
D
f
r
f
Infrastructure configuration
is environment-specific
t
T
O
o
N
o
D
DataSources
JMS Queues
29
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
30
Environment Abstraction
e
c
Spring 3.1
r
Group bean definitions for use in
specific
u
o
environments
S
y
Development, Testing, UAT,gQA, Production
l
n
i
e
n
Multiple deployment setups
r
t
O
p
u
Custom resolution
of placeholders
b
S
g
i
l
r
n
t
Dependent onathe environment
i
i
s
n
i
i
c
Hierarchyi of property sources
a
D
f
r
f
t
Injectable
environment
abstraction API
T
O
o
org.springframework.core.env.Environment
N
o
D
31
e
c
r
u
o
XML profile attribute on the <beans>
element
S
g
y
<beans> can be nested
l
n
i
e
n
r
t
Java-based
O
p
u
@Profile annotation
on
b
S
g
i
l
r
@Configuration
classes in
t
a
i
s
n
i
Or on individual
i
c
i
a tD
f
@Component
classes
r
f
T o
O
N
o
D
XML
Dev
TransferService
AccountRepo
DataSource
Application
QA
Prod
Environment
32
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
Subset of bean ldefinitions
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
All bean definitions
<beans xmlns=http://www.springframework.org/schema/beans
profile="dev"> </beans>
</beans>
Different subset
of beans for each
profile, plus some
shared beans
33
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<beans xmlns=http://www.springframework.org/schema/beans
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jdbc=http://www.springframework.org/schema/jdbc
xsi:schemaLocation="...">
<beans profile="dev">
<jdbc:embedded-database id="dataSource">
<jdbc:script location="classpath:com/bank/sql/schema.sql"/>
<jdbc:script location="classpath:com/bank/sql/test-data.sql"/>
</jdbc:embedded-database>
</beans>
<beans profile="production">
e
c
r
Using the @ActiveProfiles annotation
u
o
Make one or more profiles active
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classpath:system-test-config.xml)
@ActiveProfiles("dev")
public final class TransferServiceTests {
@Autowired
private TransferService transferService;
@Test
public void successfulTransfer() {
TransferConfirmation conf = transferService.transfer(...);
...
}
}
35
e
c
r
u
@ActiveProfiles inside the test class
o
S
@Profile inside the Component
class
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(infra-test-conf.xml)
@ActiveProfiles("jdbc")
public class TransferServiceTests
{...}
@Repository
@Profile("jdbc")
public class
JdbcAccountRepository
{ ...}
36
e
c
r
Using the @Profile annotation u
o
Can also use on a @Component
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Configuration
@Profile("dev")
public final class DevConfig {
@Component
@Profile("dev")
public class DevOnlyClass { }
@Bean
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setName("testdb")
.setType(EmbeddedDatabaseType.HSQL)
.addScript("classpath:/testdb/schema.db")
.addScript("classpath:/testdb/test-data.db").build();
}
37
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
?
?
i
c
i
a tD
f
r
f
T o
O
N
o
D
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(infra-test-conf.xml)
@ActiveProfiles("jpa")
public final class TransferServiceTests
{...}
@Service
public class
TransferServiceImpl { ...}
@Repository
@Profile("jpa")
public class
JpaAccountRepository
{ ...}
@Repository
@Profile("jdbc")
public class
JdbcAccountRepository
{ ...}
38
e
c
r
u
o
Integration Test (above)
Using @ActiveProfiles inside anS
g
(next)
Programmatically on ApplicationContext
y
l
n
i
e
n
r
t
O
p
u
b
S
g
i
System property
in the command
line
l
r
n
t
i
a
i
s
n
i
i
c
i
a
D
f
r
f
t
Web-based
application)
In web.xml (for
T
O
o
N
o
D
-Dspring.profiles.active=dev
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>jpa</param-value>
</context-param>
web.xml
39
Programmatically
e
c
r
u
o
S
g ly
Every application contextn
now has one
i
e
n
r
Must set profile before loading XML files t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
ClassPathXmlApplicationContext applicationContext =
new ClassPathXmlApplicationContext();
applicationContext.getEnvironment().setActiveProfiles("dev");
applicationContext.setConfigLocations("classpath:/application-config.xml");
applicationContext.refresh(); // Forces context to load beans
40
Property Sources
e
c
r
u
o
Different property values in different
environments
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
Property Resolvers
i
a
D
f
r
f
Same property
may be defined
multiple times
t
T
O
o
Works out which value
to use
N
since 3.1
Used by <context:property-placeholder/>
o
D
PropertySources
@Configuration
@Profile("dev")
@PropertySource("classpath:/config/dev.properties")
public final class DevConfig { ..}
41
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<import resource="classpath:config/${current.env}-config.xml"/>
<context:property-placeholder properties-ref=configProps/>
<beans profile="dev">
<util:properties id="configProps" location="config/dev.properties">
</beans>
<beans profile="prod">
<util:properties id="configProps" location="config/prod.properties">
</beans>
current.env=dev
database.url=jdbc:derby:/test
database.user=tester
current.env=prod
database.url=jdbc:oracle:thin:...
database.user=admin
42
Summary
e
c
r
u
o
S
g
External dependencies should
be minimized
y
l
n
ior mocksnto unit test
e
Consider creating stubs
r
t
O
p
u
You dont need Spring
to
unit
test
S ng rib
l
Integration testing
tests
the interaction
of
t
i
a
i
s
n
i
i
c
multiple units
working
together
i
a
D
f
r
f
Spring provides good integration
testing support
t
T
O
o
Profiles for different N
test & deployment configurations
o
D
43
e
c
r
u
o
S
g
y
l
LAB
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Testing Spring
Applications
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
o
S
Developing Aspects
with
g
y
l
n
i
e
n
Spring
AOP
r
t
O
p
u
S ng rib
l
t
i
a
i
Aspect-Oriented
Programming
for
s
n
i
i
c
i
Declarative
Enterprise
Services
a
D
f
r
f
t
T
O
o
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
What Problem Does AOP Solve?
o
S
Core AOP Concepts
g
y
l
n
Quick Start
i
e
n
r
t
O
u
Defining Pointcuts p
b
S
g
i
l
r
Implementing Advice in
t
a
i
s
i
Advancedic
topics in
a
D
f
r
f
Named Pointcuts
t
T
O
o
Context selecting pointcuts
N
Working with annotations
o
D
2
e
c
r
u
Aspect-Oriented Programming (AOP)
enables
o
modularization of cross-cutting
concerns
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
3
e
c
r
u
o
S
g
y
l
n
i
e
n
Logging and Tracing r
t
O
p
u
Transaction Management
b
S
g
i
l
r
n
Security
t
i
a
i
s
n
i
Cachingic
i
a tD
f
Error fHandling r
TMonitoringo
O
Performance
N
Custom Business
Rules
o
D
An Example Requirement
e
c
r
u
Perform a role-based security
check
o
S
before every application
method
g
y
l
n
i
e
n
r
t
O
p
u
b
S isnagcross-cutting
i
A sign this requirement
concern
l
r
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
5
e
c
r
u
Failing to modularize cross-cutting
concerns
o
leads to two things
S
g
y
1. Code tangling
l
n
i
e
n
r
t
p g O bu
2. Code scattering S
i
l
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
A coupling of concerns
e
c
r
public class RewardNetworkImpl implements RewardNetwork
{
u
o
public RewardConfirmation rewardAccountFor(Dining
dining) {
S
if (!hasPermission(SecurityContext.getPrincipal())
{
g
y
l
throw new AccessDeniedException();
n
i
e
n
r
t
}
Mixing
of concerns
O
p
u
S ng rib
Account a = accountRepository.findByCreditCard(
l
t
i
a
Restaurant r = restaurantRepository.findByMerchantNumber(
i
s
n
i
i
c
MonetaryAmount
amt = r.calculateBenefitFor(account, dining);
i
a tD
f
r
f
T o
O
}
N
}
o
D
7
e
cAccountManager {
public class HibernateAccountManager implements
r
public Account getAccountForEditing(Long id)
{
u
o
if (!hasPermission(SecurityContext.getPrincipal())
{
S
throw new AccessDeniedException();
g
y
l
}
n
i
e
n
r
t
Duplication
O
p
u
b
S
g
i
l
r
n
public class HibernateMerchantReportingService
implements
t
i
a
i
s
MerchantReportingService
{ in
i
c
i
public List<DiningSummary>
merchantNumber,
a findDinings(String
D
f
r
f
t
DateInterval interval) {
T
O
o
if (!hasPermission(SecurityContext.getPrincipal())
{
N
throw new AccessDeniedException();
o
}
D
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Security
Transactions
Logging
BankService
Code
scattering
CustomerService
Code
tangling
ReportingService
Aspect Oriented
Programming (AOP)
e
c
r
u
Aspect-Oriented Programming
(AOP)
o
enables modularizationS
of cross-cutting
g
y
l
concerns
n
i
e
n
r
t
To avoid tangling
O
p
u
S ng rib
To eliminatelscattering
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
10
e
c
r
u
1. Implement your mainline application
logic
o
Focusing on the core problem
S
g
y
l
2. Write aspects to implement
your
cross-cutting
n
i
e
n
r
t
concerns
O
p
u
b
Spring provides S
many aspects
out-of-the-box
g
i
l
r
n
t
i
a
3. Weave the iaspectsn
into your
application
s
i
c ai behaviours
Addingfithe cross-cutting
to the right
D
r
f
t
places
T
O
o
N
o
D
11
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
BankService
Security
Aspect
CustomerService
Transaction
Aspect
ReportingService
Logging
Aspect
12
e
c
r
u
AspectJ
o
Original AOP technology (firstS
version in 1995)
g
y
Offers a full-blown Aspect
Oriented
Programming
l
n
i
e
n
language
r
t
O
p
u
b
S
g
i
l
r
Spring AOP a
n
t
i
i
s
n
Java-based
AOP framework
with
AspectJ integration
i
i
c
i
a tD
f
r
f
T AOPoto solve enterprise problems
O on using
Focuses
The focus of this N
session
o
D
Uses byte code modification for aspect weaving
13
e
c
r
What Problem Does AOP Solve?u
o
S
Core AOP Concepts
g
y
l
n
Quick Start
i
e
n
r
t
O
u
Defining Pointcuts p
b
S
g
i
l
r
Implementing Advice in
t
a
i
s
i
Advancedic
topics in
a
D
f
r
f
Named Pointcuts
t
T
O
o
Context selecting pointcuts
N
Working with annotations
o
D
14
e
c
r
u
Join Point
o
A point in the execution of a S
program such as a
g
method call or field assignment
y
l
n
i
e
n
r
t
Pointcut
O
p
u
An expression that
selectsg
one or more
Join Points
b
S
i
l
r
n
t
i
a
Advice
i
s
n
i
i
c
i
Code to
be executed
at a Join
Point that has been
a
D
f
r
f
selected
by a Pointcut
t
T
O
o
Aspect
N
o
A module that encapsulates
pointcuts and advice
D
15
e
c
r
What Problem Does AOP Solve?u
o
S
Core AOP Concepts
g
y
l
n
Quick Start
i
e
n
r
t
O
u
Defining Pointcuts p
b
S
g
i
l
r
Implementing Advice in
t
a
i
s
i
Advancedic
topics in
a
D
f
r
f
Named Pointcuts
t
T
O
o
Context selecting pointcuts
N
Working with annotations
o
D
16
e
c
r
Consider this basic requirementu
o
S
g
y
l
Log a message every time
a
property
is about to change
n
i
e
n
r
t
O
p
u
b
S
g
i
l
r
How can you use AOPin
to meettit?
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
17
e
c
public class SimpleCache implements Cache, BeanNameAware
r
u
{
o
private int cacheSize;
S
private DataSource dataSource;
g
y
l
n
private String name;
i
e
n
r
t
O
p
u
public void setCacheSize(int
size)
{
cacheSize
=
size;
}
b
S
g
i
l
r
n
t
i
a
i
public void setDataSource(DataSource
ds)
{ dataSource = ds; }
s
n
i
i
c
i
a tD
f
// Allow beanf to know itsrname for
logging
T obeanName) { name = beanName; }
OsetBeanName(String
public void
N
public String toString() {o
return name; }
D
e
c
r
u
@Aspect
o
public class PropertyChangeTracker { S
g
y
private Logger logger = Logger.getLogger(getClass());
l
n
i
e
n
r
t
@Before(execution(void p
set*(*))) O
u
S { ng rib
public void trackChange()
l
t
logger.info(Property
abouti to change);
a
i
s
n
i
}
i
c
i
a tD
f
}
r
f
T o
O
N
o
D
19
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
aspects-config.xml
<beans>
e
c
<aop:aspectj-autoproxy>
<aop:include name=propertyChangeTracker />
</aop:aspectj-autoproxy>
20
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
application-config.xml
<beans>
e
c
21
e
c
r
u
o
S
ApplicationContext context =
g
y
l
new ClassPathXmlApplicationContext(application-config.xml);
n
i
e
n
r
t
Cache cache = (Cache) context.getBean(cache-A);
O
u
cache.setCacheSize(2500); p
b
S
g
i
l
INFO: Property
about toin
change tr
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
22
e
c
r
u
o
Cache S
g
y
l
n
i
e
n
r
t
O
p
u
Spring
AOP
Proxy
(this)
S ng rib
l
t
i
a
PropertyChange
SimpleCache
i
s
n
i
i
c
Tracker
(aspect)
(target)
i
a
D
f
r
f
t
T
O
o
N
o
D
setCacheSize(2500)
<<interface>>
23
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Before(execution(void set*(*)))
public void trackChange(JoinPoint point) {
String name = point.getSignature().getName();
Object newValue = point.getArgs()[0];
logger.info(name + about to change to + newValue +
on + point.getTarget());
toString() returns bean-name
}
}
e
c
r
What Problem Does AOP Solve?u
o
S
Core AOP Concepts
g
y
l
n
Quick Start
i
e
n
r
t
O
p
u
Defining Pointcuts
b
S
g
i
l
r
Implementing Advice in
t
a
i
s
i
Advancedic
topics in
a
D
f
r
f
Named Pointcuts
t
T
O
o
Context selecting pointcuts
N
Working with annotations
o
D
25
Defining Pointcuts
e
c
r
u
With Spring AOP you write pointcuts
using
o
AspectJs pointcut expression
language
S
g
For selecting where to apply
advicely
n
i
e
n
r
t
Complete expression
language
reference
O
p
u
S ng rib
available at
l
t
i
a
http://www.eclipse.org/aspectj
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
26
e
c
r
execution(<method pattern>) u
o
The method must match the S
pattern
g
y e
l
Can chain together to icreate
composite
n
n
r
t
pointcuts
O
p
u
b
&& (and), || (or),S! (not) g
i
l
r
n
t
i
a
i
s
n
i
i
c
fi ra t D
MethodfPattern
T o[ClassType]
O ReturnType
[Modifiers]
N
MethodName ([Arguments])
[throws
ExceptionType] o
D
27
Writing expressions
e
c
r
u
o
S
g
y
l
n
i
e
n
execution(* rewards.restaurant.*Service.find*(..))
r
t
O
p
u
S ng rib
l
t
designator
packagei
method
a
i
s
n
i
i
c
i
return
type a
D
f
type
params
r
f
t
T o
O
N
o
D
28
Execution Expression
Examples
e
c
r
u
o
execution(void send*(String))
S
g
y
l
n
i
e
n
r
t
O
p
u
execution(* send(*))
S ng rib
l
t
i
a
i
s
n
i
i
c
execution(* f
send(int,
fi ..))ra t D
T o
O
N
o
D
29
Execution Expression
Examples
e
c
r
u
o
S
g
y
l
n
i
e
n
execution(void example.MessageService.send(*))
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a
D
f
r
f
t
execution(@javax.annotation.security.RolesAllowed
void send*(..))
T
O
o
N
o
D
execution(void example.MessageServiceImpl.*(..))
30
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
execution(* rewards..restaurant.*.*(..)) O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
execution(* f
*..restaurant.*.*(..))
r
T o
O
N
o
D
execution(* rewards.*.restaurant.*.*(..))
31
e
c
r
What Problem Does AOP Solve?u
o
S
Core AOP Concepts
g
y
l
n
Quick Start
i
e
n
r
t
O
u
Defining Pointcuts p
b
S
g
i
l
r
Implementing Advice
n
t
i
a
i
s
i
Advancedic
topics in
a
D
f
r
f
Named Pointcuts
t
T
O
o
Context selecting pointcuts
N
Working with annotations
o
D
32
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Proxy
BeforeAdvice
Target
33
e
c
r
u
o
If the advice throws an exception,
target will not be
S
called
g
y
l
n
i
e
n
Track calls to all setter methods
r
t
O
p
u
S ng rib
@Aspect
l
i
a
public class PropertyChangeTracker
{ st
i
n
i
i
c
private Logger
logger
=
Logger.getLogger(getClass());
i
a tD
f
r
f
T set*(*)))
O
@Before(execution(void
o
public void trackChange()N
{
logger.info(Property
about to change);
o
D
}
34
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Proxy
AfterReturningAdvice
Target
Successful return
35
e
c
r
u
o
S
g
y e
Audit all operations in the servicein
package thatl return a Reward
n
r
t
object
O
p
u
b
S ngservice..*.*(..)),
i
@AfterReturning(value=execution(*
l
r
t
i
a
returning=reward)
i
s
n
i
i
c
public void audit(JoinPoint
jp, Reward
reward) {
i
a
D
f
r
f
auditService.logEvent(jp.getSignature()
+
t
T
O
o
returns the following reward
object : + reward.toString() );
N
}
o
D
36
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Proxy
AfterThrowingAdvice
Target
Exception
37
e
c
r
u
o
S
g
y
l
Send an email every time a Repository
class throws
an exception of
n
i
e
n
r
type DataAccessException
t
O
p
u
b
S
g
i
l
@AfterThrowing(value=execution(*n
*..Repository.*(..)),
throwing=e)
r
t
i
a
i
public void report(JoinPoint
jp, DataAccessException
e) {
s
n
i
i
c
i
mailService.emailFailure(Exception
in repository, jp, e);
a
D
f
r
f
t
}
T
O
o
N
o
D
Use @AfterThrowing annotation with the
throwing attribute
38
e
c
r
u
o
S
type of exception
However it can throw a differentg
y
l
n
i
e
n
r
t
@AfterThrowing(value=execution(*
*..Repository.*(..)),
throwing=e)
O
p
u
b
public void report(JoinPointS
jp, DataAccessException
e) {
g
i
l
r
n
t
mailService.emailFailure(Exception
in repository,
jp, e);
i
a
i
s
n
i
throw new RewardsException(e);
i
c
i
a tD
f
}
r
f
T o
O
N
o
D
The @AfterThrowing advice will not stop the
exception from propagating
If you wish to stop the exception from propagating any further, you can
use an @Around advice (see later)
39
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Proxy
AfterAdvice
Target
40
e
c
r
u
o
Called regardless of whether an
exception has been
S
thrown by the target or notg
y
l
n
i
e
n
Track calls to all update methods
r
t
O
p
u
S ng rib
@Aspect
l
i
a
public class PropertyChangeTracker
{ st
i
n
i
i
c
private Logger
logger
=
Logger.getLogger(getClass());
i
a tD
f
r
f
T update*(*)))
O
@After(execution(void
o
public void trackUpdate()N
{
logger.info(An update
has been attempted );
o
D
}
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Proxy
AroundAdvice
Target
proceed()
42
e
c
r
u
o
ProceedingJoinPoint parameter
S
Inherits from JoinPoint and g
adds thely
proceed() method
n
i
e
n
r
t
Cache values returned by cacheable services
O
p
u
S ng rib
@Around(
)
l
t
i
a
public Object cache(ProceedingJoinPoint
point)
throws Throwable {
i
s
n
i
i
Object value i=c
cacheStore.get(cacheKey(point));
fnull) { ra t D
f
if (value ==
T o
O= point.proceed();
value
N value);
cacheStore.put(cacheKey(point),
o
}
D
return value;
execution(@example.Cacheable * rewards.service..*.*(..))
}
43
e
c
r
u only
Annotation syntax is Javao5+
S 1.4
XML syntax works on g
Java
y
l
n
i
e
n
Approach
r
t
O
p
u
Aspect logic defined
S nJava
g trib
l
i
a
Aspect configuration
in XML
i
s
n
i
i
c
i
Uses
the aop
a namespace
D
f
r
f
t
T
O
o
N
o
D
44
e
c
r
u
o
public class PropertyChangeTracker { S
g
public void trackChange(JoinPoint
point) { y
l
n
i
e
n
r
t
}
O
p
u
S ng rib
}
l
t
i
a
i
s
n
i
i
c
i
aJava Class
D
f
r
f
Aspect
is a Plain
with no Java 5 annotations
t
T o
O
N
o
D
45
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
46
e
c
r
u
o
LABgS
y
l
n
i with Spring
e
n
Developing Aspects
AOP
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
What Problem Does AOP Solve?u
o
S
Core AOP Concepts
g
y
l
n
Quick Start
i
e
n
r
t
O
u
Defining Pointcuts p
b
S
g
i
l
r
Implementing Advice in
t
a
i
s
n
i
i
Advanced
topics
c
i
a
D
f
r
f
Named Pointcuts
t
T
O
o
Context selecting pointcuts
N
Working with annotations
o
Limitations ofD
Spring AOP
48
e
c
r
u
o
Reuse it in multiple places
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<aop:config>
<aop:pointcut id=setterMethods expression=execution(void set*(*))/>
<aop:aspect ref=propertyChangeTracker>
<aop:after-returning pointcut-ref=setterMethods method=trackChange/>
<aop:after-throwing pointcut-ref=setterMethods method=logFailure/>
</aop:aspect>
</aop:config>
<bean id=propertyChangeTracker class=example.PropertyChangeTracker />
49
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Before(serviceMethod() || repositoryMethod())
public void monitor() {
logger.info(A business method has been accessed);
}
@Pointcut(execution(* rewards.service..*Service.*(..)))
public void serviceMethod() {}
@Pointcut(execution(* rewards.repository..*Repository.*(..)))
public void repositoryMethod() {}
}
50
Named Pointcuts
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Fully-qualified pointcut name
@Before(com.acme.SystemArchitecture.serviceMethods() )
public void monitor() {
logger.info(A service method has been accessed);
}
}
51
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
When working
with many
pointcuts
i
s
n
i
i
c
i
When writing
complicated
expressions
a
D
f
r
f
t
T
O
o
N
o
D
52
e
c
r
What Problem Does AOP Solve?u
o
S
Core AOP Concepts
g
y
l
n
Quick Start
i
e
n
r
t
O
u
Defining Pointcuts p
b
S
g
i
l
r
Implementing Advice in
t
a
i
s
n
i
i
Advanced
topics
c
i
a
D
f
r
f
Named Pointcuts
t
T
O
o
Context selecting pointcuts
N
Working with annotations
o
Limitations ofD
Spring AOP
53
e
c
r
Pointcuts may also select usefulujoin point
o
context
S
g (proxy)
y
The currently executing n
object
l
i
e
n
r
t
The target object
O
p
u
Method arguments
S ng rib
l
Annotations a
associatedi with the method,
target, or
t
i
s
n
arguments
i
i
c
i
a
D
f
r
f
Allows for simple POJOtadvice methods
T
O
o
Alternative to working
N with a JoinPoint object directly
o
D
54
e
c
r
Consider this basic requirementu
o
S
g
y
l
Log a message every time
Server
is
about
to start
n
i
e
n
r
t
O
p
u
S { ng rib
public interface Server
l
t
i
a
public void start(Map
input);
i
s
n
i
i
c
i
public void
stop();a
D
f
r
f
t
}
T
O
o
N
o
In the advice, how
D do we access Server? Map?
55
e
c
r
u
o
S
y
No type-safety guarantees g
l
n
i
e
n
Write advice defensively
r
t
O
p
u
b
Sexample.Server.start(java.util.Map)))
g
i
@Before(execution(void
l
r
n
t
i
a
public void logServerStartup(JoinPoint
jp)s
{
i
n
i
i
c
Server server
= (Server)
jp.getTarget();
i
a
D
f
r
Object[]fargs= jp.getArgs();
t
T
MapO
map = (Map) args[0];o
N
o
}
D
56
e
c
r
u
o
Method attributes are bound automatically
S
y
Types must match or advicegskipped
l
n
i
e
n
r
t
@Before(execution(void example.Server.start(java.util.Map))
O
p
u
&& target(server) && args(input))
S ng rib
l
public void logServerStartup(Server
server, Map
input) {
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
}
T o
O
N
- target(server) selects
the target of the execution (your object)
o
- this(server) would
Dhave selected the proxy
Best practice: use context selection
57
e
c
r
u
@Before(serverStartMethod(server, input))
o
S
public void logServerStartup(Server server,
Map input) {
g
y
l
n
i
e
n
r
t
}
O
p
u
S ng rib
l
t
i
a
@Pointcut(execution(void
example.Server.start(java.util.Map))
i
s
n
i
i
c
&& target(server)
&& args(input))
i
a
D
f
r
f
t
public void serverStartMethod
(Server
server, Map input) {}
T
O
o
N
o
D
target binds the server starting up
58
e
c
r
What Problem Does AOP Solve?u
o
S
Core AOP Concepts
g
y
l
n
Quick Start
i
e
n
r
t
O
u
Defining Pointcuts p
b
S
g
i
l
r
Implementing Advice in
t
a
i
s
n
i
i
Advanced
topics
c
i
a
D
f
r
f
Named Pointcuts
t
T
O
o
Context selecting pointcuts
N
Working with o
annotations
Limitations ofD
Spring AOP
59
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
execution(@org.*.transaction.annotation.Transactional
* *(..))
O
p
u
S ng rib
l
i
a
execution( (@example.Sensitive
*) *(..)) t
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Sensitive
public class MedicalRecord { }
60
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
61
e
c
r
u
o
@Around(transactionalMethod(txn)) S
g
y
public Object execute(ProceedingJoinPoint
jp, Transactional
txn) {
l
n
i
e
n
...
r
t
O
p
u
}
S ng rib
l
t
i
a
i
@Pointcut(execution(* *(..)) &&
@annotation(txn))
s
n
i
i
c
i
public void transactionalMethod(Transactional
txn) {}
a
D
f
r
f
t
T
O
o
N
o
D
Same example using a named-pointcut
62
e
c
r
What Problem Does AOP Solve?u
o
S
Core AOP Concepts
g
y
l
n
Quick Start
i
e
n
r
t
O
u
Defining Pointcuts p
b
S
g
i
l
r
Implementing Advice in
t
a
i
s
n
i
i
Advanced
topics
c
i
a
D
f
r
f
Named Pointcuts
t
T
O
o
Context selecting pointcuts
N
Working with annotations
o
Limitations D
of Spring AOP
63
e
c
r
u
Can only advise public Join Points
o
S
Can only apply aspects to Spring
Beans
g
y
l
n
Limitations of weavingiwith proxies
e
n
r
t
O
Spring adds behavior
using dynamic
proxies
if a Join
p
u
b
S an interface
g
Point is declared on
i
l
r
n
t
i
a
If a Join Point
is in a class without
an interface,
i
s
n
i
c
Spring reverts
to a
using
CGLIB ifor weaving
i
D
f
r
f
CGLib proxiesT
cannot be t
applied to final classes or
O
o
methods
N
When using dynamic
proxies, suppose method a()
o
calls method D
b() on the same class/interface
advice will never be executed for method b()
64
Summary
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
b
S ngas advice
Behavior is implemented
i
l
r
t
i
a
Pointcuts select
where
advice
applies
i
s
n
i
i
c
i
Five advice
types:
Before,
AfterThrowing,
a
D
f
r
f
t
AfterReturning,
After and
Around
T
O
o
Aspects can be defined
N using Java with
o
annotations and/or
in XML configuration
D
Aspect Oriented Programming (AOP)
modularizes cross-cutting concerns
An aspect is a module containing crosscutting behavior
65
e
c
r
u
Introduction S
tooData
g
y
l
Management
n
i
e
n
r
t
O
p
u
with
Spring
S ng rib
l
t
i
a
i
Springs role in supporting
data access
s
n
i
i
c
i
aenterprise
D
f
within an
application
r
f
t
T
O
o
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
The Role of Spring in Enterprise
Data Access
o
S
The DataAccessException Hierarchy
g
y e
l
The jdbc Namespace in
n
r
t
Implementing Caching
O
p
u
S ng rib
NoSQL databases
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
2
OpenJPA
DataNucleus
Hibernate
EclipseLink
other ...
e
Works consistently with leading data access
c technologies
r
u
o
Jdbc
JDBC
S
Repository
g
y
Relational
l
n
i
e
n
Hibernate
Database
r
t
Hibernate
O
p
u
Repository
S ng rib
l
t
Ibatis
i
a
i
iBatis
s
n
i
Repository
i
c
i
a tD
f
r
f
T JPA o
O
N
o
JPA
D
Repository
Java Database
Connectivity (JDBC)
JBoss Hibernate
Java Persistence
API (JPA)
EclipseLink
Data Nucleus
Apache iBatis
e
c
r
u
Doing it manually risks resourceo
leakage
S
Spring does it all for you!g
y
l
n
imanagement
e
n
Declarative transaction
r
t
O
p
u
S ng rib
l
t
i
a
i
s
Automatic connection
management
n
i
i
c
i
a tD
f
r
f
T o
O
Nhandling
Intelligent exception
o
D
Limited resources need to be managed
Declarative Transaction
Management
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
transfer($50, 1, 2)
Spring
TransactionInterceptor
begin
commit
Transaction
Manager
TransferServiceImpl
Transaction
management
behavior is added
around your code
e
c
r
u
To access a data source an application
must
o
Establish a connection
S
g
y
l
To start its work the application
must
n
i
e
n
r
t
Begin a transactionp
O
u
b
Sits work
g
When done with
i
the application
must
l
r
n
t
i
a
Commit or i
rollback the
transaction
s
n
i
i
c
i
Close the
connection
a tD
f
r
f
T o
O
N
o
D
6
e
c
r
u
o
http://en.wikipedia.org/wiki/Template_method_pattern
S
g
y
Define the outline or skeleton
of lan
algorithm
n
i
e
n
r
t
Leave the details to specific
implementations
later
O
p
u
Hides away large S
amounts g
of boilerplate
code
b
i
l
r
n
t
i
a
Spring provides
many template
classes
i
s
n
i
i
c
i
JdbcTemplate
a
D
f
r
f
t
JmsTemplate,
RestTemplate,
WebServiceTemplate
T
O
o
Most hide low-level N
resource management
o
D
Widely used and useful pattern
e
c
r
u
o
Typically: a web-driven request
S
g
y
Spring transaction management
l
n
i
e
n
r
Transaction manager handles transaction t
O
p
u
S ng rib
l
Data-access code,
like JdbcTemplate,
finds it
t
i
a
i
s
n
automatically
i
i
c
i
a tD
f
r
f
T o
O
N
o
Hibernate sessions,
D JTA (Java EE) work similarly
DataSourceUtils.getConnection(dataSource)
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
Service layer (or application layer)
O
p
u
S ng rib
l
t
i
a
i
s
i
Data access
layer in
c
i
a tD
f
r
f
T o
O
Infrastructure layer N
o
D
Layered Application
Architecture
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Classic example of a
Separation of Concerns
Service Layer
Infrastructure Layer
10
e
c
r
The Role of Spring in EnterpriseuData Access
o
S
The DataAccessException
Hierarchy
g
y e
l
The jdbc Namespace in
n
r
t
Implementing Caching
O
p
u
S ng rib
NoSQL databases
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
11
Exception Handling
e
c
r
u
o
Force developers to handle errors
S
g
y
l
n
i mustndeclare te
Bad: intermediate methods
r
O
p
u
exception(s) from
all methods
below
S ng rib
l
t
i
a
i
s
Uncheckedc
Exceptions
n
i
i
ithrown uprathe call hierarchy
D
Can beff
to the best place
t
to handle
O it T No
Good: Methods in between don't know about it
o
D
Spring throws Runtime (unchecked) Exceptions
Checked Exceptions
A form of tight-coupling
12
e
c
r
u
o
Too general one exception for
every database error
S
g
y
Calling class 'knows' you are
using JDBC
l
n
i
e
n
Tight coupling
r
t
O
p
u
Would like a hierarchy
ofg
exceptions
b
S
i
l
r
n
Consistent among
all Data
Accessttechnologies
i
a
i
s
n
i
i
c
Needs toibe unchecked
a
D
f
r
f
Not just one exception
for
everything
t
T
O
o
Spring provides DataAccessException
hierarchy
N
o
Hides whether you
are using JPA, Hibernate, JDBC ...
D
SQLException
13
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Select iddd from T_ACCOUNT
Plain
JDBC
Spring
java.sql.SQLException
errorCode: -28
java.sql.SQLException
errorCode: -28
BadSqlGrammarException
Message: PreparedStatementCallback;
e
c
r
u
o
S
g
y
l
DataAccessException
n
i
e
n
r
t
O
p
u
S ng rib DataIntegrity
DataAccessResource
l
FailureException
t
i
a
ViolationException
i
s
n
i
i
c
i
a tD
f
r
f
BadSqlGrammar
T
CleanupFailure
O
o
Exception
DataAccessException
N
o
OptimisticLocking
D
...
FailureException
RuntimeException
15
e
c
r
The Role of Spring in EnterpriseuData Access
o
The DataAccessException Hierarchy
S
g
y
l
The jdbc Namespace
n
i
e
n
r
t
Implementing Caching
O
p
u
S ng rib
NoSQL databases
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
16
JDBC Namespace
e
c
r
u
Introduced with Spring 3.0
o
Especially useful for testingS
g
y
l
Supports H2, HSQL and
Derby
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
In memory database
(created at startup)
17
JDBC Namespace
e
c
r
u
Allows populating other DataSources,
too
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Initializes an
external
database
18
e
c
r
The Role of Spring in EnterpriseuData Access
o
The DataAccessException Hierarchy
S
g ly
The jdbc Namespace in
e
n
r
t
Implementing Caching
O
p
u
S ng rib
NoSQL databases
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
19
About Caching
e
c
r
u
o
In this context: a key-value store
= Map
S
y
What are we caching? ng
l
i
e
n
r
Any method that always returns the sametresult for
O
p
u
the same argument(s)
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T
O
o
A unique key must be
generated
from the arguments
N
o
D
What is a cache?
20
Caching Support
e
c
Spring 3.1
r
Available since Spring 3.1
u
o
Transparently applies cachingS
to Spring beans (AOP)
Define one or more caches g
in Springly
configuration
n
i
e
n
Mark methods cacheable
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Indicate caching key(s)
Name of cache to use (multiple caches supported)
Use annotations or XML
Spring Application
@Cacheable
public Country[] loadAllCountries() { }
In-memory
cache
21
e
c
r
@Cacheable marks a method forucaching
o
its result is stored in a cache S
g
y
subsequent invocations (with
the same
arguments)
l
n
i
e
n
r
t
O
p
u
@Cacheable attributes
S ng rib
l
value: name a
of cache toi use
t
i
s
n
i
i
c
key: the ikey
for each
cached data-item
a tD
f
r
f
T o
O
N
o
D
@Cacheable(value="books", key="#refId.toUpperCase()")
public Book findBook(String refId) {...}
22
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
use object
property
@Cacheable(value="books", key="T(example.KeyGen).hash(#author)")
public Book findBook3(Author author, boolean checkWarehouse); custom key
generator
@CacheEvict(value="books")
public Book loadBooks();
clear cache before method invoked
<cache:annotation-driven />
23
e
c
r
u
o
For example with third-party class
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<aop:config>
<aop:advisor advice-ref="bookCache"
pointcut="execution(* *..BookService.*(..))"/>
</aop:config>
e
c
r
u
o
Some provided, or write your S
own
g
y
package.
See org.springframework.cache
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
25
e
c
r
u
o
S
EHcache
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
VMware Gemfire
T o
O
Cache
N
o
D
26
e
c
r
GemFire configuration in Springuconfig files
o
Also enables configuration injection
for environments
S
g
y
l
Features
n
i
e
n
r
t
Exception translation
O
p
u
b
GemfireTemplateS
g
i
l
n str
i
a
Transaction imanagement
n
i
i
c
(GemfireTransactionManager)
i
a
D
f
r
f
Injection of transient dependencies
during
t
T
O
o
deserialization
N
Gemfire Cache Manager class
o
D
27
e
c
r
The Role of Spring in EnterpriseuData Access
o
The DataAccessException Hierarchy
S
g ly
The jdbc Namespace in
e
n
r
t
Implementing Caching
O
p
u
S ng rib
NoSQL databases
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
28
e
c
r
u
o
Relational databases only store
some
data
S
g
y
l
n
i
e
n
r
t
O
p
u
Other database products
exist
b
S
g
i
l
r
n
Have strengths
where RDB
are weak
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
NoSQL
Non-tabular data
29
e
c
r
u
o
Document databases
S
g
y
l
n
i (smart
e
n
Distributed key-value Stores
caches)
r
t
O
p
u
b
S
g
i
l
Network (graph) database
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
Big Data
r
f
T o
O
N
Data Grid
o
D
Column Stores coming: HBase, Cassandra
30
Summary
e
c
r
u
Data Access with Spring
o
Enables layered architecture S
principles
g
y
l
n
i
e
n
r
t
O
p
u
Isolate via Data Access
Exceptions
S ng rib
l
t
i
a
i
Provides consistent transaction
management
s
n
i
i
c
i
a data-access
D
f
Supports
most leading
technologies
r
f
t
T
O
o
A key component ofN
the core Spring libraries
o
Automatic caching
D facility
31
e
c
r
u
o
S
g
y
l
Introduction to
Spring
JDBC
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Simplifying JDBC-based
data access
with Spring
s
n
i
i
c
i
JDBC D
a
f
r
f
t
T
O
o
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
Problems with traditional JDBC
o
Results in redundant, error prone
code
S
g
Leads to poor exception handling
y
l
n
e
n
Springs JdbcTemplateri
t
O
p
u
Configuration
b
S
g
i
l
r
Query execution
n
t
i
a
i
s
Working with
resultin
sets
i
c
i
a tD
f
Exception
handling
r
f
T o
O
N
o
D
2
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
3
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
5
e
c
r
Problems with traditional JDBC u
o
Results in redundant, error prone
code
S
g
Leads to poor exception handling
y
l
n
i
e
n
Springs JdbcTemplate
r
t
O
p
u
Configuration
b
S
g
i
l
r
Query execution
n
t
i
a
i
s
Working with
resultin
sets
i
c
i
a tD
f
Exception
handling
r
f
T o
O
N
o
D
6
Springs JdbcTemplate
e
c
r
u
Greatly simplifies use of the JDBC
API
o
Eliminates repetitive boilerplate
code
S
g
Alleviates common causes
of bugs ly
n
i
e
r
t
Handles SQLExceptions properly n
O
p
u
b
S power
Without sacrificing
g
i
l
r
n
t
i
a
Provides fulli access to the standard JDBC constructs
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
7
JdbcTemplate in a Nutshell
e
c
r
u
int count = jdbcTemplate.queryForInt(
o
S
SELECT COUNT(*) FROM
CUSTOMER);
g
y
l
n
i
e
n
r
t
Acquisition of the connection
O
p
u
b
S transaction
g
Participation inlthe
i
r
n
t
i
a
All handled
Execution ofi the statement
s
n
i
i
c
i
by Spring
a
D
f
Processing
of
the
result
set
r
f
t
T
O any exceptions
Handling
o
N
Release of the connection
o
D
8
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Creating a JdbcTemplate
e
c
r
u
Requires a DataSource
o
S
JdbcTemplate template = new JdbcTemplate(dataSource);
g
y
l
n
i
e
n
r
t
O
p
u
Create a template
once
and
re-use
it
b
S
g
i
l
r
n
t
i
Do not create
one
for
each
use
a
i
s
n
i
i
c
i
Thread
safe after
construction
a
D
f
r
f
t
T
O
o
N
o
D
10
e
c
r
u
Useful standalone
o
S
Anytime JDBC is needed
g
y
l
n
In utility or test code
i
e
n
r
t
O
p
u
To clean up messy
legacy
code
S ng rib
l
t
Useful for iimplementing
a
repository in
i
a
s
n
i
i
c
i
a layered
application
a tD
f
r
f
Also
O knownTas aNdata
o access object (DAO)
o
D
11
Implementing a JDBC-based
Repository
e
c
r
u
o
S
private JdbcTemplate jdbcTemplate;
g
y
l
n
i
e
n
public JdbcCustomerRepository(DataSource
dataSource)
{
r
t
O
p
u
this.jdbcTemplate = new JdbcTemplate(dataSource);
S ng rib
}
l
t
i
a
i
s
n
i
public int getCustomerCount()
{
i
c
a fromtcustomer;
D
fi count(*)
String sql =fselect
r
T
return jdbcTemplate.queryForInt(sql);
O
o
}
N
o
D
12
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
b
S ng JEE rNamespace
i
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
CreditReporting
Service
JdbcOrder
Repository
JdbcCustomer
Repository
JEE
Container
Managed
DataSource
lookup
JNDI
Object
Factory
Bean
JDBC Options
<jee:jndi-lookup id=dataSource
jndi-name=jdbc/credit />
13
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
14
e
c
r
u
JdbcTemplate can query for
o
Simple types (int, long, String)
S
g
y
Generic Maps
l
n
i
e
n
r
t
Domain Objects
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
15
e
c
r
Query with no bind variables u
o
queryForInt, queryForLong S
g
y e
l
public long getPersonCount() { in
n
r
t
String sql = select count(*)
from PERSON;
O
p
u
return jdbcTemplate.queryForLong(sql);
S ng rib
}
l
t
i
a
i
s
n
i
i
c
queryForObject
i
a
D
f
r
f
t
public Date
getOldestPerson()
{
T
O
o
String sql = select max(dob)
from PERSON;
N
return (Date) jdbcTemplate.queryForObject(sql, Date.class);
o
}
D
16
e
c
r
u
Query with a bind variable
o
list
Note the use of a variable argument
S
g
y
l
n
i
e
n
private JdbcTemplate jdbcTemplate;
r
t
O
p
u
S ng ribage) {
public int getCountOfPersonsOlderThan(int
l
t
i
a
return jdbcTemplate.queryForInt(
i
s
n
i
c
selecticount(*)
from
PERSON iwhere age > ?, age);
a tD
f
}
r
f
T o
O
N
o
D
17
Generic Queries
e
c
r
u
JdbcTemplate can return each row
of a ResultSet
o
as a Map
S
g
y
l
When expecting a single
row
n
i
e
n
r
t
Use queryForMap(..) p
O
u
Smultiple
g
When expecting
rows rib
l
n
t
i
a
Use queryForList(..)
i
s
n
i
i
c
i
a testing,
D
f
Useful for
reporting,
and window-onr
f
t
T o
dataO
use cases
N not need mapping to a Java
The data fetched does
o
object
D
Be careful with very large data-sets
18
e
c
r
u
Query for a single row
o
public Map getPersonInfo(int id) g
{ S
y
l
String sql = select * from PERSON
where
id=?;
n
i
e
n
r
t
return jdbcTemplate.queryForMap(sql,
id);
O
p
u
}
S ng rib
l
t
i
a
i
s
n
i
i
returns: ic
a
D
f
r
f
Map { ID=1, FIRST_NAME=John,
LAST_NAME=Doe }
t
T
O
o
N
A Map of [Column Name
| Field Value ] pairs
o
D
19
e
c
r
u
Query for multiple rows
o
S
public List getAllPersonInfo() {
g
y
String sql = select * from PERSON;
l
n
i
e
n
return jdbcTemplate.queryForList(sql);
r
t
O
p
u
}
b
S
g
i
l
r
n
returns:
t
i
a
i
s
n
List {
i
i
c
i ra
D
0 - Mapf{fID=1, FIRST_NAME=John,
LAST_NAME=Doe }
t
T o
1 - Map
{ ID=2, FIRST_NAME=Jane,
LAST_NAME=Doe }
O
N
2 - Map { ID=3, FIRST_NAME=Junior,
LAST_NAME=Doe }
o
}
D
A List of Maps of [Column Name | Field Value ] pairs
20
e
c
r
u
Often it is useful to map relational
data into
o
domain objects
S
g
y
e.g. a ResultSet to an Account
l
n
i
e
n
r
t
Springs JdbcTemplate
supports
this u
using a
O
p
S ng rib
callback approach
l
t
i
a
i
s
n
i
i
c
i
a use tORM
D for this
f
You may
prefer rto
f
O to decideT between
Need
JdbcTemplate queries and
o
N
JPA (or similar) mappings
o
Some tables may
be too hard to map with JPA
D
21
RowMapper
e
c
r
u
Spring provides a RowMapper interface
for
o
mapping a single row of a ResultSet
to an
S
g
y
object
l
n
i
e
t
Can be used for both r
single and n
multiple row
queries
O
p
u
Parameterized asS
of Spring
3.0
b
g
i
l
r
n
t
i
a
public interfaceiRowMapper<T> { s
n
i
i
c
T mapRow(ResultSet
rs,
int rowNum)
i
a tD
f SQLException;
throws
r
f
T o
O
}
N
o
D
22
e
c
Query for single row with JdbcTemplate
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
Parameterizes return type
a
i
s
n
i
i
c
i
a RowMapper<Person>
D
f implements
r
f
class PersonMapper
{
t
T o rs, int i) throws SQLException {
public O
Person mapRow(ResultSet
N
return new Person(rs.getString("first_name"),
o
rs.getString("last_name"));
D
}
public Person getPerson(int id) {
return jdbcTemplate.queryForObject(
select first_name, last_name from PERSON where id=?,
new PersonMapper(), id);
}
No need to cast
23
e
c
r
u
o
S
y
public List<Person> getAllPersons() { g
l
n
e
n
return jdbcTemplate.query( ri
t
"select first_name, last_name
fromO
PERSON",
p
u
S ng rib
new PersonMapper());
l
t
i
a
i
s
n
i
i
c
class PersonMapper
implements RowMapper<Person> {
i
a trs,Dint i) throws SQLException {
f
public Person
mapRow(ResultSet
r
f
T o
returnO
new Person(rs.getString("first_name"),
N
rs.getString("last_name"));
}
o
D
}
Query for multiple rows
No need to cast
24
RowCallbackHandler
e
c
r
u
Spring provides a simpler RowCallbackHandler
o
interface when there is no S
return object
y
Streaming rows to a file ng
l
i
e
n
r
t
Converting rows to XML
O
p
u
Filtering rows before
adding
to a Collection
b
S
g
i
l
r
n
t
i
a
i
s
n
i
Faster than
JPA
equivalent
for
big queries
i
c
i
a tD
f
r
f
T o
O
public interface RowCallbackHandler
{
N
void processRow(ResultSet
rs) throws SQLException;
o
}
D
but filtering in SQL is much more efficient
25
Using a RowCallbackHandler
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
/* stateful object: may add convenience methods like getResults(), getCount() etc. */
26
ResultSetExtractor
e
c
r
u
Spring provides a ResultSetExtractor
interface for
o
processing an entire ResultSet
at once
S
g
y
You are responsible for iterating
the
ResultSet
l
n
i
e
r
t
e.g. for mapping entire ResultSetnto a single
object
O
p
u
S ng { rib
public interface ResultSetExtractor<T>
l
t
i
a
T extractData(ResultSet
rs)
throws SQLException,
i
s
n
i
i
DataAccessException;
c
i
a tD
f
}
r
f
T o
O
N
o
D
27
Using a ResultSetExtractor
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Summary of Callback
Interfaces
e
c
r
u
RowMapper
o
Best choice when each row ofS
a ResultSet maps to a
g
domain object
y
l
n
i
e
n
t
RowCallbackHandler r
O
p
u
Best choice whenS
no valueg
should be
returned from
b
i
l
n
the callback a
method
for
each rowtr
i
i
s
n
i
i
c
ResultSetExtractor
i
a
D
f
r
f
Best choice when multiple
rows of a ResultSet map to
t
T
O object No
a single
o
D
29
e
c
r
u
Inserting a new row
o
S
g { ly
public int insertPerson(Personn
person)
i
e
n
return jdbcTemplate.update(
r
t
O
p
u
insert into PERSON
(first_name,
last_name,
age) +
S ng rib
values (?, ?, ?),
l
t
i
person.getFirstName(),
a
i
s
n
i
person.getLastName(),
i
c
i
a tD
f
person.getAge());
r
f
T o
}
O
N
o
D
30
e
c
r
u
Updating an existing row
o
S
g
y
public int updateAge(Person person)
{
l
n
i
e
n
return jdbcTemplate.update(
r
t
p
u
update PERSON
set age=?O
where id=?,
S ng rib
person.getAge(),
l
t
i
person.getId());
a
i
s
n
i
}
i
c
i
a tD
f
r
f
T o
O
N
o
D
31
Exception Handling
e
c
r
u
The JdbcTemplate transforms SQLExceptions
o
into DataAccessExceptions S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
...
r
f
T o
O
N
o
D
DataAccessException
CleanupFailure
DataAccessException
DataIntegrity
ViolationException
e
c
r
u
o
S
g
y
l
LAB
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Introduction
to Spring
JDBC
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
o
S
Transaction Management
g
y
l
n
i
e
n
with
Spring
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
An Overview
of Springs
Consistent Approach to
i
a
D
f
r
f
Managing Transactions
t
T
O
o
N
o
D
Copyright2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
Why use Transactions?
o
S
Local Transaction Management
g
y
l
n
Spring Transaction Management
i
e
n
r
t
O
u
Annotations or XMLp
b
S
g
i
l
r
Isolation Levels
n
t
i
a
i
s
n
i
i
Transaction
Propagation
c
i
a
D
f
r
f
t
Rollback rulesT
O
o
Testing
N
o
Advanced topics
D
2
e
c
r
u
Atomic
o
Each unit of work is an all-or-nothing
operation
S
g
y
l
Consistent
n
i
e
n
r
t
Database integrity constraints
are never
violated
O
p
u
S ng rib
Isolated
l
t
i
a
Isolating transactions
from
each
other
i
s
n
i
i
c
i
a tD
Durableff
r
T areo permanent
O changes
Committed
N
o
D
3
Transactions in the
RewardNetwork
e
c
r
u
The rewardAccountFor(Dining) method
represents
o
a unit-of-work that should S
be atomic
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
4
RewardNetwork Atomicity
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Account
Repository
Restaurant
Repository
findByCreditCard(String)
Reward
Repository
Account
Restaurant
1. SELECT
findByMerchantNumber(String)
calculateBenefitFor(Account, Dining)
2. SELECT
makeContribution(MonetaryAmount)
3. UPDATE
updateBeneficiaries(Account)
4. INSERT
confirmReward(AccountContribution, Dining)
DATABASE
Nave Approach:
Connection per Data Access Operation
e
c
r
u
This unit-of-work contains 4 data
access
o
operations
S
g
y
l
Each acquires, uses, and
releases
a distinct
n
i
e
n
r
t
Connection
O
p
u
b
Sis non-transactional
g
The unit-of-work
i
l
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
6
Running non-Transactionally
Reward
Network
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Account
Repository
Restaurant
Repository
Reward
Repository
DataSource
Connection
findByCreditCard(String)
getConnection()
close()
connection-1
findByMerchantNumber(String)
getConnection()
close()
connection-2
updateBeneficiaries(Account)
getConnection()
close()
connection-3
1. SELECT
2. SELECT
3. UPDATE
4. INSERT
confirmReward(AccountContribution, Dining)
getConnection()
close()
connection-4
DATABASE
Partial Failures
e
c
r
u
Suppose an Account is being rewarded
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng riXb
l
t
i
a
i
s
n
i
i
c
The unit-of-work
i
a
D
f
r
f
is not atomic
If the beneficiaries
are tupdated
T
O
o
But the reward confirmation
N
fails
There will be D
noo
record of the reward!
8
Correct Approach:
Connection per Unit-of-Work
e
c
r
u
More efficient
o
Same Connection reused for S
each operation
g
y
l
Operations complete as
an
atomic
unit
n
i
e
n
r
t
Either all succeed or
all fail O
p
u
b
Scan run
g
The unit-of-work
i
in a transaction
l
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
9
Running in a Transaction
TX
Reward
Network
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Account
Repository
Restaurant
Repository
Reward
Repository
getConnection()
DataSource
Connection
connection-1
findByCreditCard(String)
1. SELECT
findByMerchantNumber(String)
updateBeneficiaries(Account)
confirmReward(AccountContribution, Dining)
close()
2. SELECT
3. UPDATE
4. INSERT
DATABASE
10
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
11
Local Transaction
Management
e
c
r
u
Transactions can be managed at
the level of a
o
local resource
S
y
Such as the database ng
l
i
e
n
r
t
Requires programmatic
management
of
O
p
u
b
S nongthe Connection
transactional behavior
i
l
r
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
12
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
13
e
c
r
Connection management code u
is error-prone
o
S
Transaction demarcation belongs
at the service
g
y
l
layer
n
i
e
n
r
t
Multiple data accesspmethods O
may be called
within a
u
transaction
S ng rib
l
Connection must
be managed
at ta higher level
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
14
e
c
r
u
Why use Transactions?
o
S
Local Transaction Management
g
y
l
n
Spring Transaction Management
i
e
n
r
t
O
u
Annotations or XMLp
b
S
g
i
l
r
Isolation Levels
n
t
i
a
i
s
n
i
i
Transaction
Propagation
c
i
a
D
f
r
f
t
Rollback rulesT
O
o
Testing
N
o
Advanced topics
D
15
Spring Transaction
Management
e
c
r
Declarative transactions are theurecommended
o
approach
S
g
y
Spring provides a flexible
and
powerful
abstraction
l
n
i
e
n
layer for transaction management
r
t
O
p
u
There are only 2 S
steps g
b
i
l
r
n
Define a TransactionManager
t
i
a
i
s
n
i
i
c
Declare ithe transactional methods
a tD
f
r
f
T o
O
N
Optimization forolocal transactions
D automatically bound to the
Database connection
Using Annotations, XML, Programmatic
Can mix and match
current thread
16
PlatformTransactionManager
e
c
r
u
Springs PlatformTransactionManager
is the base
o
interface for the abstraction
S
g
y
l
Several implementations
are
available
n
i
e
n
r
t
DataSourceTransactionManager O
p
u
HibernateTransactionManager
S ng rib
l
JpaTransactionManager
t
i
a
i
s
n
i
i
JtaTransactionManager
c
i
a tD
f
r
f
WebLogicJtaTransactionManager
T o
O
WebSphereUowTransactionManager
N
and more
o
D
Spring allows you to configure whether you use JTA or not. It does not
have any impact on your Java classes
17
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
b
S ntoguse custom
i
or for JTA, also possible
tag:
l
r
t
i
a
i
s
n
i
i
c
i
a
D
f
r
f
Resolves to appropriate impl
for environment
t
T
O
o
N
o
D
Pick the specific implementation
<bean id=transactionManager
class=org.springframework.jdbc.datasource.DataSourceTransactionManager>
<property name=dataSource ref=dataSource/>
</bean>
<tx:jta-transaction-manager/>
OC4JJtaTransactionManager
WebLogicJtaTransactionManager
WebSphereUowTransactionManager
JtaTransactionManager
18
@Transactional configuration
using XML
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
In the configuration:
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
In the code:
<tx:annotation-driven/>
<bean id=transactionManager
class=org.springframework.jdbc.datasource.DataSourceTransactionManager>
<property name=dataSource ref=dataSource/>
</bean>
<jdbc:embedded-database id="dataSource"> </jdbc:embedded-database>
19
@Transactional configuration
using Java configuration
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
In the configuration:
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
In the code:
20
e
c
r
u
o
Uses an Around advice
S
g
y
Proxy implements the following
behavior
l
n
i
e
n
r
t
Transaction started before entering the method
O
p
u
Commit at the end
of the method
b
S
g
i
l
r
n
t
Rollback if method
throws
a RuntimeException
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T
O
o
All controlled by configuration
N
o
D
Transactional object wrapped in a proxy
Default behavior
Can be overridden (see later)
Spring Proxy
Reward
NetworkImpl
21
e
c
r
u
o
Purpose
b
S ng Integration
i
l
r
testing
t
i
a
i
s
n
i
Deploy to Tomcat or
i
c
i
a t D other servlet container
f
r
f
T o
O
N
o
D
Spring Proxy
Reward
NetworkImpl
JdbcAccount
Repository
BasicData
Source
How?
JdbcCustomer
Repository
DataSource
Transaction
Manager
<bean id="transactionManager"
class="...DataSourceTransactionManager"> ...
e
c
r
u
o
gS
How?
y
l
n
Use
container-managed
i
e
n
r
t
datasource
(JNDI)
O
p
u
b
S ng JTAriTransaction
Manager
l
t
i
a
i
Purpose
s
n
i
i
c
i
a t D Deploy to JEE container
f
r
f
T o
O
N
o
D
Spring Proxy
Reward
NetworkImpl
JdbcAccount
Repository
JEE
Container
Managed
DataSource
No code changes
Just configuration
JdbcCustomer
Repository
JTA
Transaction
Manager
<tx:jta-transaction-manager/>
23
e
c
r
u
Why use Transactions?
o
S
Local Transaction Management
g
y
l
n
Spring Transaction Management
i
e
n
r
t
O
p
u
Annotations or XML
b
S
g
i
l
r
Isolation Levels
n
t
i
a
i
s
n
i
i
Transaction
Propagation
c
i
a
D
f
r
f
t
Rollback rulesT
O
o
Testing
N
o
Advanced topics
D
24
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Transactional
Class and method levels
e
c
r
u
o
default settings
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
overriding
attributes at
a
i
s
n
theimethod level
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Transactional(timeout=60)
public class RewardNetworkImpl implements RewardNetwork {
26
XML-based Spring
Transactions
e
c
r
u
Cannot always use @Transactional
o
Annotation-driven transactions
require JDK 5
S
g thelyservice (without
Someone else may haven
written
i
e
n
annotations)
r
t
O
p
u
Spring also provides
an option
for
XML
b
S
g
i
l
n
An AOP pointcut
declares
what totr
advise
i
a
i
s
n
i
i
c
Springsitx namespace enables a concise definition of
a tD
f advice
r
f
transactional
T behavior to any class used as a
O
Can add transactional o
N
Spring Bean
o
D
27
Declarative Transactions:
XML
e
cpointcut expression
AspectJ named
r
u
o
S
g
y
l
n
i Method-level
e
n
configuration
r
t
p
u
forO
transactional
advice
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<aop:config>
<aop:pointcut id=rewardNetworkMethods
expression=execution(* rewards.service.*Service.*(..))/>
<aop:advisor pointcut-ref=rewardNetworkMethods advice-ref=txAdvice/>
</aop:config>
<tx:advice id=txAdvice>
<tx:attributes>
<tx:method name="get*" read-only="true" timeout="10"/>
<tx:method name="find*" read-only="true" timeout="10"/>
<tx:method name="*" timeout="30"/>
</tx:attributes>
Includes rewardAccountFor(..) and
</tx:advice>
updateConfirmation(..)
<bean id=transactionManager
class=org.springframework.jdbc.datasource.DataSourceTransactionManager>
<property name=dataSource ref=dataSource/>
</bean>
28
e
c
r
u
Why use Transactions?
o
S
Local Transaction Management
g
y
l
n
Spring Transaction Management
i
e
n
r
t
O
u
Annotations or XMLp
b
S
g
i
l
r
Isolation levels
n
t
i
a
i
s
n
i
i
Transaction
Propagation
c
i
a
D
f
r
f
t
Rollback rulesT
O
o
Testing
N
o
Advanced topics
D
29
Isolation levels
e
c
r
u
o
READ_UNCOMMITTED
S
g
y
READ_COMMITTED
l
n
e
n
REPEATABLE_READ ri
t
p g O bu
SERIALIZABLE S
i
l
r
n sallt isolation levels
Some DBMSsia
do not support
i
n
i
i
c
i
Isolation fis
a complicated
subject
a
D
r
f
t
DBMS
all
have
differences
in the way their isolation
T
O
o
policies have been implemented
N
We just provide o
general guidelines
D
4 isolation levels can be used:
30
Dirty Reads
e
c
r
u
o
S
Transactions
g
y
l
should be
n
i
e
n
r
t
isolated unable
O
p
u
to see the results
S ng rib
l
of another
t
i
a
i
s
n
i
uncommitted ic
i
a tD
r
unit-of-workff
T rollbacko X
O
N
o
D
31
READ_UNCOMMITTED
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
32
READ_COMMITTED
e
c
r
u
o
Only committed information can
be accessed
S
g
y
Default strategy for most
databases
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
33
e
c
r
u
o
Does not allow dirty reads
S
g
y
Non-repeatable reads are prevented
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
SERIALIZABLE
s
n
i
i
c
i
a treads
D and dirty-reads
Prevents
non-repeatable
f
r
f
Also
reads
Oprevents Tphantom
o
N
o
D
REPEATABLE_READ
34
e
c
r
u
Why use Transactions?
o
S
Local Transaction Management
g
y
l
n
Spring Transaction Management
i
e
n
r
t
O
u
Annotations or XMLp
b
S
g
i
l
r
Isolation levels
n
t
i
a
i
s
n
i
i
Transaction
Propagation
c
i
a
D
f
r
f
t
Rollback rulesT
O
o
Testing
N
o
Advanced topics
D
35
Understanding Transaction
Propagation: Example
e
c
r
u
o
S
y
Should everything run into g
a single ltransaction?
n
i its ownntransaction?
e
Should each service have
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Transactional
public void updateClient(Client c)
{ //
this.accountService.update(c.getAccounts());
}
Understanding Transaction
Propagation
e
c
r
u
o
S
B
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Single Transaction
Transaction 1
Transaction 2
Caller
Transaction created,
committed or rolled
back as needed
Transactional method 1
Transactional method 2
37
e
c
r
u
o
S
g
y
l
n
i
e
n
r
Check the documentation for other levels t
O
p
u
S ng rib
Can be used as follows:
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
7 levels of propagation
The following examples show REQUIRED and
REQUIRES_NEW
@Transactional( propagation=Propagation.REQUIRES_NEW )
38
REQUIRED
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
REQUIRED
Default value
Execute within a current transaction, create a new one if
none exists
tx1
no tx
tx1
tx1
@Transactional(propagation=Propagation.REQUIRED)
39
REQUIRES_NEW
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
REQUIRES_NEW
no tx
tx1
tx1
tx2
@Transactional(propagation=Propagation.REQUIRES_NEW)
40
e
c
r
u
Why use Transactions?
o
S
Local Transaction Management
g
y
l
n
Spring Transaction Management
i
e
n
r
t
O
u
Annotations or XMLp
b
S
g
i
l
r
Isolation Levels
n
t
i
a
i
s
n
i
i
Transaction
Propagation
c
i
a
D
f
r
f
t
Rollback rules
T
O
o
Testing
N
o
Advanced topics
D
41
Default behavior
e
c
r
u
o
S
g
y
Could be any kind of RuntimeException:
l
n
i
e
n
DataAccessException, r
HibernateException
etc.
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Triggers a rollback
42
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Transactional(rollbackFor=MyCheckedException.class)
public void updateConfirmation(Confirmation c) throws MyCheckedException {
// ...
}
@Transactional(noRollbackFor={JmxException.class, MailException.class})
public RewardConfirmation rewardAccountFor(Dining d) {
// ...
}
}
43
e
c
r
u
Why use Transactions?
o
S
Local Transaction Management
g
y
l
n
Spring Transaction Management
i
e
n
r
t
O
u
Annotations or XMLp
b
S
g
i
l
r
Isolation Levels
n
t
i
a
i
s
n
i
i
Transaction
Propagation
c
i
a
D
f
r
f
t
Rollback rulesT
O
o
Testing
N
o
Advanced topics
D
44
@Transactional in an
Integration Test
e
c
r
u
o
S
g
y
l
n
i databasenafter testing!
e
No need to clean up your
r
t
O
p
u
S ng rib
@ContextConfiguration(locations={"/rewards-config.xml"})
l
t
i
a
@RunWith(SpringJUnit4ClassRunner.class)
i
s
n
i
i
c
i
public class f
RewardNetworkTest
{D
a
r
f
t
T
O
o
N
o
D
@Test @Transactional
public void testRewardAccountFor() {
...
}
}
45
Advanced use of
@Transactional in a Unit Test
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Inside @TransactionConfiguration,
no need to specify the
@ContextConfiguration(locations={"/rewards-config.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@TransactionConfiguration(defaultRollback=false, transactionManager="txMgr")
@Transactional
Transactions does a commit at the
public class RewardNetworkTest {
end by default
@Test
Overrides default rollback settings
@Rollback(true)
public void testRewardAccountFor() {
...
}
}
@Before vs @BeforeTransaction
e
c
r
u
o
S
g
y
starts
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
and
work in the same way as
@ContextConfiguration(locations={"/rewards-config.xml"})
@Before runs in the transaction
@RunWith(SpringJUnit4ClassRunner.class)
public
class RewardNetworkTest { runs before the transaction
@BeforeTransaction
Run before transaction is started
@BeforeTransaction
public void verifyInitialDatabaseState() {}
@Before
public void setUpTestDataInTransaction() {}
@Test @Transactional
public void testRewardAccountFor() {
...
}
@After
@AfterTransaction
and @BeforeTransaction
@Before
47
e
c
r
LAB ou
S
g
y
Managing Transactions Declaratively
with Spring
l
n
i
e
n
Annotations
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Copyright2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Advanced topics
e
c
Programmatic transactions
Read-only transactions
Multiple transaction managers
Distributed transactions
49
e
c
r
u
Declarative transaction management
is highly
o
recommended
S
g
y
Clean code
l
n
i
e
n
t
Flexible configuration r
O
p
u
b
S programmatic
Spring does enable
transaction
g
i
l
n str manager
Works with ilocal
a
or JTAi transaction
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Can be useful inside
a technical framework that would not rely on
external configuration
50
Programmatic Transactions:
example
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
No longer
public RewardConfirmation rewardAccountFor(Dining dining) {
@Transactional
...
txTemplate = new TransactionTemplate(txManager);
return txTemplate.execute(new TransactionCallback() {
public Object doInTransaction(TransactionStatus status) {
try {
...
accountRepository.updateBeneficiaries(account);
confirmation = rewardRepository.confirmReward(contribution, dining);
}
catch (RewardException e) {
status.setRollbackOnly();
confirmation = new RewardFailure();
}
return confirmation;
Method no longer throws exception
}
automatic rollback not possible
});
Must force rollback manually
}
51
e
c
r
u
o
S
y
Performance: allows Springg
to optimize
the
l
n
i read-only
e
n
transactional resource r
for
data access
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
2 connections
1 single connection
52
e
c
r
u
o
S
g
Isolation: with a high isolation
level,ly
a readOnly
n
i from being
e
n
transaction prevents data
modified
until the
r
t
O
u
transaction commitsp
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Transactional(readOnly=true, isolation=Isolation.READ_COMMITTED)
public void rewardAccount2() {
jdbcTemplate.queryForList();
jdbcTemplate.queryForInt();
}
53
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Uses "transactionManager"
bean by default
54
Distributed transactions
e
c
r
u
o
2 different databases
S
g
y
1 database and 1 JMS queue
l
n
i
e
n
r
t
O
p
u
Distributed transactions
often
require
specific
b
S
g
i
l
r
n
drivers (XA drivers)
t
i
a
i
s
n
i
i
c
i
In Java, Distributed
transactions
often rely on
a
D
f
r
JTA Of
T ot
Java Transaction API
N
o
D
55
Distributed transactions
Spring integration
e
c
r
u
o
Spring allows you to switch easily
from a non-JTA to a
S
JTA transaction policy
g
y
l
n
ithe transaction
e
n
Just change the type of
manager
r
t
O
p
u
Reference:
b
S
g
i
l
r
n
Distributed transactions
with Spring,
with and without
t
i
a
i
s
XA (Dr. Dave
Syer) in
i
c
i
a tD
f
http://www.javaworld.com/javaworld/jw-01-2009/jwr
f
T o
01-spring-transactions.html
O
N
o
D
56
e
c
r
u
o
S
g
y
l
ORM with Spring
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Object Relational n
Mapping with
s
i
i
c
i
aPersistence
D
f
Spring
and Java
API
r
f
t
T
O
o
N
o
D
Copyright2006-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
Introduction to JPA
o
General Concepts
S
g
y
Mapping
l
n
i
e
n
r
t
Querying
O
p
u
b
S ng inriSpring
Configuring an EntityManager
l
t
i
a
Implementing
JPA DAOs
i
s
n
i
i
c
i
a tD
f
Exception
Translation
r
f
T o
Lab O
N
Spring Data - JPA
o
D
2
Introduction to JPA
e
c
r
u
o
S
y
Defined as POJO entities g
l
n
i
e
n
No special interface required
r
t
p g O mechanisms
u
Replaces previousSpersistence
b
i
l
r
n
EJB Entity Beans
t
i
a
i
s
n
i
Java Datac
Objects (JDO)
i
i
aobject-relational
D
f
A common
API for
mapping
r
f
t
O from Tthe experience
o
Derived
of existing products such
N Oracle TopLink
as JBoss Hibernate and
o
D
About JPA
e
c
r
u
o
Released May 2006
S
y
Version 2 since Dec 2009 g
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Key Concepts
s
n
i
i
c
fi ra t D
Entity fManager
Entity
O ManagerTFactory
o
Persistence ContextN
o
D
Java Persistence API
e
c
r
u
o
S y
Manages a unit of work andg
persistent
l
objects therein: the PersistenceContext
n
i
e
n
r
t
Lifecycle often bound
to a Transaction
O
p
u
(i.e. container-managed)
S ng rib
l
t
i
a
i
s
n
i
i
c
EntityManagerFactory
i
a tD
f
r
f
T
O
o
thread-safe, shareable
object that represents a single
N
data source / persistence
unit
o
Provides access
Dto new application-managed
EntityManager
EntityManagers
e
c
r
u
Describes a group of persistent classes
(entities)
o
Defines provider(s)
S
g
y
Defines transactional types
(local
vs lJTA)
n
i
e
n
r
t
Multiple Units per application are
allowed
O
p
u
S ng rib
l
t
In a Spring JPA
application
i
a
i
s
n
i
i
c
The configuration
can be in the Persistence Unit
i
a
D
f
r
f
Or in the Spring
bean-file t
T
O
o
Or a combination of the
N two
o
D
Persistence Unit
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
creates
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
persist(Object o)
remove(Object o)
flush()
JPA Providers
e
c
r
spec
u
Several major implementations of JPA
o
Hibernate EntityManager
S
g
Used inside JBoss
y
l
n
i
e
n
EclipseLink (RI)
r
t
O
p
u
S ng rib
Apache OpenJPA
l
t
i
a
i
s
n
i
i
c
i
Data Nucleus
a tD
f
r
f
T o
O
N
application server as well
Can all be used without
o
D
Used inside Glassfish
Hibernate JPA
e
c
r
u
Hibernate adds JPA support through
an
o
additional library
S
g
y
The Hibernate EntityManager
l
n
i
e
n
r
t
Hibernate sessions used behind JPA
interfaces
O
p
u
Custom annotations
for Hibernate
specific
extensions
b
S
g
i
r
n
not covered a
bylJPA
t
i
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
less important since JPA
version 2
JPA
API
Hibernate
Implementation
10
JPA Mapping
e
c
r
u
o
S
Usually provided as annotations
g
y
l
n
XML mappings also supported
(orm.xml)
i
e
n
r
t
O
p
u
S onndefaults
g trib
JPA metadata relies
l
i
a
No need to iprovide
metadata
for
the obvious
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
11
e
c
r
u
Applies to the entire class (such as
table properties)
o
S
Fields
g
y
l
Typically mapped to a column
n
i
e
n
r
t
By default, all treatedpas persistent
O
u
S ng rib
l
t
i
a
i
s
n
i
c
Accessed idirectly
viaiReflection
a tD
f (getters)
r
f
Properties
T
O
o
Also mapped to a column
N
Annotate getters o
instead of fields
D
Classes
12
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
Data members set directly
N
o
D
@Entity
@Entity
@Table(name=
@Table(name= T_CUSTOMER)
T_CUSTOMER)
public
public class
class Customer
Customer {{
@Id
@Id
@Column
@Column (name=cust_id)
(name=cust_id)
private
private Long
Long id;
id;
Mark as an entity
Optionally override
table name
@Column
@Column (name=first_name)
(name=first_name)
private
private String
String firstName;
firstName;
Optionally override
column names
@Transient
@Transient
private
private User
User currentUser;
currentUser;
...
...
Mark id-field
(primary key)
13
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Entity
@Entity @Table(name=
@Table(name= T_CUSTOMER)
T_CUSTOMER)
public
public class
class Customer
Customer {{
private
private Long
Long id;
id;
private
private String
String firstName;
firstName;
@Id
@Id
@Column
@Column (name=cust_id)
(name=cust_id)
public
public String
String getId()
getId()
{{ return
return this.id;
this.id; }}
Beware of Side-Effects
getter/setter methods
may do additional work
such as invoking listeners
@Column
@Column (name=first_name)
(name=first_name)
public
public String
String getFirstName()
getFirstName()
{{ return
return this.firstName;
this.firstName; }}
public
public void
void setFirstName(String
setFirstName(String fn)
fn)
{{ this.firstName
this.firstName == fn;
fn; }}
}}
14
Relationships
e
c
r
Common relationship mappingsusupported
o
Single entities and entity collections
both supported
S
y
Associations can be uni- n
org
bi-directional
l
i
e
n
r
t
@Entity
O
p
u
b
@Table(name= T_CUSTOMER)
S
g
i
l
r
n
public class Customer
{
t
i
a
i
s
@Id
n
Propagate
all operations
i
i
c
i
a
@Column (name=cust_id)
D
f
to the child objects
r
f
t
privateO
Long id; T
o
N
@OneToMany(cascade=CascadeType.ALL)
o
@JoinColumn (name=cust_id)
D
private Set<Address> addresses;
Foreign key in
Address table
Embeddables
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N classes
Map a table row to multiple
o
columns in T_CUSTOMER
Address fields also
D
@AttributeOverride overrides mapped column name
@Entity
@Table(name= T_CUSTOMER)
public class Customer {
@Id
@Column (name=cust_id)
private Long id;
@Embeddable
public class Address {
private String street;
private String suburb;
private String city;
private String postcode;
private String country;
}
@Embedded
@AttributeOverride
(name="postcode", column=@Column(name="ZIP"))
private Address office;
maps to ZIP
column in
T_CUSTOMER
16
JPA Querying
e
c
r
u
o
Retrieve an object by primaryS
key
y
Query for objects using JPAg
Query Language
(JPQL)
l
n
i
e
n
r
t
O
p
u
Query for objects using
Criteria Queries
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a to underlying
D
f
Execute
SQL
directly
database
r
f
t
T o
O
N
o
D
17
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
returns null
if no object
exists for the identifier
s
n
i
i
c
i
a tD
f
r
f
O JPAT usesNgenerics
o
No cast required
o
D
18
e
c
r
u
To query for objects based on properties
or
o
associations use JPQL
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
.
T o
O
N
o
D
e
c
r
u
Criteria Query API (JPA 2)
o
Build type safe queries: fewerSrun-time errors
g
y
Much more verbose
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Meta-data class
created by JPA
(note underscore)
20
e
c
r
u
Use a native query to execute raw
SQL
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
21
e
c
r
u
Introduction to JPA
o
General Concepts
S
g
y
Mapping
l
n
i
e
n
r
t
Querying
O
p
u
b
Configuring an S
EntityManager
in Spring
g
i
l
r
n
t
i
a
Implementing
JPA DAOs
i
s
n
i
i
c
i
a tD
f
Exception
Translation
r
f
T o
Lab O
N
Spring Data - JPA
o
D
22
Setting up an
EntityManagerFactory
e
c
r
u
o
LocalEntityManagerFactoryBean
S
g
y
LocalContainerEntityManagerFactoryBean
l
n
i
e
n
Use a JNDI lookup
r
t
O
p
u
b
S
g
i
l
r
persistence.xml
n
required
for configuration
t
i
a
i
s
n
i
i
Spring 3.1
c
allows
no
persistence.xml
with
i
a tD
f
r
f
LocalContainerEntityManagerFactoryBean
T o
O
N
o
D
23
persistence.xml
e
c
r
u
Always stored in META-INF
o
S
Specifies:
g
y
l
persistence unit
n
i
e
n
r
t
optional vendor-dependent
information
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="rewardNetwork"/>
</persistence>
24
LocalEntityManagerFactoryBean
e
c
r
u
o
S
g
y
Useful when only data access
is via lJPA
n
i locationn(SPI) mechanism
e
Uses standard JPA service
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
/META-INF/services/javax.persistence.spi.PersistenceProvider
<bean id="entityManagerFactory"
class="o.s.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName"
value="rewardNetwork"/>
</bean>
25
LocalContainer
EntityManagerFactoryBean
e
c
r
u
o
S
g
y
l
n
i configuration
e
n
Can specify vendor-specific
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
26
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="persistenceUnitName" value="rewardNetwork"/>
<property name="jpaVendorAdapter">
<bean class="org.sfwk.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true"/>
<property name="generateDdl" value="true"/>
<property name="database" value="HSQL"/>
</bean>
<persistence version="1.0" ...>
</property>
<persistence-unit name="rewardNetwork"/>
<property name="jpaProperties"> </persistence>
<props>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
NOTE: no persistence.xml needed when using new
</bean>
packagesToScan property in Spring 3.1
27
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="persistenceUnitName" value=rewardNetwork"/>
</property>
</bean>
<persistence-unit name="rewardNetwork">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect"
value="org.hibernate.dialect.HSQLDialect"/>
<property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
If using JTA declare <jta-data-source> in the persistence-unit
28
EntityManagerFactoryBeans
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
persistence.xml
O
N
o
D
This is hidden
inside Spring
DataSource
LocalContainer
EntityManager
FactoryBean
creates
Entity Manager
Factory
creates
OrderServiceImpl
JPA
OrderRepository
EntityManager
Spring Proxy
29
JNDI Lookups
e
c
r
u
A jee:jndi-lookup can be used to
retrieve
o
EntityManagerFactory fromS
application server
g
y e
l
Useful when deployingin
to JEE Application
n
r
t
Servers (WebSphere,
WebLogic,
etc.)
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
<jee:jndi-lookup
id="entityManagerFactory"
i
a tD
f
r
f
jndi-name="persistence/rewardNetwork"/>
T o
O
N
o
D
30
e
c
r
u
Introduction to JPA
o
General Concepts
S
g
y
Mapping
l
n
i
e
n
r
t
Querying
O
p
u
b
S ng inriSpring
Configuring an EntityManager
l
t
i
a
Implementing
JPA
DAOs
i
s
n
i
i
c
i
a tD
f
Exception
Translation
r
f
T o
O
N
o
D
31
e
c
r
u
JPA provides configuration options
so Spring
o
can manage transactions and
the
S
g
y
EntityManager
l
n
i
e
n
r
t
O
p
u
Use AOP for transparent
exception
translation
b
S
g
i
l
r
n
to Springs DataAccessException
hierarchy
t
i
a
i
s
n
i
i
c
i
a dependencies
D
f
r
f
There are
no Spring
in your DAO
t
T o
O
implementations
N
o
D
32
Spring-managed Transactions
and EntityManager (1)
e
c
r
u
To transparently participate in Spring-driven
o
transactions
S
g
y
FactoryBeans
for building
Simply use one of Springs
l
n
i
e
n
the EntityManagerFactory
r
t
O
p
u
Inject an EntityManager
reference
with
b
S
g
i
l
@PersistenceContext n
r
t
i
a
i
s
n
i
Define a transaction
manager
i
c
i
a tD
f
JpaTransactionManager
r
f
T o
O
JtaTransactionManager
N
o
D
33
Spring-managed Transactions
and EntityManager (2)
e
c
r
u
The code no Spring dependencies
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
public class JpaOrderRepository implements OrderRepository {
private EntityManager entityManager;
@PersistenceContext
public void setEntityManager (EntityManager entityManager) {
this. entityManager = entityManager;
}
34
Spring-managed Transactions
and EntityManager (3)
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
The configuration
<beans>
<bean id=entityManagerFactory
class=org...orm.jpa.LocalContainerEntityManagerFactoryBean>
...
</bean>
Automatic injection of entity-manager proxy
<bean id=orderRepository class=JpaOrderRepository/>
<bean id= transactionManager
class=org.springframework.orm.jpa.JpaTransactionManager>
<property name=entityManagerFactory ref=entityManagerFactory />
</bean>
Provides injection via @PersistenceContext
<context:annotation-config/>
</beans>
35
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Spring AOP Proxy
invoke(input)
Service
proxy handles
transaction
e
c
create entity
manager
EntityManager
Factory
Spring
Hibernate
TransactionInterceptor
OrderRepository
begin
commit
OrderServiceImpl
get order
data
JpaTransactionManager
begin
txn
commit
txn
Entity
Manager
(EM)
Repository's EM
proxy gets EM
for current thread
OrderRepository
find order
get EM
36
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Spring
Hibernate
TransactionInterceptor
OrderRepository
Service
proxy handles
transaction begin
OrderServiceImpl
commit
get order
data
JtaTransaction
Manager
begin
txn
JTA
commit
txn
join
txn
Proxy gets EM
for current txn
OrderRepository
find
order
Entity
Manager
(EM)
create
get EM
EntityManager
Factory
37
e
c
r
u
Introduction to JPA
o
General Concepts
S
g
y
Mapping
l
n
i
e
n
r
t
Querying
O
p
u
b
S ng inriSpring
Configuring an EntityManager
l
t
i
a
Implementing
JPA DAOs
i
s
n
i
i
c
i
a tD
f
Exception
Translation
r
f
T o
Lab O
N
Spring Data - JPA
o
D
38
Transparent Exception
Translation (1)
e
c
r
u
Used as-is, the previous DAO implementation
o
will throw unchecked PersistenceExceptions
S
g lyup to the service
Not desirable to let thesenpropagate
i DAOsn te
layer or other users ofrthe
O
p
u
Introduces dependency
on
the
specific
persistence
b
S
g
i
l
solution that should
notn
exist
r
t
i
a
i
s
n
i
i
c
i
a ttoDSprings rich, vendorf
AOP allows
translation
r
f
T o
O DataAccessException
neutral
hierarchy
N
Hides access technology used
o
D
39
Transparent Exception
Translation (2)
e
c
r
u
o
Annotate with @Repository
S
g
Define a Spring-provided BeanPostProcessor
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Repository
public class JpaOrderRepository implements OrderRepository {
...
}
<bean class=org.springframework.dao.annotation.
PersistenceExceptionTranslationPostProcessor/>
40
Transparent Exception
Translation (3)
e
c
r
Can't always use annotations u
o
For example with a third-party
repository
S
g
y
Use XML to configure instead
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<aop:config>
<aop:advisor pointcut=execution(* *..OrderRepository+.*(..))
advice-ref=persistenceExceptionInterceptor />
</aop:config>
41
Features in JPA 2
e
c
r
u
o
Compound keys: @IdClass S
g
y
Nested embeddables
l
n
i and primitives
e
n
Collections of non-entities
r
t
p g O bu
Support for mapsS
and lists in relationships
i
l
r
Fewer limitations
n
t
i
a
i
s
n
i
Criteria and
type-safe
query API
i
c
i
a t D@Access
f
r
f
ORM specific
getters/setters:
T o and @JoinColumn
FullO
support for @JoinTable
N
Locking modes: o
Optimistic and Pessimistic
Supports JSR D
303 validation: @NotNull, @Max ...
Improved mappings
42
e
c
r
u
o
S
g
y
l
LAB
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Using JPA
with Spring
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Copyright2006-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
Introduction to JPA
o
General Concepts
S
g
y
Mapping
l
n
i
e
n
r
t
Querying
O
p
u
b
S ng inriSpring
Configuring an EntityManager
l
t
i
a
Implementing
JPA DAOs
i
s
n
i
i
c
i
a tD
f
Exception
Translation
r
f
T o
Lab O
N
Spring Data - JPA
o
D
44
e
c
r
u
o
Works in many environments S
g
y
l
n
i
e
n
r
t
Core
project
SpringpData O
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
Sub-projects
N
o
D
JPA
Apache
Hadoop
vFabric
Gemfire
REST
MongoDB
JDBC
extensions
45
Instant Repositories
e
c
r
How?
u
o
Annotate domain classes suitably
to define keys and
S
g
enable persistence
y
l
n
i an interface
e
n
Define your repository r
as
t
O
p
u
Spring will implement
it
at
run-time
b
S
g
i
l
r
Scans for interfaces implementing
Repository
<T, K>
n
t
i
a
i
s
n
CRUD methods
auto-generated
i
i
c
i
a and
D
f
Paging,
custom queries
sorting supported
r
f
t
O existTfor most
o
Variations
Spring Data sub-projects
N
o
D
<jpa:repositories base-package="com.acme.**.repository" />
e
c
r
u
o
Spring Data defines similar annotations
for other
S
storage products
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Document
public class Customer {
@Entity @Table(...)
...
public class Customer {
MongoDB map to
@Id
a JSON document
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Date firstOrderDate;
private String email;
// Other data-members
}
@Region
public class Customer {
...
Gemfire map to a
region
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
PagingAndSortingRepository<T, K>
- adds Iterable<T> findAll(Sort)
- adds Page<T> findAll(Pageable)
48
e
c
r
u
o
findBy<DataMember><Op> S
g
y
<Op> can be Gt, Lt, Ne, Between,
Like
etc
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
ID
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
50
Internal behavior
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
$Proxy1
a
i
s
n
i
i
c
i
a
D
f
r
f
t
<jpa:repositories base-package="com.acme.repository"/>
T
O
o
N
o
D
Before startup
Interface
UserRepository
After startup
Interface
UserRepository
implements
51
Summary
e
c
r
u
o
Repositories have no Spring dependency
S
g
y
l
n
i JPA entity-manager
e
n
Use Spring to configure
r
t
O
p
u
factory
b
S
g
i
l
r
Smart proxy a
works within
Spring-driven
transactions
t
i
s
n
i
Optional translation
to
DataAccessExceptions
i
c
i
a tD
f
r
f
T
O
o
Spring-Hibernate 3 day N
in-depth JPA and Hibernate course
emphasis on Hibernate,
but many JPA features used also
o
D
52
e
c
r
u
o
S
g lyWeb
Overview ofinSpring
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
Developing
modern
web iapplications
i
c
i
awith Spring
D
f
r
f
t
T
O
o
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
Introduction
o
S
Using Spring in Web Applications
g
y
l
n
i
Overview of Spring Web
e
n
r
t
O bu
p frameworks
Spring and otherS
Web
g
i
l
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
2
e
c
r
u
o
Spring MVC, Spring WebFlow...
S
g
y
l
n
i
e
n
r
t
However, you are free
to use
Springuwith any
O
p
S ng rib
Java web framework
l
t
i
a
Integration might
be provided
by
Spring or by the
i
s
n
i
i
c
other framework
itself
i
a tD
f
r
f
T o
O
N
o
D
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
Web
Layer
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a
D
f
r
f
Application Layer
t
T
O
o
(Spring)
N
o
D
Clients
JVM
e
c
r
u
Introduction
o
S
Using Spring in Web Applications
g
y
l
n
i
Overview of Spring Web
e
n
r
t
O bu
p frameworks
Spring and otherS
Web
g
i
l
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
5
e
c
r
u
Spring can be initialized within
a webapp
o
S y etc.
start up business services, g
repositories,
l
n
i
e
n
r
t
Uses a standard servlet
listener
O
p
u
b
S before
initialization occurs
any servlets
execute
g
i
l
r
n requests
t
i
a
application iready
for user
s
n
i
i
c
i
ApplicationContext.close()
is called when the
a
D
f
r
f
application
isT
stopped
t
O
o
N
o
D
6
Configuration in web.xml
e
c
r
u
o
<context-param>
S
g
<param-name>contextConfigLocation</param-name>
y
l
n
i
<param-value>
e
n
r
t
/WEB-INF/merchant-reporting-webapp-config.xml
O
p
u
b
S
</param-value>
g
i
l
r
n
</context-param> a
t
i
i
s
n
i
i
c
a
<listener> fi
D
r
f
t
<listener-class>
T
O
o
org.springframework.web.context.ContextLoaderListener
N
</listener-class>
o
</listener>
D
web.xml
Configuration Options
e
c
Default resource location is document-root
r
Can use classpath: designator ou
S
Defaults to WEB-INF/applicationContext.xml
g
y
l
n
Can optionally select profile
ton
use
i
e
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:/rewards/internal/application-config.xml
/WEB-INF/merchant-reporting-webapp-config.xml
</param-value>
</context-param>
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>web</param-value>
</context-param>
web.xml
8
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Servlet Context
Root ApplicationContext
Bound in ServletContext
under a well-known name
Now accessible to
any Servlet or other
web-layer artifact
JVM
WebApplicationContextUtils
e
c
r
u
o
Provides access to the Spring ApplicationContext
S
Spring retrieves the ApplicationContext
from the
g
y
l
n
ServletContext
i
e
n
r
t
O
p
u
S = ...;ng rib
ServletContext servletContext
l
t
i
a
i
s
n
i
i
c
ApplicationContext
context
=
WebApplicationContextUtils.
i
a tD
f
getRequiredWebApplicationContext(servletContext);
r
f
T o
O
N
o
D
10
WebApplicationContextUtils (2)
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
11
Dependency injection
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Autowired
public TopSpendersReportController(ClientService service) {
this.clientService = service;
}
Dependency is automatically injected by type
12
Dependency injection
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Autowired
public TopSpendersReportController(ClientService service) {
this.clientService = service;
}
Dependency is automatically injected by type
13
e
c
r
u
Introduction
o
S
Using Spring in Web Applications
g
y
l
n
Overview of SpringriWeb n
e
t
O bu
p frameworks
Spring and otherS
Web
g
i
l
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
14
Spring Web
e
c
r
u
o
Web framework bundled with S
Spring
g
y
Spring WebFlow
l
n
i
e
n
r
t
Plugs into Spring MVC
O
p
u
Implements navigation
flows
b
S
g
i
l
r
n
t
i
a
Spring BlazeDS
Integration s
i
n
i
i
c
i
Integration
between
Adobe
Flex
clients and Spring
a
D
f
r
f
t
applications
T
O
o
N
o
D
Spring MVC
15
e
c
r
u
Springs web framework
o
Uses Spring for its own configuration
S
g
y
Controllers are Spring beans
l
n
i
e
n
r
t
testable artifacts
O
p
u
b
Smodel
Annotation-based
since Spring
2.5
g
i
l
r
n
t
i
a
Builds on the
Java Servlet
API
i
s
n
i
i
c
i
A parallel
Portlet a
version isD
also provided
f
r
f
t
T
The core
developing web
O platform for
o
N
applications with Spring
o
All higher-level
Dmodules such as WebFlow build on it
16
e
c
r
u
Plugs into Spring Web MVC as
a
Controller
o
technology for implementing
stateful "flows"
S
g
y
l
Checks that users follow
the right
navigation path
n
i
e
n
r
t
Manages back button
and multiple
windows
issues
O
p
u
b
Sbeyond
g
Provides scopes
request iand
session
l
r
n
t
i
a
such asithe flownand flashsscope
i
i
c
i
Addresses
a t D problem elegantly
f therdouble-submit
f
T o
O
N
o
D
17
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<flow ...>
<view-state id="enterPassengerInfo">
<transition on="findItinerary to=reviewItinerary" />
</view-state>
<view-state id="reviewItinerary">
<transition on="viewSeat" to="chooseSeat" />
<transition on="accept" to="finish" />
</view-state>
<view-state id="chooseSeat">
<transition on="findSeat" to="finish" />
</view-state>
enterPassengerInfo
findItinerary
reviewItinerary
viewSeat
accept
chooseSeat
findSeat
finish
<end-state id="finish"/>
</flow>
18
e
c
r
u
o
S
g
Sample applications can be
downloaded
here:
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Online sample application is available here:
http://richweb.springframework.org/swf-booking-faces/spring/intro
http://www.springsource.org/webflow-samples
19
e
c
r
u
Introduction
o
S
Using Spring in Web Applications
g
y
l
n
i
Overview of Spring Web
e
n
r
t
O
p
u
Spring and other
Web
frameworks
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
20
e
c
r
u
o
Inherit from ActionSupport instead
of Action
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Provided by the
Spring framework
}
}
This is one of the 2 ways to integrate Spring and Struts 1 together. More
info in the reference documentation
21
e
c
r
u
o
Spring-centric integration
S
g
y
l
n
e
n
JSF-centric integrationri
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Two options
<managed-bean>
<managed-bean-name>userList</managed-bean-name>
<managed-bean-class>com.springsource.web.ClientController</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
<managed-property>
<property-name>userManager</property-name>
<value>#{userManager}</value>
</managed-property>
</managed-bean>
JSF-centric integration
22
e
c
r
u
o
provides a Spring plugin
S
http://struts.apache.org/2.0.8/docs/spring-plugin.html
g
y
l
n
i
e
n
Wicket
r
t
O
p
u
Comes with an integration
to
Spring
b
S
g
i
l
r
n
http://cwiki.apache.org/WICKET/spring.html
t
i
a
i
s
n
i
i
c
Tapestry 5i
a
D
f
r
f
t
Comes with an
integration
to Spring
T
O
o
http://tapestry.apache.org/tapestry5/tapestry-spring/
N
o
D
Struts 2
23
Summary
e
c
r
u
o
Spring provides the ContextLoaderListener
that can be
S
declared in web.xml
g
y
l
n
i webn framework
e
Spring MVC is a lightweight
r
t
Obeansbu
p Spring
where controllersS
are
g
i
l
r
n
More about Spring
MVCiin
the next
module
t
a
i
s
n
i
i
c
WebFlow plugs
into
Spring MVC as a Controller
i
a
D
f
r
f
technology forT
implementing
stateful "flows"
t
O
o
N
o
D
24
e
c
r
u
o
S
g
y
l
Spring Web MVC
Essentials
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Getting started
with Spring
Web MVC
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
Request Processing Lifecycle
o
S
g
y
l
Key Artifacts
n
i
e
n
r
t
DispatcherServlet p
O
u
S ng rib
Handlers
l
t
i
a
Views
i
s
n
i
i
c
i
a
D
f
r
f
t
Quick
Start
T
O
o
N
o
D
2
e
c
r
Web request handling is ratheru
simple
o
Based on an incoming URL... S
g
y
...we need to call a method...
l
n
i value (ifnany)... te
r
...after which the return
O
p
u
...needs to be rendered
using
a viewb
S
g
i
l
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
3
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Incoming Request
Handle
Request
Delegate request
Front
Controller
Model
Return Response
Model
Return control
Delegate
rendering of
response
Render response
Controller
Create Model
View Template
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Spring @MVC Configuration Types
Generic Configuration
Configuration at the
Controller level
@Controller
annotated classes
e
c
r
u
o
S
Spring configuration
g
y
l
n
i insidenweb.xmlte
r
O
p
u
S ng rib
l
i
a
Spring tconfiguration also
i
s
n
i
i
c
inside
web.xml if part of
i
a t aDweb application
f
r
f
T
O
o
Two options:
N
o
Separate configurations
or All-In-One
D
How does Spring @MVC interact with Spring
Spring @MVC
Back-end
Application
(using Spring)
1. Separate Configurations
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/app-config.xml</param-value>
</context-param>
<listener> <listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class> </listener>
Back-end
<servlet>
<servlet-name>main</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
Spring
<init-param>
<param-name>contextConfigLocation</param-name>
@MVC
<param-value>/WEB-INF/spring/web-config.xml</param-value>
</init-param>
</servlet>
<servlet-mapping></servlet-mapping>
web.xml
2. All-In-One Alternative
e
c
r
u
o
S
g
is the only entry
Works well if the MVC DispatcherServlet
y
l
n
i
point to Spring
e
n
r
t
O
p
u
No need for the ContextLoaderListener
S ng rib
l
t
i
a
i
DispatcherServlet
configuration
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Controllers
Transactions
Data access
...
2. All-In-One Example
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<servlet>
<servlet-name>main</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
Spring @MVC
<param-value>
/WEB-INF/spring/web-config.xml
/WEB-INF/spring/application-config.xml
</param-value>
</init-param>
</servlet>
Back-end
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>/main/*</url-pattern>
</servlet-mapping>
web.xml
2. All-In-One Limitation
e
c
r
u
o
For example, you want Web Services
as well
S
g
y
Use the separate configuration
approach
(option 1)
l
n
ishared bynboth servlets
e
Root application context
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Spring @MVC
DispatcherServlet
WebServices Servlet
Back-end Application
(using Spring)
10
1 or 2: Configuration Options
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<servlet>
<servlet-name>main</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
Wildcards are accepted
/WEB-INF/spring/*-beans.xml
classpath:com/springsource/application-config.xml
</param-value>
</init-param>
</servlet>
Can use the classpath prefix
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>/main/*</url-pattern>
</servlet-mapping>
11
e
c
r
Request Processing Lifecycle u
o
S
g
y
l
Key Artifacts
n
i
e
n
r
t
DispatcherServlet p
O
u
S ng rib
Handlers
l
t
i
a
Views
i
s
n
i
i
c
i
a
D
f
r
f
t
Quick
Start
T
O
o
N
o
D
12
DispatcherServlet:
The Heart of Spring Web MVC
e
c
r
u
coordinates all request handlingo
activities
S
/ JSF
FacesServlet
analogous to Struts ActionServlet
g
y
l
n
i
e
n
r
t
O
Delegates to Web infrastructure
beans
p
u
S ng rib
l
t
i
a
i
s
Invokes user
Web icomponents
n
i
c
i
a tD
f
r
f
T
FullyO
customizable o
N
interfaces for allo
infrastructure beans
many extension
D points
A front controller
13
DispatcherServlet
Configuration
e
c
r
u
o
S
Uses Spring for its configuration
g
y
l
n
i + dependency
programming to interfaces
injection
e
n
r
t
u
easy to swap parts p
in and outO
S ng rib
l
t
i
a
i
s
Creates separate
servlet
application
context
n
i
i
c
i
a tot DispatcherServlet
D
f
configuration
isrprivate
f
T o
O
N root context
Full access to the parent
o
Option 1
instantiated via
ContextLoaderListener
D
shared across servlets
Defined in web.xml
14
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
child
u
S ng rib
l
t
parent
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
Option 1: Separate
D
Configurations
DispatcherServlet Application
Context
Application Layer
Context:
Business Services,
Repositories, etc.
15
e
c
r
Request Processing Lifecycle u
o
S
g
y
l
Key Artifacts
n
i
e
n
r
t
DispatcherServlet p
O
u
S ng rib
Handlers
l
t
i
a
Views
i
s
n
i
i
c
i
a
D
f
r
f
t
Quick
Start
T
O
o
N
o
D
16
Request Processing
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Dispatcher
Servlet
Handler
Mapping
Handler
Adapter
Handler
getHandler(
HttpServletRequest)
17
Spring @MVC
e
c
r
u
Since Spring 2.5, annotated MVC
is preferred
o
Informally referred to as Spring
@MVC
S
g
y
Use <mvc:annotation-config/>
to setup
default
l
n
e
n
handlers and adaptersri
t
O
p
u
b
S
g
i
l
r
Spring 2.0 used
controller
base-classes
& XML
n
t
i
a
i
s
n
i
Controllercclass hierarchy
deprecated
in Spring 3.0
i
i
a compatible
D
f3 is backwards
r
f
Spring
by default
t
T o
O
N
o
This training focuses
D on Spring @MVC
do not specify <mvc:annotation-config/>
18
Controllers as Request
Handlers
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
@Controller
u
S { ng rib
public class AccountController
l
t
i
a
i
s
n
@RequestMapping("/listAccounts.htm")
i
i
c
i
a {...}t D
f
public String
list(Model
model)
r
f
}
T URL: o
O of calling
Example
http://localhost:8080 / N
mvc-1 / rewardsadmin / listAccounts.htm
o
D
Handlers are typically called controllers and are
usually annotated by @Controller
@RequestMapping tells Spring what method to
execute when processing a particular request
application server
webapp
servlet mapping
request mapping
19
e
c
r
u
Mapping rules typically URL-based,
optionally
o
using wild cards:
S
g
y
/login
l
n
i
e
n
r
t
/editAccount
O
p
u
/reward/*/**
S ng rib
l
t
i
Mapping rules
in Spring
2.5+:
defined using
a
i
s
n
i
i
c
annotations
or
XML:
i
a
D
f
r
f
t
@RequestMapping(/login)
T
O
o
N < 2.5: defined in XML
Mapping rules in Spring
o
Using the normal
<beans/> config language
D
20
e
c
r
u
o
S
g
HttpServletRequest, HttpSession,
Principle
y
l
n
iMVC classes
e
n
Model and other Spring
r
t
O
p
u
allows for very flexible
method
signatures
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
Model holds data for view
o
Dname
View
@Controller
public class AccountController {
@RequestMapping("/listAccounts")
public String list(Model model) {
...
}
}
21
Extracting Request
Parameters
e
c
r
u
o
Extracts parameter from the request
S y
Performs type conversion g
l
n
i
e
n
r
t
@Controller
O
p
u
public class AccountController
{
S ng rib
l
@RequestMapping("/showAccount")
t
i
a
i
s
n
public String
show(@RequestParam("entityId")
long id,
i
i
c
i
a
D
Model model)
{
f
r
f
t
...
T
O
o
}
N
}
o
Example of calling URL:D
http://localhost:8080/mvc-1/rewardsadmin/showAccount.htm?entityId=123
Use @RequestParam annotation
22
URI Templates
e
c request
Spring 3.0 can also extract valuesrfrom
u
URLs using so-called URI Templates
o
S
not Spring-specific concept, used
in many frameworks
g
y
l
@PathVariable
n
Use {} placeholders and
i
e
n
r
t
O
Allows clean URLs without
request
parameters
p
u
b
S
g
i
l
r
n
@Controller
t
i
a
i
s
public class AccountController
{
n
i
i
c
i
a tD
f
@RequestMapping("/accounts/{accountId}")
r
f
T o
OString show(@PathVariable("accountId")
public
long id,
N
Model
model) {
...
o
D
}
}
Example of calling URL:
http://localhost:8080/mvc-1/rewardsadmin/accounts/123
23
e
c
r
Request Processing Lifecycle u
o
S
g
y
l
Key Artifacts
n
i
e
n
r
t
DispatcherServlet p
O
u
S ng rib
Handlers
l
t
i
a
Views
i
s
n
i
i
c
i
a
D
f
r
f
t
Quick
Start
T
O
o
N
o
D
24
Selecting a View
e
c
r
u
By default interpreted as path too
JSP page
S
Example: /WEB-INF/reward/list.jsp
g
y
l
n
i
e
n
r
t
O
Controllers may return
null (or
void)u
p
b request URL
Sselectedngbased onrithe
Default view then
l
t
i
a
i
s
n
i
i
c
i
a return
Controllers
may ralso
a concrete View
D
f
f
t
T
O
o
N
Not common Spring
o
does this anyway!
D
Controllers typically return a view name
new JstlView(/WEB-INF/reward/list.jsp)
new RewardListingPdf()
25
View Resolvers
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
The default ViewResolver
treats
theu
view name
b
S
g
i
l
as a Web Application-relative
file
path
r
n
t
i
a
i
s
n
i
i
c
i
a bytregistering
D
f
Override
r
this default
a
f
Tbean with
O
o
ViewResolver
the DispatcherServlet
N
Internal resource
(default)
o
Bean name D
The DispatcherServlet delegates to a
ViewResolver to map returned view names to
View implementations
26
e
c
r
u
o
S
DispatcherServlet
RewardController
g
y
l
n
i
e
n
r
t
O
p
u
S ng ribLogical view name
l
t
i
a
i
s
n
i
i
c
Custom i
a Resolved
D
physical path
f
r
f
InternalResource
t
T
O
ViewResolver
o
N
o
D
1
handle GET
/reward/list
rewardList
model={rewards}
rewardList
/WEB-INF/views/rewardList.jsp
<bean class=org.springframework.web.servlet.view.
InternalResourceViewResolver>
<property name=prefix value=/WEB-INF/views/ />
<property name=suffix value=.jsp />
</bean>
27
e
c
r
Request Processing Lifecycle u
o
S
g
y
l
Key Artifacts
n
i
e
n
r
t
DispatcherServlet p
O
u
S ng rib
Handlers
l
t
i
a
Views
i
s
n
i
i
c
i
a
D
f
r
f
t
Quick
Start
T
O
o
N
o
D
28
Quick Start
e
c
r
Steps to developing a Spring MVCuapplication
o
S
g
y
1. Deploy a Dispatcher Servlet
(one-time
only)
l
n
i
e
n
t
2. Implement a requestrhandler (controller)
O
p
u
3. Implement the View(s)
S ng rib
l
4. Register theaControlleri with the t
DispatcherServlet
i
s
i
c
5. Deploy iand
test in
a tD
f
r
f
T
O
o
Repeat steps 2-5 to develop
N new functionality
o
D
29
e
c web.xml
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<servlet>
<servlet-name>rewardsadmin</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/mvc-config.xml
</param-value>
</init-param>
Contains Spring MVC configuration
<init-param>
<param-name>spring.profiles.active</param-name>
<param-value>dev</param-value>
Optional profile Spring 3.1
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
Default is on first request
30
e
c
r
u
o
S
<servlet-mapping>
g
y
<servlet-name>rewardsadmin</servlet-name>
l
n
i
e
n
<url-pattern>/rewardsadmin/*</url-pattern>
r
t
O
p
u
</servlet-mapping>
S ng rib
l
t
i
a
i
s
Will now be
able toin
invoke ithe
Servlet like
c
i
a tD
f
r
f
http://localhost:8080/mvc-1/rewardsadmin/reward/list
T o
O
http://localhost:8080/mvc-1/rewardsadmin/reward/new
N
http://localhost:8080/mvc-1rewardsadmin/reward/show?id=1
o
D
Map the Servlet to a URL pattern
31
Initial DispatcherServlet
Configuration
<beans>
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
/WEB-INF/mvc-config.xml
o
D
<bean class=org.springframework.web...InternalResourceViewResolver>
<property name=prefix value=/WEB-INF/views/ />
<property name=suffix value=.jsp />
</bean>
</beans>
32
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Controller
public class RewardController {
private RewardLookupService lookupService;
application service
@RequestMapping("/reward/show")
public String show(@RequestParam("id") long id, Model model) {
Reward reward = lookupService.lookupReward(id);
model.addAttribute(reward, reward);
return rewardView;
}
Automatically filled
}
Selects the rewardView to
in by Spring
to render the reward
33
e
c
r
u
o
<html>
S
g
<head><title>Your Reward</title></head>
y
l
n
i
e
<body>
n
r
t
p
u
Amount=${reward.amount}
<br/> O
S<br/>ng rib
Date=${reward.date}
l
t
i
a
i
Account Number=${reward.account}
<br/>
s
n
i
i
c
i
Merchant
Number=${reward.merchant}
a tD
f
r
f
</body>
T o
O
</html>
N
o
D
/WEB-INF/views/rewardView.jsp
References result model object by name
34
<beans>
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
/WEB-INF/mvc-config.xml
o
D
<bean class=org.springframework.web...InternalResourceViewResolver>
</bean>
<bean id=rewardController class=rewardsadmin.RewardController>
<constructor-arg ref=rewardLookupService />
</bean>
</beans>
35
e
c
r
u
o
http://localhost:8080/rewardsadmin/reward/show?id=1
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Your Reward
Amount = $100.00
Date = 2006/12/29
Account Number = 123456789
Merchant Number = 1234567890
36
Optionally:
Enable Component Scanning
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<!-- only scan for controllers, not services, repositories etc. that belong in root ctx -->
<context:component-scan base-package="rewardsadmin" use-default-filters="false">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
@Controller
public class RewardController {
private RewardLookupService lookupService;
@Autowired
public RewardController(RewardLookupService svc) {
this.lookupService = svc;
}
@RequestMapping("/reward/show")
public String show(@RequestParam("id") long id, Model model) { ... }
}
37
e
c
r
u
o
Appropriate Handler Mapping S
and Adapters registered
out-of-the-box
g
y
l
n
i
e
n
r
t
Spring 3.0 introduces
new features
not enabled
O
p
u
S ng rib
by default
l
i
a
Stateless converter
framework
fort binding & formatting
i
s
n
i
i
c
Support for
JSR-303
declarative
validation
i
a
D
f
r
f
t
HttpMessageConverters
(for
RESTful web services)
T
O
o
N features?
How do you use these
o
D
38
MVC Namespace
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
Registers Handler
Mapping/Adapter
for @MVC only
i
c
i
a tD
f
r
f
T o
O
N
o
D
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="...">
<!-- Provides default conversion service, validator and message converters -->
<mvc:annotation-driven/>
39
@EnableMvc
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Spring 3.1
@Override
public void addFormatters(FormatterRegistry registry) {
// Register your own type converters and formatters...
// For using non-simple types as @RequestParams and and in forms
// example: convert 8.25% to/from instances of a Percentage class
}
}
e
c
r
u
o
S
g
y
l
LAB
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Spring Web
MVC Essentials
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
o
S y with
Web Application gSecurity
l
n
i
e
n
Spring
r
t
O
p
u
S ng rib
l
t
i
a
i
Addressing Common
Web
Application
s
n
i
i
c
i
Security
Requirements
a
D
f
r
f
t
T
O
o
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
High-Level Security Overview
o
S
Motivations of Spring Security
g
y
l
n
Spring Security in a Web
Environment
i
e
n
r
t
O
p
u
Configuring Web Authentication
b
S
g
i
l
r
Using Spring Security's
Tag Libraries
n
t
i
a
i
s
n
i
i
Method security
c
i
a
D
f
r
f
t
Advanced security:
working
with filters
T
O
o
N
o
D
2
Security Concepts
e
c
r
u
Principal
o
User, device or system that performs
an action
S
g
y
l
Authentication
n
i
e
n
r
t
Establishing that a principals
credentials
are valid
O
p
u
b
g
Authorization l S
i
r
n
t
i
a
Deciding if a
principal
is allowed
to perform an action
i
s
n
i
i
c
i
fitem ra t D
Secured
f
O thatTis being
Resource
secured
o
N
o
D
3
Authentication
e
c
r
There are many authentication u
mechanisms
o
e.g. basic, digest, form, X.509
S
g
y
l
There are many storage
options
for credential
n
i
e
n
r
t
and authority information
O
p
u
b
S in-memory
e.g. Database, LDAP,
(development)
g
i
l
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
4
Authorization
e
c
r
u
Authorization depends on authentication
o
Before deciding if a user can S
perform an action, user
g
identity must be established
y
l
n
i
e
n
t
The decision processris often based
on
roles
O
p
u
ADMIN can cancel
orders g
b
S
i
l
r
n
MEMBER canaplace orders
t
i
i
s
n
i
i
c
GUEST can
browse the catalog
i
a tD
f
r
f
T o
O
N
o
D
5
e
c
r
High-Level Security Overview u
o
S
Motivations of Spring Security
g
y
l
n
Spring Security in a Web
Environment
i
e
n
r
t
O
p
u
Configuring Web Authentication
b
S
g
i
l
r
Using Spring Security's
Tag Libraries
n
t
i
a
i
s
n
i
i
Method security
c
i
a
D
f
r
f
t
Advanced security:
working
with filters
T
O
o
N
o
D
6
Motivations: Portability
e
c
r
u
Servlet-Spec security is not portable
o
Requires container specific adapters
and role
S
g
mappings
y
l
n
i across
e
n
r
t
Spring Security is portable
containers
O
p
u
Secured archive S
(e.g. WAR)
can be ideployed
as-is
b
g
l
r
Also runs in a
standalonein
environments
t
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
7
Motivations: Flexibility
e
c
r
u
Supports all common authentication
o
mechanisms
S
g
y
Basic, Form, X.509, Cookies,
Single-Sign-On,
etc.
l
n
i
e
n
r
t
Provides configurable
storage
options
for user
O
p
u
S andnauthorities)
details (credentials
g trib
l
i
a
RDBMS, LDAP,
Properties
file, custom DAOs, etc.
i
s
n
i
i
c
i
Uses Spring
for configuration
a tD
f
r
f
T o
O
N
o
D
8
Motivations: Extensibility
e
c
r
u
Security requirements often require
o
customization
S
g
y e are
l
With Spring Security, iall
of the following
n
n
r
t
extensible
O
p
u
b
How a principal isSdefined g
i
l
r
n
t
i
a
Where authentication
information
is stored
i
s
n
i
i
c
How authorization
decisions
are
made
i
a
D
f
r
f
t
Where
security
constraints
are stored
T
O
o
N
o
D
9
Motivations: Separation of
Concerns
e
c
r
u
Business logic is decoupled from
security
o
concerns
S
g SpringlyAOP for an
Leverages Servlet Filtersn
and
i
e
n
interceptor-based approach
r
t
O
p
u
Authentication and
Authorization
are decoupled
b
S
g
i
l
r
n
Changes to the
authentication
process
have no
t
i
a
i
s
n
i
impact oncauthorization
i
i
a tD
f
r
f
T o
O
N
o
D
10
Motivations: Consistency
e
c
r
u
The goal of authentication is always
the same
o
regardless of the mechanism
S
g
y
Establish a security context
with the
authenticated
l
n
e
n
principals informationri
t
O
p
u
The process of authorization
is always
the
b
S
g
i
l
r
n
same regardless
of resource
type
t
i
a
i
s resource
n
i
i
c
Consult ithe
attributes
of the secured
a
D
f
r
f
Obtain principal information
from security context
t
T
O
o
Grant or deny access
N
o
D
11
e
c
r
u
Authentication AccessDecision delegates
Security Interceptor
o
Manager
Manager
S
protects consults
g
y
l
polls
n
i
e
obtains n
populates
r
t
O
Config
p
u
S ng rib
Voters
Attributes
l
t
describes
i
a
i
s
n
i
i
c
i
a Context
D
f Security
r
f
Secured
thread of
t
T o
Authentication
executionO
Resource
(Principal + N
Authorities)
o
D
12
e
c
r
High-Level Security Overview u
o
S
Motivations of Spring Security
g
y
l
n
Spring Security in a iWeb Environment
e
n
r
t
Authorization by p
URL
O
u
b
SAuthentication
g
i
Configuring Web
l
r
n
t
i
a
i
n
Using Spring
Security's
Tagis
Libraries
i
c
i
a tD
f
Methodfsecurityr
T
O
o
Advanced security:N
working with filters
o
D
13
Configuration in the
Application Context
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Spring configuration
Using Spring Security's "Security" namespace
<beans>
<security:http>
<security:intercept-url pattern="/accounts/**"
access="IS_AUTHENTICATED_FULLY" />
<security:form-login login-page="/login.htm"/>
<security:logout logout-success-url="/index.html"/>
</security:http>
</beans>
Configuration in web.xml
e
c
r
u
springSecurityFilterChain is a mandatory
name
o
S
Refers to an existing Spring
bean
with same name
g
y
l
n
i
e
<filter>
n
r
t
O
<filter-name>springSecurityFilterChain</filter-name>
p
u
S ng rib
<filter-class>
l
org.springframework.web.filter.DelegatingFilterProxy
t
i
a
i
s
n
</filter-class> c
i
i
i
a tD
</filter>
f
r
f
T
O
o
<filter-mapping>
N
<filter-name>springSecurityFilterChain</filter-name>
o
<url-pattern>/*</url-pattern>
D
</filter-mapping>
Define the single proxy filter
web.xml
15
intercept-url
e
c listed
intercept-urls are evaluated in therorder
u
the first match will be used
o
specific matches should be putS
on top
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<beans>
<security:http>
<security:intercept-url pattern="/accounts/edit*"
access="ROLE_ADMIN" />
<security:intercept-url pattern="/accounts/account*"
access="ROLE_ADMIN,ROLE_USER" />
<security:intercept-url pattern="/accounts/**"
access="IS_AUTHENTICATED_FULLY" />
<security:intercept-url pattern="/customers/**"
access="IS_AUTHENTICATED_ANONYMOUSLY" />
</security:http>
</beans>
Security EL expressions
e
c
r
u
Checks whether the principal hasothe given role
S
hasAnyRole('role1', 'role2',
)
g
y
l
n
Checks whether the principal
i hasnany of thetegiven roles
r
O
p
u
isAnonymous()
b
S
g
i
l
Allows access for unauthenticated
principals
r
n
t
i
a
i
s
n
i
isAuthenticated()
i
c
i
a t D or remembered
f
Allowsfaccess forrauthenticated
T o
O
principals
N
o
Available from Spring
Security 3.0
D still works in Spring Security 3.0
Previous syntax
hasRole('role')
17
Intercept-url and
Expression Language
e
c
r
u
o
Many built-in expressions available
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<beans>
<security:http use-expressions="true">
<security:intercept-url pattern="/accounts/edit*"
access="hasRole('ROLE_ADMIN')" />
<security:intercept-url pattern="/accounts/account*"
access="hasAnyRole('ROLE_ADMIN', 'ROLE_USER')" />
<security:intercept-url pattern="/accounts/**"
access="isAuthenticated() and hasIpAddress('192.168.1.0/24')" />
</security:http>
</beans>
e
c
r
u
o
S
or clause
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
and clause a
t
i
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
Previous and new syntax
N can't be mixed
o
D
<security:intercept-url pattern="/accounts/update*"
access="hasAnyRole('ROLE_ADMIN', 'ROLE_MANAGER')" />
<security:intercept-url pattern="/accounts/update*"
access="hasRole('ROLE_ADMIN') and hasRole('ROLE_MANAGER')" />
<security:intercept-url pattern="/accounts/update*"
access="hasRole('ROLE_MANAGER')" />
<security:intercept-url pattern="/accounts/update*" access="ROLE_ADMIN" />
Not correct!!
19
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<beans ...>
<security:http pattern="/accounts/login" security="none"/>
<security:http use-expressions="true">
<security:form-login login-page="/accounts/login"
default-target-url="/accounts.home"/>
<security:intercept-url pattern="/accounts/update*"
access="hasAnyRole('ROLE_ADMIN', 'ROLE_MANAGER')" />
<security:intercept-url pattern="/accounts/**"
access="hasRole('ROLE_ADMIN')" />
<security:logout logout-success-url="/home.html"
</security:http>
...
</beans>
e
c
r
High-Level Security Overview u
o
S
Motivations of Spring Security
g
y
l
n
Spring Security in a Web
Environment
i
e
n
r
t
O
u
Configuring Web p
Authentication
b
S
g
i
l
r
Using Spring Security's
Tag Libraries
n
t
i
a
i
s
n
i
i
Method security
c
i
a
D
f
r
f
t
Advanced security:
working
with filters
T
O
o
N
o
D
21
Configure Authentication
e
c
r
u
o
Expects a UserDetailsService implementation
to
S
provide credentials and authorities
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Or define your
owniAuthentication
provider
s
n
i
c
i
a t D user details when
f
Example:
to getrpre-authenticated
f
T o
using
Osingle sign-on
N
o
See online examples
D
22
e
c
r
u
o
S
g
y
l
n
This is web security
i
e
n
r
t
after all
O
p
u
S ng rib
Must specify form-login
l
t
i
element
a
i
s
n
i
i
c
A basic form
is provided
i
a
D
f
r
f
t
Configure to use
your
T
O
o
own login-page
N
o
D
<security:http>
<security:form-login/>
</security:http>
<security:authentication-manager>
<security:authentication-provider>
...
</security:authentication-provider>
<security:authentication-manager>
23
e
c
r
u
o
S
g
y
<form action=<c:url value=j_spring_security_check/>
method=POST>
l
n
i
e
n
<input type=text name=j_username/>
r
t
O
p
u
<br/>
S ng rib
<input type=password name=j_password/>
l
t
i
<br/>
a
i
s
n
i
<input type=submit
name=submit
value=LOGIN/>
i
c
i
a tD
f
</form>
r
f
T o
O
N
o
D
URL that indicates an
authentication request
24
e
c
r
u
Useful for development and testing
o
Note: must restart system toS
reload properties
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
admin=secret,ROLE_ADMIN,ROLE_MEMBER,ROLE_GUEST
testuser1=pass,ROLE_MEMBER,ROLE_GUEST
testuser2=pass,ROLE_MEMBER
guest=guest,ROLE_GUEST
List of roles separated by commas
login
password
25
e
c
r
u
Queries RDBMS for users and their
authorities
o
Provides default queries S
g
y
enabledlFROM
users
SELECT username, password,
n
i
e
n
WHERE username = ? r
t
O
p
u
authority
FROM
authorities
WHERE
SELECT username,
b
S
g
i
username = ? l
r
n
t
i
a
i
s
n
Groups also
supported
i
i
c
i
a group_authorities
D
f
group_members,
tables
groups,
r
f
t
T o for details
Oonline documentation
See
N
Advantage
o
D info whilst system is running
Can modify user
26
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Configuration:
<beans>
<security:http> <security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:jdbc-user-service data-source-ref="myDatasource" />
</security:authentication-provider>
<security:authentication-manager>
</beans>
Can customize queries using attributes:
users-by-username-query
authorities-by-username-query
group-authorities-by-username-query
27
Password Encoding
e
c
r
u
o
sha, md5,
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
Secure passwords
using
a well-known
string
t
i
a
i
s
n
i
i
c
Known asi a 'salt'
a
D
f
r
f
Makes brute force attackst against passwords harder
T o
O
N
o
D
Can encode passwords using a hash
<security:authentication-provider>
simple md5 encoding
<security:password-encoder hash="md5" />
<security:user-service properties="/WEB-INF/users.properties" />
</security:authentication-provider>
<security:authentication-provider>
md5 encoding with salt
<security:password-encoder hash="md5">
<security:salt-source system-wide="MySalt" />
</security:password-encoder>
<security:user-service properties="/WEB-INF/users.properties" />
</security:authentication-provider>
28
e
c
r
u
Implement a custom UserDetailsService
o
Delegate to an existing User S
repository or DAO
g
y
l
LDAP
n
i
e
n
r
t
X.509 Certificates p
O
u
S ng rib
JAAS Login Module
l
t
i
a
i
s
n
Single-Sign-On
i
i
c
i
a tD
f
SiteMinder
r
f
T o
O
Kerberos
N
JA-SIG Central Authentication Service
o
D
e
c
r
High-Level Security Overview u
o
S
Motivations of Spring Security
g
y
l
n
Spring Security in a Web
Environment
i
e
n
r
t
O
p
u
Configuring Web Authentication
b
S
g
i
l
Using Spring Security's
TagtrLibraries
n
i
a
i
s
n
i
i
Method security
c
i
a
D
f
r
f
t
Advanced security:
working
with filters
T
O
o
N
o
D
30
e
c
r
u
o
S
g
y
l
<%@ taglib prefix="security"
n
i
e
n
r
uri="http://www.springframework.org/security/tags"
%>
t
O
p
u
S ng rib
l
t
i
a
i
Facelet tags
for JSFin
are alsois
available
c
i
aand install
D
f
You need
to define
them manually
r
f
t
TSpring oSecurity Facelets Tag Library in
SeeO
Using the
the Spring Webflow N
documentation
o
Principle is available
D in SpEL: #{principle.username}
The Spring Security tag library is declared as
follows
jsp
31
e
c
r
u
Display properties of the Authentication
object
o
S
You are logged in as:
g
y
<security:authentication property=principal.username/>
l
n
i
e
n
r
t
O
p
u
S
g tonribrole
Hide sections of
outputnbased
l
i
a
i
s
n
i
<security:authorize
access=hasRole('ROLE_MANAGER')>
i
c
i
a tD
f
TOP-SECRET
INFORMATION
r
f
T o
Click <a
href=/admin/deleteAll>HERE</a>
to delete all records.
O
</security:authorize>
N
o
D
jsp
jsp
32
e
c
r
u
Role declaration can be centralized
in Spring
o
config files
S
g
y
l
n
i
e
n
r
t
<security:authorize url=/admin/deleteAll>
O
p
u
TOP-SECRET INFORMATION
b
S
g
i
l
Click <a href=/admin/deleteAll>HERE</a>
r
n
t
i
a
</security:authorize>i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
URL to protect
jsp
Pattern that
matches the URL
to be protected
<security:intercept-url pattern="/admin/*"
access="hasAnyRole('ROLE_MANAGER', 'ROLE_ADMIN')" />
Spring configuration file
Matching roles
33
e
c
r
High-Level Security Overview u
o
S
Motivations of Spring Security
g
y
l
n
Spring Security in a Web
Environment
i
e
n
r
t
O
p
u
Configuring Web Authentication
b
S
g
i
l
r
Using Spring Security's
Tag Libraries
n
t
i
a
i
s
n
i
i
Method security
c
i
a
D
f
r
f
t
Advanced security:
working
with filters
T
O
o
N
o
D
34
Method Security
e
c
r
u
Spring Security uses AOP for security
at the
o
method level
S
g
y
xml configuration with the
Spring Security
l
n
i
e
n
namespace
r
t
O
p
u
annotations based
on
Spring
annotations
or JSR-250
b
S
g
i
annotations l
r
n
t
i
a
i
s
n
Typically isecure
your
services
i
i
c
a tD
faccess repositories
r
f
Do not
directly, bypasses security
T o
Otransactions)
(and
N
o
D
35
e
c with only
Can apply security to multiple beans
r
u
a simple declaration
o
S
<security:global-method-security>
g
y
l
n
<security:protect-pointcut
i
e
n
r
t
expression="execution(*p
com.springsource..*Service.*(..))"
O
u
access="ROLE_USER,ROLE_MEMBER"
/>b
S
g
i
l
r
</security:global-method-security>
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Spring configuration file
36
e
c
JSR-250 annotations should be enabled
r
u
<security:global-method-security jsr250-annotations="enabled"
/>
o
S
g
y
l
n
i
e
n
import javax.annotation.security.RolesAllowed;
r
t
O
p
u
S{ ng rib
public class ItemManager
l
t
i
a
@RolesAllowed("ROLE_MEMBER")
i
s
n
i
i
public Item findItem(long
itemNumber)
{
c
i
a tD
f
...
r
f
T o
}
O
}
N
@RolesAllowed({"ROLE_MEMBER",
"ROLE_USER"})
o
D
Only supports role-based security hence the name
37
e
c
Secured annotation should be enabled
r
u
<security:global-method-security secured-nnotations="enabled"
/>
o
S
g
y
l
n
i
e
n
import org.springframework.security.annotation.Secured;
r
t
O
p
u
S{ ng rib
public class ItemManager
l
t
i
a
@Secured("IS_AUTHENTICATED_FULLY")
i
s
n
i
i
public Item findItem(long
itemNumber)
{
c
i
a tD
f
...
r
f
T o
}
O
@Secured("ROLE_MEMBER")
}
N
@Secured({"ROLE_MEMBER",
"ROLE_USER"})
o
D
Spring 2.0 syntax, so not limited to roles. SpEL not supported.
38
e
c
Use Pre/Post annotations for SpEL
r
u
<security:global-method-security pre-post-annotations="enabled"
/>
o
S
g
y
l
n
i
e
n
import org.springframework.security.annotation.PreAuthorize;
org.springframework.security.annotation.Secured;
r
t
O
p
u
S{ ng rib
public class ItemManager
l
t
i
a
@Secured("ROLE_MEMBER")
@PreAuthorize("hasRole('ROLE_MEMBER')")
i
s
n
i
i
c
public Item findItem(long
itemNumber)
{
i
a tD
f
...
r
f
T o
}
O
}
N
o
D
39
e
c
r
High-Level Security Overview u
o
S
Motivations of Spring Security
g
y
l
n
Spring Security in a Web
Environment
i
e
n
r
t
O
p
u
Configuring Web Authentication
b
S
g
i
l
r
Using Spring Security's
Tag Libraries
n
t
i
a
i
s
n
i
i
Method security
c
i
a
D
f
r
f
t
Advanced security:
working
with filters
T
O
o
N
o
D
40
e
c
r
u
springSecurityFilterChain is declared
in
o
web.xml
S
g
This single proxy filterin
delegatesly
to a chain of
e
n
r
t
Spring-managed filters
O
p
u
S ng rib
Drive authentication
l
t
i
a
Enforce authorization
i
s
n
i
i
c
Manage ilogout a
D
f
r
f
t
in
HttpSession
Maintain SecurityContext
T
O
o
and more
N
o
D
41
r
u
o
S
DelegatingFilterProxy
g
Servlet
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
springSecurityFilterChain
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
Filter
T Filter
O Filter
o
1
N
N2
o
DSpring ApplicationContext
Servlet Container
Web
User
e
c
42
e
c
r
u
Filters were manually configuredoas individual
S
<bean> elements
g
y
l
n
Led to verbose and error-prone
XML
i
e
n
r
t
u
Spring Security 2.xpand 3.xO
b
S withncorrect
g tvalues
i
Filters are initialized
by default
l
r
i
a
i
s
Manual configuration
is not required
unless you
n
i
i
c
i
want to
customize
Security's behavior
a Spring
D
f
r
f
t
T
It is
still
important
to
understand
how they work
O
o
underneath
N
o
D
With ACEGI Security 1.x
43
e
c
r
u
o
S
g
SecurityContextPersistenceFilter
y
l
n
i
e
n
r
t
O
p
u
LogoutFilter
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
ExceptionTranslationFilter
T o
O
N
o
FilterSecurityInterceptor
D
Web Browser
No context in session
Establishes empty
security context
Not a logout request
does nothing
Not an authentication
request does nothing
Does nothing on
request side
Does nothing on
response side
UsernamePasswordProcessingFilter
Does nothing on
response side
No exceptions thrown
does nothing
Resource has no
security attributes
does nothing
UnsecuredResource
Resource has no
security attributes
does nothing
44
e
c
r
Login Form
u
o
S
g
SecurityContextPersistenceFilter
y
l
n
i
e
n
r
t
O
p
u
LogoutFilter
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
ExceptionTranslationFilter
T o
O
N
o
FilterSecurityInterceptor
D
Web Browser
No context in session
Establishes empty
security context
Does nothing
Does nothing
Does nothing
Resource is secured
THROWS NOT
AUTHENTICATED
EXCEPTION
UsernamePasswordProcessingFilter
Authentication
exception!
Saves current
request in session
Clears context
Redirects to
authentication entry
point
SecuredResource
45
e
c
r
u
o
S
g
SecurityContextPersistenceFilter
y
l
n
i
e
n
r
t
O
p
u
LogoutFilter
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
ExceptionTranslationFilter
T o
O
N
o
FilterSecurityInterceptor
D
Web Browser
No context in session
Establishes empty
security context
Does nothing
UsernamePasswordProcessingFilter
SecuredResource
46
e
c
r
u
o
S
g
SecurityContextPersistenceFilter
y
l
n
i
e
n
r
t
O
p
u
LogoutFilter
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
ExceptionTranslationFilter
T o
O
N
o
FilterSecurityInterceptor
D
Web Browser
Finds context in
session and sets
for current thread
Does nothing
Does nothing
Does nothing
Consults attributes,
obtains context, and
delegates to access
decision manager
UsernamePasswordProcessingFilter
Does nothing
Does nothing
Does nothing
SecuredResource
47
e
c
r
Error Page
u
o
S
g
SecurityContextPersistenceFilter
y
l
n
i
e
n
r
t
O
p
u
LogoutFilter
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
ExceptionTranslationFilter
T o
O
N
o
FilterSecurityInterceptor
D
Web Browser
Finds context in
session and sets
for current thread
Does nothing
Does nothing
Does nothing
Consults attributes,
obtains context, and
delegates to access
decision manager
UsernamePasswordProcessingFilter
Access Denied
Exception!
Puts exception in
request scope
Forwards to the
error page
SecuredResource
e
c
r
u
o
S
g
SecurityContextPersistenceFilter
y
l
n
i
e
n
r
t
O
p
u
LogoutFilter
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
ExceptionTranslationFilter
T o
O
N
o
FilterSecurityInterceptor
D
Logout Success
Web Browser
Finds context in
session and sets
for current thread
Clears context
Redirects to
logout success url
UsernamePasswordProcessingFilter
SecuredResource
49
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Filter Name
SecurityContext
IntegrationFilter
2
3
e
c
LogoutFilter
UsernamePassword
Processing Filter
Main Purpose
Exception
TranslationFilter
FilterSecurity
Interceptor
50
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
One filter ican be a
added to the chain
D
f
r
f
t
T
O
o
N
o
D
<security:http>
<security:custom-filter after="FORM_LOGIN_FILTER" ref="myFilter />
</security:http>
<bean id="myFilter" class="com.mycompany.MySpecialFilter"/>
51
e
c
r
u
o
S
g
y
l
LAB
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Applying Security
to a Web
Application
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
o
S
g
y
l
Introduction to Spring
Remoting
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Simplifying Distributed
Applications
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
Introduction to Remoting u
o
Spring Remoting Overview S
g
y
l
n
Spring Remoting and RMI
i
e
n
r
t
O
p
u
HttpInvoker
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
2
Local access
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
ClientService
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
AccountService
o
D
findAccount(...)
Account
Remote access
e
What if those 2 objects run in somerc
separate JVMs?
u
o
S
g
ClientService
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T AccountService
O
o
N
o
D
jvm 1
findAccount(...)
Account
jvm 2
e
c
r
u
Standard Java remoting protocol
o
Remote Method Invocation S
g
y
Java's version of RPC
l
n
i
e
n
r
t
Server-side exposes
a skeleton
O
p
u
S methods
g
Client-side invokes
onraib
stub (proxy)
l
n
t
i
a
i
Java serialization
isin
used foris
marshalling
c
i
a tD
f
r
f
T o
O
N
o
D
5
e
c
r
u
Couples business logic to remoting
infrastructure
o
S y
For example, with RMI: g
l
n
i
Service interface extends
Remoten
e
r
t
O
p
u
Client must catch RemoteExceptions
b
S
g
i
l
for binding
and retrieving
r
Technical Java code needed
n
t
i
a
i
s
objects on the
RMI server
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
RMI violates separation of concerns
Traditional RMI
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
Client must catch ia
s
n
i
i
c
RemoteExceptions
i
a tD
f
r
f
T o
O
N
o
D
Client Process
Server Process
Remote
<<interface>>
TransferService
Teller
Desktop
UI
Stub
transfer(..)
Skeleton
TransferServiceImpl
e
c
r
u
RMI relies on Object Serialization
o
Objects transferred using RMISshould implement
g
interface Serializable
y
l
n
i to benimplemented
e
Marker interface, no method
r
t
O
p
u
S ng rib
l
t
i
a
i
ClientService
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
import java.io.Serializable;
Account
AccountService
e
c
r
u
Introduction to Remoting
o
S
Spring Remoting Overview
g
y
l
n
Spring Remoting and RMI
i
e
n
r
t
O
p
u
HttpInvoker
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
9
e
c
r
u
Hide plumbing code
o
S
Configure and expose services
declaratively
g
y
l
n
Support multiple protocols
in a
consistent
way
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
10
e
c
r
u
Spring provides exporters to handle
servero
side requirements
S
g
y
Binding to registry or exposing
an endpoint
l
n
i model
e
n
r
t
Conforming to a programming
if necessary
O
p
u
b
S ng that
Spring provides FactoryBeans
generate
i
l
r
t
i
proxies to handle
client-side
requirements
a
i
s
n
i
i
c
Communicate
with
the server-side
endpoint
i
a
D
f
r
f
t
Convert remote
exceptions
to a runtime hierarchy
T
O
o
N
o
D
11
Service Exporters
e
c
r
u
Spring provides service exporters
to enable
o
declarative exposing of existing
services
S
g
y
l
n
i
e
n
r
t
O
p
u
Accessible from remote clients
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<<interface>>
Spring
ServiceExporter
TransferService
transfer(..)
transfer(..)
TransferServiceImpl
Teller
Controller
12
Client Proxies
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
Generated byD
a Spring FactoryBean
Server Process
<<interface>>
TransferService
Teller
Desktop
UI
Spring
Proxy
transfer(..)
<<interface>>
Teller
Controller
TransferService
Spring
ServiceExporter
TransferServiceImpl
13
A Declarative Approach
e
c
r
u
Uses a configuration-based approach
o
No code to write
S
g
y
l
On the server side
n
i
e
n
r
t
Expose existing services
with O
NO code changes
p
u
S ng rib
On the client side
l
t
i
a
Invoke remote
methods
from
existing
code
i
s
n
i
i
c
i
Take advantage
of
polymorphism
by using
a
D
f
r
f
t
dependency injection
T
O
o
Migrate between remote
N vs. local deployments
o
D
14
e
c
r
u
Springs exporters and proxy FactoryBeans
bring
o
the same approach to multiple
protocols
S
g
y
Provides flexibility
l
n
i
e
n
r
t
Promotes ease of adoption
O
p
u
S ng rib
On the server side
l
t
a
Expose a single
servicei over multiple
protocols
i
s
n
i
i
c
i
On the client
sidea
D
f
r
f
t
Switch
easily
between
protocols
T
O
o
N
o
D
15
e
c
r
u
Introduction to Remoting
o
Spring Remoting Overview S
g
y
l
n
Spring Remoting and
RMI n
i
e
r
t
O
p
u
HttpInvoker
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
16
e
c
r
u
Transparently expose an existing
POJO service
o
to the RMI registry
S
g
No need to write the binding
code ly
n
i
e
n
r
t
Avoid traditional RMI
requirements
O
p
u
b
Service interfaceS
does notg
extend Remote
i
l
r
n
t
i
a
Service class
is
a
POJO
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Transferred objects still need to implement the interface
java.io.Serializable
17
e
c
r
u
o
S y
<property name=accountRepositoryg
ref=accountRepository/>
l
n
</bean>
i
e
n
r
t
O
p
u
b
S
Define a bean to
export itg
i
l
r
n
t
i
a
i
s
n
i
<bean class=org.springframework.remoting.rmi.RmiServiceExporter>
i
c
i
a value=transferService/>
D
f
<property name=serviceName
r
f
t
<propertyO
name=serviceInterface
value=app.TransferService/>
T
o
<property name=service ref=transferService/>
N
<property name=registryPort
value=1096/>
o
</bean>
D
Server
Binds to rmiRegistry
as transferService
18
e
c
r
u
o
S
g
y
l
n
i
into Springs
Converts checked RemoteExceptions
e
n
r
t
O
runtime hierarchy of
RemoteAccessExceptions
p
u
b
S ntheg business
i
Dynamically implements
interface
l
r
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Exception
java.io.
RemoteException
RuntimeException
converted into
org.springframework.remoting.
RemoteAccessException
19
e
c
r
u
o
<bean id=transferService
S
g
class=org.springframework.remoting.rmi.RmiProxyFactoryBean>
y
l
n
i
<property name=serviceInterface
value=app.TransferService/>
e
n
r
t
<property name=serviceUrlp
value=rmi://foo:1099/transferService/>
O
u
</bean>
S ng rib
l
t
i
a
i
s
n
Inject it into
the
client
i
i
c
i
a
D
f
r
f
t
<bean id=tellerDesktopUI
class=app.TellerDesktopUI>
T
O
o
<property name=transferService
ref=transferService/>
N
</bean>
o
D
Client
20
e
c
r
u
Introduction to Remoting
o
Spring Remoting Overview S
g
y
l
n
Spring Remoting and RMI
i
e
n
r
t
O
p
u
HttpInvoker
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
21
Springs HttpInvoker
e
c
r
u
Lightweight HTTP-based remoting
protocol
o
Method invocation converted S
to HTTP POST
g
y
Method result returned as
an
HTTPlresponse
n
i return values
e
n
r
t
Method parameters and
marshalled
O
p
u
with standard Java
serialization
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
Java serialization
D
Client Process
HttpInvoker
Proxy
Server Process
HttpInvoker
ServiceExporter
e
c
r
u
<bean id=transferService class=app.impl.TransferServiceImpl>
o
<property name=accountRepositoryS
ref=accountRepository/>
g
y
</bean>
l
n
i
e
n
r
t
p
u
Define a bean to export
it O
b
S
g
i
l
endpoint for
HTTP request handling
r
<bean id=/transfer
n
t
i
a
i
class=org.springframework.remoting.httpinvoker.
s
n
i
i
c
i
HttpInvokerServiceExporter>
a
D
f
r
f
<property name=serviceInterface
value=app.TransferService/>
t
T
O name=serviceNref=transferService/>
o
<property
</bean>
o
D
Start with an existing POJO service
Server
Pre Spring 3.1: Spring did not allow characters such as '/' in an id attribute.
If special characters are needed, the name attribute could be used instead.
23
e
c
r
u
o
Uses BeanNameUrlHandlerMapping
to map requests to
S
service
g
y
l
n
i
e
n
Can expose multiple exporters
r
t
O
p
u
http://foo:8080/services/transfer
b
S
g
i
l
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
web.xml
<servlet>
<servlet-name>transfer</servlet-name>
<servlet-class>org.sfw...DispatcherServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>transfer</servlet-name>
<url-pattern>/services/</url-pattern>
</servlet-mapping>
servlet context
service exporter
bean name
24
e
c
Alternatively define HttpRequestHandlerServlet
r
u
Doesn't require Spring-MVC
o
S
Service exporter bean is defined
in root context
g
y
l
n
No handler mapping servlet
can
only
be used
by one
i
e
n
t
HttpInvoker exporter r
O
p
u
Servlet name mustS
match bean
nameib
g
l
r
n
t
i
a
http://foo:8080/services/transfer
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
service exporter bean name
o
D
<servlet>
<servlet-name>transfer</servlet-name>
<servlet-class>org.sfw...HttpRequestHandlerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>transfer</servlet-name>
<url-pattern>/services/transfer</url-pattern>
</servlet-mapping>
web.xml
25
e
c
r
u
Define a factory bean to generate
the proxy
o
S
<bean id=transferService
g
y
class=org.springframework.remoting.httpinvoker.
l
n
i
e
n
HttpInvokerProxyFactoryBean>
r
t
O
p
<property name=serviceInterface
value=app.TransferService/>
u
b
S value=http://foo:8080/services/transfer/>
g
<property name=serviceUrl
i
l
r
n
t
</bean>
i
a
i
s
n
i
i
c
i
a
D
f
r
f
Inject it into the
client t
T
O
o
N
<bean id=tellerDesktopUI class=app.TellerDesktopUI>
<property name=transferService
ref=transferService/>
o
D
</bean>
Client
26
e
c
r
u
o
(Too) Simple to setup and useS
g
y
Abstracts away all messaging
concerns
l
n
i
e
n
r
t
Disadvantages
O
p
u
Client-server tightly
coupled
by shared
erface
b
S
g
i
l
r
n
t
i
a
i
s
n
i
i
c
Can't control
underlying
messaging
(hidden)
i
fto scalera t D
f
Difficult
T o
O
N only
Not interoperable,
Java
o
D
Enterprise Integration with Spring
Advantages
27
e
c
r
u
o
S
g
y
l
LAB
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Simplifying Distributed
Applications
with Spring
s
n
i
i
c
i
Remoting
a
D
f
r
f
t
T
O
o
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
o
S
g
y
l
Spring
JMS
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Simplifying Messaging
Applications
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Copyright 2006-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
Introduction to JMS
o
S
Apache ActiveMQ
g
y
l
n
Configuring JMS Resources
with
Springe
i
n
r
t
O
p
u
Springs JmsTemplate
b
S
g
i
l
r
Sending Messages
n
t
i
a
i
s
n
i
i
Receivingic
Messages
a
D
f
r
f
t
Advanced Features
T
O
o
N
o
D
2
e
c
r
u
The JMS API provides an abstraction
for
o
accessing Message Oriented
Middleware
S
g
y
Avoid vendor lock-in
l
n
i
e
n
t
Increase portability r
O
p
u
S ng rib
l
t
i
JMS does not
enable different
MOM vendors to
a
i
s
n
i
i
c
communicate
i
a
D
f
r
f
t
Need a bridgeT(expensive)
O
o
Or use AMQP (standard
N msg protocol, like SMTP)
o
D
See RabbitMQ from VMware
e
c
r
u
Message
o
S
Destination
g
y
l
n
Connection
i
e
n
r
t
O
p
u
Session
b
S
g
i
l
r
MessageProducer
n
t
i
a
i
s
n
i
i
MessageConsumer
c
i
a tD
f
r
f
T o
O
N
o
D
4
e
c
r
u
Implementations of the Message
interface
o
TextMessage
S
g
y
ObjectMessage
l
n
i
e
n
MapMessage
r
t
O
p
u
BytesMessage
b
S
g
i
l
StreamMessage
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
5
e
c
r
u
Implementations of the Destination
interface
o
Queue
S
g
y
l
n
i
e
n
Topic
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
Both support
multiple
producers
and
i
i
c
i
a tD
f
consumers
r
f
O areTdifferent
o
Messages
N
Let's take a closer look ...
o
D
Point-to-point messaging
Publish/subscribe messaging
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Producer
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D Queue
Producer
Consumer
Consumer
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Producer
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D Topic
Producer
Consumer
Consumer
e
c
r
u
A JMS Connection is obtained from
a factory
o
S
Connection conn = connectionFactory.createConnection();
g
y
l
n
i
e
n
r
t
O
p
u
Typical enterprise application:
b
Sis a managed
g
i
resource
bound to
ConnectionFactory
l
r
n
t
i
a
i
JNDI
s
n
i
i
c
i
aProperties();
D
f
Properties
env = new
r
f
t
T
// provide
JNDI environmentoproperties
O
Context ctx = new InitialContext(env);
N
ConnectionFactory connectionFactory
=
o
(ConnectionFactory)
ctx.lookup("connFactory");
D
9
e
c
r
u
A Session is created from the Connection
o
Represents a unit-of-work S
g
y
Provides transactional capability
l
n
i
e
n
r
t
Session session = conn.createSession(
O
p
u
boolean
transacted,
int acknowledgeMode);
b
S
g
i
l
r
n
t
i
a
s
// use session i
n
i
i
c
i
if (everythingOkay)
{ a
D
f
r
f
t
session.commit();
T
O
o
} else {
N
session.rollback();
o
}
D
10
Creating Messages
e
c
r
u
The Session is responsible for the
creation of
o
various JMS Message typesS
g
y
l
n
session.createTextMessage("Some
Message
Content");
i
e
n
r
t
O
p
u
session.createObjectMessage(someSerializableObject);
S ng rib
l
t
i
a
i
MapMessage message =n
session.createMapMessage();
s
i
i
c
i
message.setInt("someKey",
123);
a
D
f
r
f
t
T
O messageN= osession.createBytesMessage();
BytesMessage
message.writeBytes(someByteArray);
o
D
11
e
c
r
The Session is also responsible u
for creating
o
instances of MessageProducer
and
S
g
y
MessageConsumer
l
n
i
e
n
r
t
producer = session.createProducer(someDestination);
O
p
u
b
S
g
i
l
r
consumer = session.createConsumer(someDestination);
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
12
e
c
r
u
Introduction to JMS
o
S
Apache ActiveMQ
g
y
l
n
Configuring JMS Resources
with
Springe
i
n
r
t
O
p
u
Springs JmsTemplate
b
S
g
i
l
r
Sending Messages
n
t
i
a
i
s
n
i
i
Receivingic
Messages
a
D
f
r
f
t
Advanced Features
T
O
o
N
o
D
13
JMS Providers
e
c
r
u
o
S
y
WebSphere MQ, Tibco EMS,g
Oracle EMS,
JBoss AP,
l
n
i
e
n
SwiftMQ, etc.
r
t
p
u
Some are Open Source,
some O
commercial
b
S
g
i
l
Some are implemented in
Java themselves
r
n
t
i
a
i in usesisApache ActiveMQ
The lab foric
this module
a tD
f
r
f
T o
O
N
o
D
14
Apache ActiveMQ
e
c
r
u
o
S
g
y
Including non-Java clients!
l
n
i
e
n
r
t
Can be used stand-alone
in O
production
p
u
b
environment l S
g
i
r
n
t
i
a
'activemq' script
in download starts
with default config
i
s
n
i
i
c
i
SpringSource
provides
support
a tD
f
r
f
T embedded
Can also
in an application
O be used
o
Configured through N
ActiveMQ or Spring xml files
o
What we use in the
D labs
15
e
c
r
u
o
S
g
y
Incl. excellent Spring integration
l
n
i
e
n
r
t
Flexible & powerful deployment configuration
O
p
u
Clustering incl. load-balancing
& failover,
...
b
S
g
i
l
r
n
t
i
Advanced messaging
features
a
i
s
n
i
i
c
Message igroups, virtual
& composite destinations,
a
D
f
f
wildcards,
etc. r
t
T
O
o
Enterprise Integration
Patterns
when combined with
N
Spring Integrationoor Apache Camel
from the bookD
by Gregor Hohpe & Bobby Woolf
Support for:
Many cross language clients & transport protocols
16
e
c
r
u
Introduction to JMS
o
S
Apache ActiveMQ
g
y
l
n
Configuring JMS Resources
with Spring
i
e
n
r
t
O
p
u
Springs JmsTemplate
b
S
g
i
l
r
Sending Messages
n
t
i
a
i
s
n
i
i
Receivingic
Messages
a
D
f
r
f
t
Advanced Features
T
O
o
N
o
D
17
e
c
r
u
Spring enables decoupling of your
application
o
code from the underlying infrastructure
S
g
y
Container provides the resources
l
n
i againstn the APIte
r
Application is simply coded
O
p
u
b
S flexibility
Provides deployment
g
i
l
r
n
t
i
a
use a standalone
JMS
provider
i
s
n
i
i
c
use anfapplication
server to
manage JMS resources
i
a
D
r
f
t
T
O
o
N
o
D
18
Configuring a
ConnectionFactory
e
c
r
u
ConnectionFactory may be standalone
o
S
<bean id="connectionFactory"
g
y
class="org.apache.activemq.ActiveMQConnectionFactory">
l
n
ivalue="tcp://localhost:61616"/>
e
n
<property name="brokerURL"
r
t
O
p
</bean>
u
S ng rib
l
t
i
a
i
s
n
i
i
c
Or retrieved
from
JNDI
i
a
D
f
r
f
<jee:jndi-lookup id="connectionFactory"
t
T
O
o
jndi-name="jms/ConnectionFactory"/>
N
o
D
19
Configuring Destinations
e
c
r
Destinations may be standalone u
o
S
<bean id=orderQueue
g
y
class=org.apache.activemq.command.ActiveMQQueue>
l
n
i
e
n
<constructor-arg value=queue.order/>
r
t
O
p
</bean>
u
S ng rib
l
t
i
a
i
s
n
i
i
c
Or retrieved
from
JNDI
i
a
D
f
r
f
t
<jee:jndi-lookup id=orderQueue
T
O jndi-name=jms/OrderQueue/>
o
N
o
D
20
e
c
r
u
Introduction to JMS
o
S
Apache ActiveMQ
g
y
l
n
Configuring JMS Resources
with
Springe
i
n
r
t
O
p
u
Springs JmsTemplate
b
S
g
i
l
r
Sending Messages
n
t
i
a
i
s
n
i
i
Receivingic
Messages
a
D
f
r
f
t
Advanced Features
T
O
o
N
o
D
21
Springs JmsTemplate
e
c
r
u
The template simplifies usage of
the API
o
Reduces boilerplate code
S
g
y
Manages resources transparently
l
n
i to runtime
e
n
r
t
Converts checked exceptions
equivalents
O
p
u
Provides convenience
methods
and callbacks
b
S
g
i
l
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
22
Exception Handling
e
c
r
Exceptions in JMS are checked u
by default
o
S
JmsTemplate converts checked
exceptions to
g ly
runtime equivalents in
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Exception
javax.jms.
JMSException
RuntimeException
converted into
org.springframework.jms.
JmsException
23
JmsTemplate Strategies
e
c
r
u
The JmsTemplate delegates to two
collaborators
o
to handle some of the workS
g
y
MessageConverter
l
n
i
e
n
r
t
DestinationResolver
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
24
MessageConverter
e
c
r
u
The JmsTemplate uses a MessageConverter
to
o
convert between objects and
messages
S
g
You only send and receive
objects ly
n
i
e
n
Object
r
t
The default SimpleMessageConverter
O
p
u
S ng rib
handles basic types
l
t
i
a
String to TextMessage
i
s
n
i
i
c
Map to MapMessage
i
a
D
f
r
f
t
byte[] to BytesMessage
T
O
o
Serializable to ObjectMessage
N
Message
o
D
Message
Convertor
25
DestinationResolver
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
u
Resolves topic and p
queue names
b
S
g
i
Not their Spring
bean names
l
r
n
t
i
a
i
s
n
JndiDestinationResolver
also available
i
i
c
i
a tD
f
r
f
T o
OresolveDestinationName(Session
Destination
session,
N
String destinationName,
o
boolean pubSubDomain)
D
throws JMSException;
Convenient to use destination
names at runtime
DynamicDestinationResolver used by
default
Name
Destination
Resolver
Destination
publish-subscribe?
true Topic
false Queue
26
JmsTemplate configuration
e
c
r
u
Must provide reference to ConnectionFactory
o
via
either
constructor
or
setter
injection
S
g
y
Optionally provide other
facilities
l
n
i
e
n
r
t
setMessageConverter
O
p
u
setDestinationResolver
S ng rib
l
or setDefaultDestinationName
setDefaultDestination
t
i
a
i
s
n
i
i
c
i
a tD
f
<bean id=jmsTemplate
r
f
class=org.springframework.jms.core.JmsTemplate>
T
O
o
<constructor-arg ref=connectionFactory/>
N
<property name=defaultDestination
ref=orderQueue/>
o
</bean>
D
27
e
c
r
u
Introduction to JMS
o
S
Apache ActiveMQ
g
y
l
n
Configuring JMS Resources
with
Springe
i
n
r
t
O
p
u
Springs JmsTemplate
b
S
g
i
l
r
Sending Messages
n
t
i
a
i
s
n
i
i
Receivingic
Messages
a
D
f
r
f
t
Advanced Features
T
O
o
N
o
D
28
Sending Messages
e
c
r
The template provides options u
o
Simple methods to send a JMS
message
S
g
One line methods that leverage
thely
templates
n
i
e
n
MessageConverter
r
t
O
u
Callback-accepting p
methods that
reveal
more of the
b
S
g
i
JMS API
l
r
n
t
i
a
i
s
n
Use the simplest
option
for ithe
task at hand
i
c
i
a tD
f
r
f
T o
O
N
o
D
29
Sending POJO
e
c line
A message can be sent in one single
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
}
}
30
e
c
r
u
eg. set expiration, redelivery mode...
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
31
e
c
r
u
Introduction to JMS
o
S
Apache ActiveMQ
g
y
l
n
Configuring JMS Resources
with
Springe
i
n
r
t
O
p
u
Springs JmsTemplate
b
S
g
i
l
r
Sending Messages
n
t
i
a
i
s
n
i
i
c
Receiving
Messages
i
a
D
f
r
f
t
Advanced Features
T
O
o
N
o
D
32
Synchronous Message
Reception
e
c
r
u
but methods are blocking (synchronous)
o
S
optional timeout: setReceiveTimeout()
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
33
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
}
a
i
s
n
i
}
i
c
i
a tD
f
r
f
T
O
Traditionally, using N
ao
MessageListener required
an EJB containero
DBeans
Message Driven
The JMS API defines this interface for
asynchronous reception of messages
import javax.jms.Message;
import javax.jms.MessageListener;
34
Springs MessageListener
Containers
e
c
r
u
Spring provides lightweight alternatives
o
SimpleMessageListenerContainerS
g
y
l
n
i
e
n
r
t
O
p
u
DefaultMessageListenerContainer
S ng rib
l
t
i
a
i
s
n
Advancedic
scheduling
and endpoint
i
i
a available
D
f options
management
for each
r
f
t
T o
O option
container
N
o
D
Uses plain JMS client API
Creates a fixed number of Sessions
Adds transactional capability
35
Defining a plain
JMS Message Listener
e
c
r
u
Define listeners using jms:listener
elements
o
S
<jms:listener-container connection-factory="myConnectionFactory">
g
y
l
<jms:listener destination="queue.order"
ref="myOrderListener"/>
n
i
e
n
r
t
<jms:listener destination="queue.conf" ref="myConfListener"/>
O bu
</jms:listener-container> Sp
g
i
l
r
n
t
i
a
i
s
n
i
i
c
Listener fneeds
toaimplement
MessageListener
i
D
r
f
t
or SessionAwareMessageListener
T
O
o
jms:listener-container
N configurable
o
D
task execution strategy, concurrency, container type,
transaction manager and more
36
e
c
r
u
o
S
y
MessageConverter providesg
parameter
l
n
e
n
Any return value sent r
toi response-destination
after
t
O
p
u
conversion
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<jms:listener
ref="orderService"
1
method="order" 2
destination="queue.orders"
3
response-destination="queue.confirmation"/>
37
e
c
r
u
o
Resilience, guaranteed delivery
S
g
y
Asynchronous support
l
n
i
n
Application freed from r
messaging
concernste
O
p
u
Interoperable languages,
environments
S ng rib
l
Disadvantages
t
i
a
i
s
n
i
i
c
Requiresiadditional third-party software
a tD
f
r
f
T
O
More complex to use o
N but not with JmsTemplate!
o
D
Enterprise Integration
with Spring
Advantages
38
e
c
r
u
o
S
g
y
l
LAB
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Sending and Receiving
Messages
in a Spring
s
n
i
i
c
i
Environment
a
D
f
r
f
t
T
O
o
N
o
D
Copyright 2006-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
Introduction to JMS
o
S
Apache ActiveMQ
g
y
l
n
Configuring JMS Resources
with
Springe
i
n
r
t
O
p
u
Springs JmsTemplate
b
S
g
i
l
r
Sending Messages
n
t
i
a
i
s
n
i
i
Receivingic
Messages
a
D
f
r
f
t
Advanced Features
T
O
o
N
o
D
40
SessionCallback Example:
Synchronous Request-Reply
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
RewardConfirmation confirmation =
jmsTemplate.execute(new SessionCallback() {
Advanced Option:
CachingConnectionFactory
e
c
r
JmsTemplate aggressively closesu
and reopens
o
resources like Sessions and S
Connections
g
y
Normally these are cached by
connection
factory
l
n
i lots ofnoverheadte
Without caching can cause
r
O
p
u
S ng rib
l
Use our CachingConnectionFactory
to add caching
t
i
a
i
s
n
i
i
c
within theiapplication
if needed
a tD
f
r
f
T o
O
N
o
D
Resulting in poor performance
<bean id="connectionFactory"
class="org.springframework.jms.connection.CachingConnectionFactory">
<property name="targetConnectionFactory">
<bean class="org.apache.activemq.ActiveMQConnectionFactory">
<property name="brokerURL" value="vm://embedded?broker.persistent=false"/>
</bean>
</property>
</bean>
42
e
c
r
u
o
S
Performance and
Operations
g
y
l
n
i
e
n
with
Spring
r
t
O
p
u
S ng rib
l
t
i
a
i
Management and
Monitoring
of Java
s
n
i
i
c
i
Applications
a
D
f
r
f
t
T
O
o
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
Introduction
o
S
JMX
g
y
l
n
Introducing Spring JMX
i
e
n
r
t
O
u
Explicitly exportingpbeans with
Spring
b
S
g
i
l
r
Automatically exporting
existing
MBeans
n
t
i
a
i
s
n
i
i
Spring Insight
c
i
a tD
f
r
f
T o
O
N
o
D
2
Overall Goals
e
c
r
u
Gather information about application
during
o
runtime
S
g
y
l
n
i
e
n
r
t
Dynamically reconfigure
app
to align
to
O
p
u
S ng rib
external occasions
l
t
i
a
i
s
n
i
i
c
i
Trigger operations
inside D
the application
a
f
r
f
t
T
O
o
N changes in smaller
Even adapt to business
o
scope
D
3
e
c
r
u
Introduction
o
S
JMX
g
y
l
n
Introducing Spring JMX
i
e
n
r
t
O
u
Explicitly exportingpbeans with
Spring
b
S
g
i
l
r
Automatically exporting
existing
MBeans
n
t
i
a
i
s
n
i
i
Spring Insight
c
i
a tD
f
r
f
T o
O
N
o
D
4
What is JMX?
e
c
r
u
The Java Management Extensions
specification
o
aims to create a standard API
for adding
S
g
y
management and monitoring
tolJava
n
i
e
n
r
applications
t
O
p
u
S ng rib
l
t
i
Managementia
s
n
i
i
c
i
Changing
configuration
properties
at runtime
a
D
f
r
f
t
T
Monitoring
O
o
N ratios at runtime
Reporting cache hit/miss
o
D
5
e
c
r
u
To add this management and monitoring
o
capability, JMX instrumentsSapplication
g
y
components
l
n
i
e
n
r
t
O
p
u
b
S concept
g
JMX introducesl the
of the
MBean
i
r
n
t
i
a
An object with
management
metadata
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
6
JMX Architecture
e
c
r
u
o
S
JSR-160
JSR-160
g
y
l
n
Connector ri
Connector
e
n
t
O
p
u
S ng rib
l
t
i
a
i
MBeanServer
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
MBean o MBean
MBean
D
7
JMX Architecture
e
c
r
MBeanServer acts as broker forucommunication
o
between
S
y
Multiple local MBeans ng
l
i
e
n
r
t
Remote clients and MBeans
O
p
u
b
S nga keyedrireference
MBeanServer maintains
to
l
i
all MBeans registered
with it t
a
i
s
n
i
i
c
object name
i
a tD
f
r
f
ManyO
generic T
clients o
available
N
JDK: jconsole, jvisualvm
o
VMware: Hyperic,
http://www.hyperic.com/
D
8
JMX Architecture
e
c
r
u
An MBean is an object with additional
o
management metadata
S
g
y
Attributes
( properties)
l
n
i
e
n
r
t
Operations
( methods)
O
p
u
S ng rib
l
t
i
a
The management
metadata
can
be defined
i
s
n
i
i
c a Java
staticallyfiwith
interface
or defined
a
D
r
f
t
dynamically
at
runtime
T
O
o
N MBean respectively
Simple MBean or Dynamic
o
D
9
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
10
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
try {
ObjectName name = new ObjectName("ourapp:name=counter");
server.registerMBean(bean, name);
} catch (Exception e) {
e.printStackTrace();
}
11
e
c
r
u
Introduction
o
S
JMX
g
y
l
n
Introducing Spring JMX
i
e
n
r
t
O
u
Explicitly exportingpbeans with
Spring
b
S
g
i
l
r
Automatically exporting
existing
MBeans
n
t
i
a
i
s
n
i
i
Spring Insight
c
i
a tD
f
r
f
T o
O
N
o
D
12
e
c
r
u
Using the raw JMX API is difficult
and complex
o
S
g
y
l
n
The goal of Spring's JMX
support
is to e
simplify
i
n
r
t
the use of JMX while
hiding
the
complexity
of
O
p
u
S ng rib
the API
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
13
e
c
r
Configuring JMX infrastructure u
o
Declaratively using context namespace
or
S
g
FactoryBeans
y
l
n
i
e
n
r
t
O
p
u
Exposing Spring S
beans as
MBeans
b
g
i
l
r
n
Annotation based
metadata
t
i
a
i
s
n
i
i
c
Declaratively
using Spring bean definitions
i
a tD
f
r
f
T o
O
N beans
Consuming JMX managed
o
Transparently using
a proxy-based mechanism
D
14
Creating an MBeanServer
e
c
r
u
To locate or create an MBeanServer
o
declaratively, use the context
namespace
S
g
y
l
n
<context:mbean-server />
i
e
n
r
t
O
p
u
or declare it explicitly
S ng rib
l
t
i
a
i
s
n
<bean id="mbeanServer"
i
i
c
i
a
class="org.springframework.jmx.support.
D
f
r
f
t
MBeanServerFactoryBean">
T
O
o
<property name="locateExistingServerIfPossible"
value="true"/>
N
</bean>
o
D
15
e
c
r
u
Introduction
o
S
JMX
g
y
l
n
Introducing Spring JMX
i
e
n
r
t
O
p
u
Explicitly exporting
beans
with Spring
b
S
g
i
l
r
Automatically exporting
existing
MBeans
n
t
i
a
i
s
n
i
i
Spring Insight
c
i
a tD
f
r
f
T o
O
N
o
D
16
e
c
r
u
Annotate your class and methodsoto be exposed
Activate exporter in Bean XMLS
g
y
l
n
ObjectName derived from
@ManagedResource
attribute
i
e
n
r
t
or fully qualified classname
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
How it works
@ManagedResource(objectName=statistics:name=counter,
description=A simple JMX counter)
public class JmxCounterImpl implements JmxCounter {
@ManagedAttribute(description=The counter value)
public int getCount() {}
<context:mbean-export/>
17
Spring's MBeanExporter
e
c
r
u
Transparently expose an existing
POJO bean to
o
the MBeanServer
S
g
y
No need to write the registration
code
l
n
i
e
n
r
t
By default avoids the
need O
to create
an explicit
p
u
b
S norgcreaterian
management interface
l
t
ObjectNameia
instance i
s
n
i
i
c
Uses reflection
toa
manage D
all properties and methods
i
f
r
t
Uses f
map key
as
the ObjectName
T
O
o
N
o
D
18
Exporting a bean as an
MBean
e
c
r
u
Start with an existing POJO bean
o
S
<bean id="messageService" class="example.MessageService"/>
g
y
l
n
i
e
n
r
t
Use the MBeanExporter
to export
itu
O
p
S ng rib
<bean class="org.springframework.jmx.export.MBeanExporter">
l
t
i
a
<property name="beans">
i
s
n
i
i
c
<map> i
a tD
f key="service:name=messageService"
r
f
<entry
T o
O value-ref="messageService"/>
N
</map>
o
</property>
D
</bean>
19
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
MBean
O
p
u
S nServer
g trib
l
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Server Process
Client Process
<<interface>>
JmxCounter
Client
Generated
at startup
Spring
Proxy
MBean
Registration
at startup
<<interface>>
JmxCounter
JmxCounterImpl
Spring
MBeanExporter
20
e
c
r
u
Introduction
o
S
JMX
g
y
l
n
Introducing Spring JMX
i
e
n
r
t
O
u
Explicitly exportingpbeans with
Spring
b
S
g
i
l
r
Automatically exporting
existing
MBeans
n
t
i
a
i
s
n
i
i
Spring Insight
c
i
a tD
f
r
f
T o
O
N
o
D
21
Automatically exporting
pre-existing MBeans
e
c
r
u
Some beans are MBeans themselves
o
Example: Log4j's LoggerDynamicMBean
S
g
y
Spring will auto-detect and
export them
for you
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<context:mbean-export/>
<bean class="org.apache.log4j.jmx.LoggerDynamicMBean">
<constructor-arg>
<bean class="org.apache.log4j.Logger"
factory-method="getLogger"/>
<constructor-arg value="org.springframework.jmx" />
</bean>
</constructor-arg>
</bean>
22
Automatically exporting
pre-existing MBeans
e
c
r
u
Hibernate StatisticsService
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<context:mbean-export/>
Pure Hibernate
<property name="sessionFactory">
<!-- Get sessionFactory property from Hibernate E.M.F. -->
<util:property-path path="entityManagerFactory.sessionFactory" />
</property>
Need util:property-path to access custom
property of HibernateEntityManagerFactory
23
e
c
r
u
Introduction
o
S
JMX
g
y
l
n
Introducing Spring JMX
i
e
n
r
t
O
u
Explicitly exportingpbeans with
Spring
b
S
g
i
l
r
Automatically exporting
existing
MBeans
n
t
i
a
i
s
n
i
i
Spring Insight
c
i
a tD
f
r
f
T o
O
N
o
D
24
e
c
r
u
o
Monitors web applications deployed
to tc Server
S
g
y
http://localhost:8080/insight
l
n
i
e
n
r
t
O
p
u
Focuses on what's
relevant
b
S
g
i
l
r
n
esp. performance
related
parts oftthe application
i
a
i
s
n
i
i
c
i
a
D
f
r
f
Detects performance
issues
during development
t
T
O
o
Commercial version N
for production: vFabric APM
o
D
Part of tc Server Developer Edition
25
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Timeline
Servlet Selector
26
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
27
Summary
e
c
r
u
Spring JMX
o
Export Spring-managed beans
to a JMX MBeanServer
S
g
y
Simple value-add now that
your beans
are managed
l
n
i
e
n
r
t
Steps
O
p
u
b
S ng to create
Use <context:mbean-server>
MBean server
i
l
r
t
i
a
Use Spring iannotations to declare JMX metadata
s
n
i
i
c
Use <context:mbean-export>
to automatically export
i
a
D
f
r
f
annotated
and pre-existing
MBeans
t
T
O
o
Spring Insight
N
o
Deep view into your
web-application in STS
D
Production version available in vFabric APM
28
e
c
r
u
o
S
g ly
What'sinnext?
e
n
r
t
O
p
u
b
S
g
i
l
r
n
Certification
t
i
a
i
s
n
i
Other
courses
i
c
i
aResources
D
f
r
f
t
T
O
o
Evaluation
N
o
D
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Certification
e
c
r
u
o
50 multiple-choice questions S
g
y
90 minutes
l
n
iquestionsnansweredte
Passing score: 76% (38
r
O
p
u
successfully)
S ng rib
l
t
i
a
i
s
n
i
Preparation
i
c
i
a t D guide
f
f
See Core
Springr3.x certification
T o
O
N
o
Review all theD
slides
Computer-based exam
http://www.springsource.com/training/certification/springprofessional
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Certification: Questions
e
c
r
Typical question
u
o
Statements
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Pick the correct
response:
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
1.
2.
3.
4.
Only a. is correct
Both a. and c. are correct
All are correct
None are correct
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Certification: Logistics
e
c
r
u
o
At any Pearson VUE Test Center
S
Most large or medium-sizedg
cities ly
n
i
e
n
r
t
O
p
u
How?
S ng rib
l
At the end ofa
the class,iyou will receive
a certification
t
i
s
voucher by
email in
i
c
i
a tD
f
Make an
appointment
r
f
Othem theTvoucher
o
Give
when you take the test
N
For any further inquiry, you can write to
o
eduoperations@vmware.com
D
Where?
See http://www.pearsonvue.com/vtclocator/
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Other courses
e
c
r
u
o
Web Applications with Spring S
Enterprise Integration with g
Spring ly
n
e
n
Hibernate with Spring ri
t
p g O bu
Groovy and GrailsS
i
l
r
n
tc Server, Tomcat,
Hyperic
t
i
a
i
s
n
i
i
c
i
a
D
f
r
f
More details here:
t
T
O
o
http://www.springsource.com/training/curriculum
N
o
D
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
o
S
g
Making the most of Spring
in thely
web layer
n
i
e
n
r
t
Spring MVC
O
p
u
Spring Web Flow S
b
g
i
l
r
n
t
REST using MVC
and AJAX
i
a
i
s
n
i
i
c
Productivity
with Spring Roo
i
a
D
f
r
f
Security of Web applications
t
T
O
o
Performance testingN
o
D
Spring Web Application
Developer certification
4-day workshop
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Enterprise Integration
with Spring (EIwS)
e
c
r
u
o
S
g
y
Separate processing, communications
& integration
l
n
i
e
n
r
t
4 day course covering
O
p
u
Concurrency
S ng rib
l
t
Advanced transaction
management
i
a
i
s
n
i
i
c
SOAP Web
Services with Spring WS
i
a
D
f
r
f
REST Web Services with Spring
MVC
t
T
O
o
Spring Batch
N
Spring Integration
o
D
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
o
Configure Hibernate applications
with Spring and
S
Spring Transactions
g
y
l
n
i relationships
e
n
Implement inheritancerand
with
JPA and
t
O
p
u
Hibernate
b
S nmanages
g tobjects
i
Discover how Hibernate
l
r
i
a
i
Go more in depth
on n
locking with
Hibernate
s
i
i
c
i
asuch ast D
f
Advanced
features
interceptors, caching and
r
f
batch
OupdatesT No
o
D
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Consulting Offerings
e
c
r
u
o
Expert reviews project or architecture
and shows how
S
to improve
g
y
l
n
e
n
Hyperic Jump Start ri
t
p g O bu your
Helps you startingS
with Hyperic to monitor
i
r
environment l
n
t
i
a
i
s
n
i
Java EE orTomcat
to
tc
Server
Migration
i
c
i
a and
D
fyour application
r
f
Migrate
production environment
t
OServer T No
to tc
Custom consulting
engagements
o
D needs
to fit your specific
Quick Scan
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Resources
e
c
r
u
o
http://www.springsource.org/documentation
S
g
y
Already 800+ pages!
l
n
i
e
n
r
t
O
p
u
b
S blog
The official technical
g
i
l
r
n
t
i
a
http://blog.springsource.com/
i
s
n
i
i
c
i
a tD
f
r
f
T oforums
The Spring
O community
N
http://forum.springframework.org/
o
D
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
10
Resources (2)
e
c
r
u
o
http://jira.springframework.org/
S
g
y
l
n
i
e
n
r
t
The source code is available
here u
O
p
S ng rib
https://src.springsource.org/svn/spring-framework
l
t
i
a
More information
on how
to build
Spring:
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
Follow Spring development
o
D
http://blog.springsource.com/2009/03/03/building-spring-3/
https://fisheye.springsource.org/browse/
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
11
Thank You!
e
c
r
We hope you enjoyed the course u
o
S
g
y
l
Please fill out the evaluation
form
on
MyLearn
n
i
e
n
r
t
O
http://www.vmware.com/education
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
12
e
c
r
u
o
S
g
y
l
Object/Relational
Mapping
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Fundamental Concepts
and iConcerns
When
s
n
i
c
i
UsingfO/R
Mapping
in Enterprise
Applications
a
D
r
f
t
T
O
o
N
o
D
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
The Object/Relational mismatch
o
S
ORM in context
g
y
l
n
Benefits of O/R Mapping
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
The Object/Relational
Mismatch (1)
e
c
r
u
A domain object model is designed
to serve
o
the needs of the application
S
g
y
Organize data into abstract
concepts
that prove
l
n
i problem
e
n
useful to solving the r
domain
t
O
p
u
Encapsulate behavior
specific
to
the
application
b
S
g
i
l
r
Under the control of the
application
developer
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
The Object/Relational
Mismatch (2)
e
c
r
u
Relational models relate business
data and are
o
typically driven by other factors:
S
g
y
Performance
l
n
i
e
n
r
t
Space
O
p
u
b
S ngdatabase
Furthermore, a relational
schema
i
l
r
t
i
often:
a
i
s
n
i
i
c
Predatesi the application
a
D
f
r
f
t
Is shared with
other applications
T
O
o
Is managed by a separate
N DBA group
o
D
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Object/Relational Mapping
e
c
r
u
Object/Relational Mapping (ORM)
engines exist
o
to mitigate the mismatch S
g
y e
Spring supports all of ithe
majorlones:
n
n
r
t
Hibernate
O
p
u
S ng rib
EclipseLink
l
i
a
Other JPA (Java
Persistence
API)timplementations,
i
s
n
i
i
c
such as iOpenJPA
a
D
f
r
f
t Hibernate
This O
session will
T focusoon
N
o
D
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
The Object/Relational Mismatchu
o
S
ORM in context
g
y
l
n
Benefits of modern-day
ORM engines
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
ORM in context
e
c
r
u
For the Reward Dining domain
o
The database schema alreadyS
exists
g
Several applications share
the dataly
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
NDatabase
o
D
Reward Network
Legacy
Apps?
Account Management
Portal
SQL
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
Merchant
Reporting
Mapping to a legacy
schema is much harder
than starting fresh.
7
e
c
r
In an object-oriented language,ucohesive fineo
grained classes provide encapsulation
and
S
g
y
express the domain naturally
l
n
i
e
n
r
t
In a database schema,
granularity
is
typically
O
p
u
b
S nand
driven by normalization
g performance
i
l
r
t
i
considerations
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
just one examplerc
u
Domain Model in Java
Table in Database
o
S
CUSTOMER
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Customer
- customerId
- firstName
- lastName
EmailAddress
PhoneNumber
Address
- streetNumber
- streetName
- city
- state
- zipCode
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
CUST_ID <<PK>>
FIRST_NAME
LAST_NAME
EMAIL
PHONE
STREET_NUMBER
STREET_NAME
CITY
STATE
ZIP_CODE
e
c
r
u
In Java, there is a difference between
Object
o
identity and Object equivalence:
S
g memory
y
x == y
identityn
(same
address)
l
i
e
n
r
t
x.equals(y)
equivalence
O
p
u
b on
S nisgbasedrsolely
In a database, identity
i
l
t
i
primary keys:
a
i
s
n
i
i
c
x.getEntityId().equals(y.getEntityId())
i
a tD
f
r
f
T o
O
N
o
D
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
10
e
c
r
u
When working with persistent Objects,
the
o
identity problem leads to difficult
challenges
S
g
y
Two different Java objects
may correspond
to the
l
n
e
n
same relational row ri
t
O
p
u
But Java says they
are
not
equal
S ng rib
l
Some of the a
challenges:
t
i
i
s
n
i
i
c
Implement
equals() to accommodate this scenario
i
a
D
f
r
f
Determine when to update
and when to insert
t
T
O
o
Avoid duplication when
N adding to a Collection
o
D
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
11
O/R Mismatch:
Inheritance and Associations (1)
e
c
r
In an object-oriented language:u
o
IS-A relations are modeled with
inheritance
S
g
y
HAS-A relations are modeled
with composition
l
n
i
e
n
r
t
In a database schema,
relations
areulimited to
O
p
b
S nbyg foreign
what can be expressed
keys
i
l
r
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
12
O/R Mismatch:
Inheritance and Associations (2)
e
c
r
u
Bi-directional associations are common
in a
o
domain model (e.g. Parent-Child)
S
g
y
This can be modeled naturally
in each
Object
l
n
i
e
n
r
t
In a database:
O
p
u
b
Sprovides
One side (parent)
a primary-key
g
i
l
r
n
t
i
a
Other side (child)
provides
a
foreign-key
reference
i
s
n
i
i
c
i
For many-to-many
associations,
the database
a
D
f
r
f
t
schema
requires
a
join
table
T
O
o
N
o
D
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
13
e
c
r
The Object/Relational Mismatchu
o
S
ORM in Context
g
y
l
n
Benefits of O/R Mapping
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
14
Benefits of ORM
e
c
r
u
Object Query Language
o
S
Automatic Change Detection
g
y
l
n
Persistence by Reachability
i
e
n
r
t
O
p
u
Caching
S ng rib
Per-Transaction
(1 Level)
l
t
i
a
i
Per-DataSource (2 n
Level) is
i
c
i
a tD
f
r
f
T o
O
N
o
D
st
nd
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
15
e
c
r
u
When working with domain objects,
it is more
o
natural to query based on objects.
S
g
y
Query with SQL:
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T
O
o
Query with object properties
and associations:
N
o
D
SELECT c.first_name, c.last_name, a.city, ...
FROM customer c, customer_address ca, address a
WHERE ca.customer_id = c.id
AND
ca.address_id = a.id
AND
a.zip_code = 12345
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
16
e
c
r
u
When a unit-of-work completes,
all modified
o
state will be synchronized with
the database.
S
g
y
l
n
i
e
n
r
t
Service
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Database
Repository1
invoke(input)
Repository2
UnitOfWork
begin
find
find
modify
commit
flush
output
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
17
Persistence by Reachability
e
c
r
u
When a persistent object is being
managed,
o
other associated objects may
become managed
S
g
y
transparently:
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Order order = orderRepository.findByConfirmationId(cid);
// order is now a managed object retrieved via ORM
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
18
(Un)Persistence by Reachability
= Make Transient
e
c
r
u
The same concept applies for deletion:
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Order order = orderRepository.findByConfirmationId(cid);
// order is now a managed object retrieved via ORM
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
19
Caching
e
c
r
u
The first-level cache (1LC) is scoped
at the
o
level of a unit-of-work
S
g
y
When an object is first loaded
fromlthe
database
n
e
within a unit-of-work r
it iis stored n
in this cache
t
O
p
u
Subsequent requests
to
load
that
same
entity from
b
S
g
i
l
the database will
hit thisncache first
r
t
i
a
i
s
n
The second-level
cache
(2LC)
is scoped at the
i
i
c
i
a tD
f SessionFactory
level offthe
r
O trips Tto database
o
Reduce
for read-heavy data
N
Especially usefulowhen a single application has
exclusive access
D to the database
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
20
Summary
e
c
r
u
o
Especially if caching is involved
S
g
y
Especially on a shared, legacy
schema
with existing
l
n
i
e
n
applications
r
t
O
p
u
The ORM overcomes
some
of
these
problems
b
S
g
i
l
r
n
Automatic change
detection,
queries,
caching
t
i
a
i
s
n
i
Ideal if your
application
owns
its
database
i
c
i
a tD
fa magic-bullet
r
f
It is not
T o
O
N
o
D
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
21
e
c
r
u
o
S y with
Object/RelationalgMapping
l
n
i
e
n
Spring and
Hibernate
r
t
O
p
u
S ng rib
l
t
i
a
i
ORM Simplification
using
Spring
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
Introduction to Hibernate u
o
Mapping
S
g
y
Querying
l
n
i
e
n
r
t
Configuring a Hibernate
SessionFactory
O
p
u
b
S Hibernate
g
Implementing Native
i
DAOs
l
r
n
t
i
a
i
Exception c
Mapping
s
n
i
i
i
a tD
f
r
f
T o
O
N
o
D
2
Introduction to Hibernate
e
c
r
u
A SessionFactory is a thread-safe,
shareable
o
object that represents a single
data source
S
g
y
Provides access to a transactional
Session
l
n
i Spring
e
n
r
t
Ideal candidate for a singleton
bean
O
p
u
S ng rib
l
t
a
Hibernates iSession
isi a stateful
object
s
n
i
i
c
representing
a
unit-of-work
i
a
D
f
r
f
t
Session
Often corresponds
at a higher-level
to a JDBC
T
O
o
Connection
N
Manages persistent
objects within the unit-of-work
o
D
Acts as a transaction-scoped
cache (1LC)
3
Hibernate Mapping
e
c
r
Hibernate requires metadata u
o
for mapping classes to database
tables
S
g
y
and their properties to columns
l
n
i
e
n
r
t
O
p
u
b
Metadata can beS
annotations
or iXML
g
l
r
n
t
i
a
This sessioni will present JPA annotations
s
n
i
i
c
XML shown
in theaappendixD
i
f
r
f
t
T
O
o
N
o
D
Customer
firstName: String
dob: Date
...
???
Customer
PK
FIRST_NAME
DATE_OF_BIRTH
Annotations support in
Hibernate
e
c
r
u
o
Since Hibernate 3.5
S
javax.persistence.*
g
y
l
n
Suitable for most needsi
e
n
r
t
O
p
u
b
S
g
i
l
Hibernate Specific Extensions
r
n
t
i
a
i
s
n
In addition
to
JPA annotations
i
i
c
i
a tD
f
r
f
T o
O
Less important sinceN
JPA 2
o
D
Hibernate supports all JPA 2 annotations
e
c
r
u
o
Applies to the entire class (such
as table properties)
S
g
y
Data-members
l
n
i
e
n
r
t
Typically mapped to a column
O
p
u
By default, all data-members
treatedib
as persistent
S
g
l
r
n
t
i
a
i
s
n
i
i
c
i
aaccessed
D
f
r
f
All data-members
directly
t
T o
O
N
o
D
Classes
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Entity
@Entity
@Table(name=
@Table(name= T_CUSTOMER)
T_CUSTOMER)
public
public class
class Customer
Customer {{
@Id
@Id
@Column
@Column (name=cust_id)
(name=cust_id)
private
private Long
Long id;
id;
Mark as an entity
Optionally override
table name
@Column
@Column (name=first_name)
(name=first_name)
private
private String
String firstName;
firstName;
Optionally override
column names
@Transient
@Transient
private
private User
User currentUser;
currentUser;
public
public void
void setFirstName(String
setFirstName(String firstName)
firstName) {{
this.firstName
this.firstName == firstName;
firstName;
}}
...
... Only @Entity and @Id are mandatory
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Entity
@Entity
@Table(name=
@Table(name= T_CUSTOMER)
T_CUSTOMER)
public
public class
class Customer
Customer {{
private
private Long
Long id;
id;
private
private String
String firstName;
firstName;
@Id
@Id
@Column
@Column (name=cust_id)
(name=cust_id)
public
public String
String getId()
getId()
{{ return
return this.id;
this.id; }}
@Column
@Column (name=first_name)
(name=first_name)
public
public String
String getFirstName()
getFirstName()
{{ return
return this.firstName;
this.firstName; }}
Beware of Side-Effects
getter/setter methods
may do additional work
such as invoking listeners
public
public void
void setFirstName(String
setFirstName(String name)
name)
{{ this.firstName
this.firstName == name;
name; }}
}}
8
e
c
r
u
o
Propagate all operations
S
to y
the underlying objects
g
@Id
@Id
l
n
i
e
@Column
) r
n
@Column (name
(name
t
O
p
u
b
S
g
i
l
r
n
@OneToMany(
@OneToMany( a
t
i
i
s
@JoinColumn
))
n
@JoinColumn (name
(name
i
i
c
i
a tD
f
r
f
O JoinTableTalso N
o
supported, more
commonly
used in
o
@ManyToMany
D associations
@Entity
@Entity
@Table(name
@Table(name== T_CUSTOMER
T_CUSTOMER))
public
public class
class Customer
Customer {{
private
private Long
Long id;
id;
=cust_id
=cust_id
cascade=CascadeType.ALL)
cascade=CascadeType.ALL)
=cust_id
=cust_id
private
private Set<Address>
Set<Address> addresses;
addresses;
Foreign key in
Address table
e
c
r
u
Provides methods to manipulateo
entities
S
g
y
l
n
Create queries using Hibernate
Query
Language
i
e
n
r
t
O
Manages transactions
p
u
b
S class:
g
i
JPA defines a similar
EntityManager
l
r
n
t
i
a
i
s
Sessions more
popular
thaniEntityManagers
n
i
c
i
a beforet D
f
Already
widely
used
JPA
r
f
T hybridoapplications
O to write
Common
N
Session
o
D
Hibernate's key class is the Session
persist, delete, get
10
Hibernate Querying
e
c
r
u
Hibernate provides several options
for
o
accessing data
S
g
Retrieve an object by primary
key ly
n
i
e
n
t
Query for objects withrthe Hibernate
Query
Language
O
p
u
(HQL)
b
S
g
i
l
r
Query for objects usingin
Criteria Queries
t
a
i
s
n
Execute standard
SQL
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
11
Hibernate Querying: by
primary key
e
c
r
u
To retrieve an object by its database
identifier
o
simply call get(..) on the Session
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a if no object
D
returns r
null
exists for the identifier
f
f
t
T
O
o
N
o
D
Long custId = new Long(123);
Customer customer = (Customer) session.get(Customer.class, custId);
12
e
c
r
u
To query for objects based on properties
or
o
associations use HQL
S
g ly
Pre Java 5 API, not typen
aware
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
No generics
i
a
D
f
r
f
t
T
O
o
N
o
Must cast
D
Query query = session.createQuery(
from Customer c where c.address.city = :city);
query.setString(city, Chicago);
List customers = query.list();
13
e
c
r
u
Introduction to Hibernate
o
Configuring a Hibernate S
SessionFactory
g
y
l
n
Implementing Native Hibernate
DAOs e
i
n
r
t
O
u
Exception Mappingp
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
14
Configuring a
SessionFactory (1)
e
c
r
u
Hibernate implementations of data
access code
o
require access to the SessionFactory
S
g
y
l
The SessionFactory requires
n
i
e
n
r
t
DataSource (local orp
container-managed)
O
u
S ng rib
Mapping metadata
l
t
i
a
Spring provides
a FactoryBean
for configuring a
i
s
n
i
i
c
i
shareable
SessionFactory
a tD
f
r
f
Hibernate
Spring 3
Supports
T V4 from
O
o
in hibernate2, hibernate3,
There are different versions
N
hibernate4 packages
o
D
15
Configuring a
SessionFactory (2)
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
Mapping
D Metadata
OrderServiceImpl
Hibernate
OrderRepository
Annotation
Session
FactoryBean
creates
SessionFactory
DataSource
16
SessionFactory and
annotated classes
e
c
Spring 3.1
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a t D Entities listed one by one
f
r
f
T o
O
- wildcards not supported
N
o
D
e
c
r
u
o
Wildcards are supported
S
y
Also scans all sub-packagesg
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Spring 3.1
e
c
r
u
Introduction to Hibernate
o
S
Configuring a Hibernate SessionFactory
g
y
l
n
Implementing Native
Hibernate
DAOs
i
e
n
r
t
O
u
Exception Mappingp
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
19
e
c
r
u
Since Hibernate 3.1+
o
Hibernate provides hooks soS
Spring can manage
transactions and Sessionsg
in a transparent
fashion
y
l
n
i exception
e
n
Use AOP for transparent
translation
to
r
t
O
p
u
Springs DataAccessException
hierarchy
S ng rib
l
t
i
a
i
s
n
i
No dependency
on
Spring
in
your DAO
i
c
i
a tD
f
implementations
r
f
T HibernateTemplate
O to require
o
Used
(obsolete)
N
o
D
20
Spring-managed Transactions
and Sessions (1)
e
c
r
u
Transparently participate in Spring-driven
o
transactions
S
g
Beans toly
build the
use one of Springs Factory
n
i
e
n
SessionFactory
r
t
p g Ocodebu
Provide it to the S
data access
i
l
r
dependency a
injection in
t
i
s
n
i
i
c
Define aftransaction
manager
i
a
D
r
f
t
HibernateTransactionManager
T
O
o
JtaTransactionManager
N
o
D
21
Spring-managed Transactions
and Sessions (2)
e
c
r
u
The code with no Spring dependencies
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Spring-managed
Transactions (3)
e
c
r
u
The configuration
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<beans>
<bean id=sessionFactory
class=org.springframework.orm.hibernate3.
annotation.AnnotationSessionFactoryBean>
...
</bean>
<bean id=orderRepository class=HibernateOrderRepository>
<constructor-arg ref=sessionFactory/>
</bean>
<bean id= transactionManager
class=org.springframework.orm.hibernate3.HibernateTransactionManager>
<property name=sessionFactory ref=sessionFactory/>
</bean>
</beans>
could use JtaTransactionManager if needed
23
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Spring AOP Proxy
invoke(input)
Spring
Hibernate
TransactionInterceptor
OrderRepository
begin
commit
OrderServiceImpl
get order data
Hibernate
TransactionManager
new
session
close
session
SessionFactory
getCurrentSession
OrderRepository
24
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
invoke(input)
Spring
Hibernate
TransactionInterceptor
OrderRepository
Service
proxy handles
transaction begin
commit
HibernateTransaction
Manager
begin
txn
JTA
commit
txn
join
txn
OrderServiceImpl
get order
data
OrderRepository
getCurrent
Session
SessionFactory
find
order
Session
25
Spring-managed
Transactions (4)
e
c
r
u
Best practice: use read-only transactions
when
o
you don't write anything toS
the database
g
y
l
Prevents Hibernate from
flushing
its session
n
i
e
n
r
t
possibly dramatic performance
improvement
O
p
u
b
SConnection
g
Also marks JDBC
asriread-only
l
n
t
i
a
provides additional
safeguards
with
some databases
i
s
n
i
i
c
i
for example:
Oracle
only accepts
SELECT statements
a
D
f
r
f
t
T
O
o
N
o
D
@Transactional(readOnly=true)
public List<RewardConfirmation> listRewardsFrom(Date d) {
// read-only, atomic unit-of-work
}
26
e
c
r
u
Introduction to Hibernate
o
S
Configuring a Hibernate SessionFactory
g
y
l
n
Implementing Native Hibernate
DAOs e
i
n
r
t
O
p
u
Exception Mapping
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
27
Transparent Exception
Translation
e
c
r
u
Used as-is, the previous DAO implementation
o
can throw an access specific
HibernateException
S
g
y
Propagate up to the caller
l
n
i
e
n
r
t
O
p
u
Introduces dependency
on
specific
persistence
b
S
g
i
l
solution that should notn
exist
r
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
O AOP Tto convert
o
Can use
them to Springs rich
N hierarchy
DataAccessException
o
Hides access D
technology used
service layer or other users of the DAOs
28
Exception Translation
Using @Repository
e
c
r
Spring provides this capability outu
of the box
o
Annotate with @Repository S
g
y
Define a Spring-provided BeanPostProcessor
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@Repository
public class HibernateOrderRepository implements OrderRepository {
...
}
<bean class=org.springframework.dao.annotation.
PersistenceExceptionTranslationPostProcessor/>
29
e
c
r
Can't always use annotations u
o
For example with a third-party
repository
S
g
y
Use XML to configure instead
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<aop:config>
<aop:advisor pointcut=execution(* *..OrderRepository+.*(..))
advice-ref=persistenceExceptionInterceptor />
</aop:config>
30
Summary
e
c
r
u
o
Repositories have no Spring dependency
S
g lysession
Use Spring to configuren
Hibernate
i
e
n
r
t
factory
O
p
u
Works with Spring-driven
transactions
b
S
g
i
l
r
n
t
Optional translation
to DataAccessExceptions
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
Spring-Hibernate 3 day in-depth Hibernate course
o
D
31
e
c
r
u
o
S
g
y
l
LAB
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Using Hibernate
with
Spring
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
Introduction to Hibernate
o
S
Configuring a Hibernate SessionFactory
g
y
l
n
Implementing Native Hibernate
DAOs e
i
n
r
t
O
u
Exception Mappingp
b
S
g
i
l
r
Appendix
n
t
i
a
i
s
n
XML Metadata
i
i
c
i
a tD
f
Configuration
r
f
T o
O
HibernateTemplate
N
o
D
33
Metadata in XML
e
c
r
u
o
JPA defines an XML syntax (orm.xml)
S
g
y
In practice rarely used
l
n
i
e
n
Most JPA users, use annotations
r
t
O
p
u
S ng rib
l
Hibernate XML
t
i
a
i
s
n
i
i
c
Predatesiannotations and JPA
a
D
f
r
f
Still extensively
used in older
applications
t
T
O
o
Will be shown here N
o
D
JPA XML
34
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Different defaults:
public
public class
class Customer
Customer {{
private
private Long
Long id;
id;
private
private String
String firstName;
firstName;
public
public void
void setFirstName(String
setFirstName(String firstName)
firstName) {{
this.firstName
this.firstName == firstName;
firstName;
}}
property access (default) uses setter
...
...
<hibernate-mapping package=org.xyz.customer>
field access
<class name=Customer table= T_CUSTOMER>
<id name=id column=cust_id access=field/>
<property name=firstName column=first_name/>
</class>
</hibernate-mapping>
Suggestion: put default-access=field in <class>
35
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
36
e
c
r
u
Introduction to Hibernate
o
S
Configuring a Hibernate SessionFactory
g
y
l
n
Implementing Native Hibernate
DAOs e
i
n
r
t
O
p
u
Appendix
S ng rib
XML Metadata l
t
i
a
i
s
Configuration
n
i
i
c
i
a tD
f
HibernateTemplate
r
f
T o
O
N
o
D
37
Configuring a SessionFactory
with XML Metadata
e
c
r
u
o
Define XML mappling-locations
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o Wildcards are supported
O
N
o
D
<bean id=sessionFactory
class=org.springframework.orm.hibernate4.LocalSessionFactoryBean>
<property name=dataSource ref=dataSource/>
<property name=mappingLocations>
<list>
<value>classpath:example/Customer.hbm.xml</value>
<value>classpath:example/Address.hbm.xml</value>
</list>
</property>
</bean>
Prior to Spring 3.1, use class in hibernate3 package
38
Mixing Metadata
e
c
r
u
o
S
g
y
Migration
l
n
i
e
n
r
t
O
p
u
Some features better
defined
using XML
b
S
g
i
l
r
n
t
i
a
i
s
n
i
i
c
LocalSessionFactoryBean
supports both
i
a
D
f
r
f
AnnotationSessionFactoryBean
prior to Spring 3.1
Use the
t
T
O
o
N LocalSessionFactory
o
D
Can use annotations and XML together
Why do this?
Sub-classes LocalSessionFactory
Functionality now moved to
39
Configuring a SessionFactory
with Both
e
c
Spring 3.1
r
u
o
S
Can use
g
y
l
n
annotations
and
i
e
n
r
t
XML in same
O
p
u
S ng rib application
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<bean id=sessionFactory
class=org.springsource.orm.hibernate4.annotation.LocalSessionFactoryBean>
e
c
r
u
Introduction to Hibernate
o
S
Configuring a Hibernate SessionFactory
g
y
l
n
Implementing Native Hibernate
DAOs e
i
n
r
t
O
p
u
Appendix
S ng rib
XML Metadata l
t
i
a
i
s
Configuration
n
i
i
c
i
a tD
f
HibernateTemplate
r
f
T o
O
N
o
D
41
HibernateTemplate
e
c
r
u
Consistent with Springs general
DAO support
o
Manages resources (acquiring/releasing
Sessions)
S
g
y
Provides convenience methods
l
n
i
e
n
r
t
O
p
u
Throws DataAccessExceptions
S ng rib
l
t
Native approach
recommended
since
i
a
i
s
i
Hibernateic
3.1+ ain
D
f
r
f
Preferred by T
most Hibernate
& Spring developers
t
O
o
No Spring dependencies
in DAO
N
HibernateTemplate
no longer recommended
o
D
findBy*, getSession,
42
Topics Covered
e
c
r
u
Introduction to Hibernate
o
S
Configuring a Hibernate SessionFactory
g
y
l
n
Implementing Native Hibernate
DAOs e
i
n
r
t
O
p
u
Appendix: XML
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
Spring-Hibernate o
3 day in-depth Hibernate course
D
43
e
c
r
u
o
S
g
y
l
Spring Web
Services
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Implementing Loosely
Coupled
Communication
s
n
i
i
c
i
with Spring
WebD
Services
a
f
r
f
t
T
O
o
N
o
D
Copyright 2007-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
Introduction to Web Services
o
Why use or build a web service?
S
g
y
Best practices for implementing
a web
service
l
n
i
e
n
r
t
Spring Web Services
O
p
u
b
g
Client access l S
i
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
2
e
c
r
u
o
S
Loosely coupled systems are
considered useful
g
y
l
when either the source
or
the
destination
n
i
e
n
r
t
computer systems p
are subject
to frequent
O
u
S ng rib
changes
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
Loose coupling o
increases tolerance
D not cause incompatibility
changes should
Wikipedia (July 2007)
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
XML is understoodp
by all major
platforms
O
u
b
S in Java
SAX, StAX or DOM
g
i
l
r
n
t
i
a
System.XML
or
.NET
XML
Parser
in
.NET
i
s
n
i
i
c
REXML or
XmlSimple
in
Ruby
i
a
D
f
r
f
t
Perl-XML or XML::Simple
in Perl
T
O
o
N
o
D
XML is the lingua franca in the world of
interoperability
e
c
r
u
o
S
g
y
l
n
Design contract independently
fromn
service interface
i
e
r
t
O
Refrain from using stubs
and skeletons
p
u
b
S ngfor incoming
i
Consider skippingl validation
requests...
r
t
i
a
i
and using Xpath
to only
extract
what
you need
s
n
i
i
c
i
a law:
D
f
Postels
r
f
t
T
Be conservative
in what you do;
O
o
be N
liberal in what you accept from others.
o
D
Remember:
e
c
r
u
o
S
The Web GUI layer
g
y
l
n
provides compatibility ri
e
n
t
O
u
between HTML-basedp
S ng rib
world of the user (the
l
t
i
a
i
s
browser) and c
the OO-in
i
i
a tD
f
based world
of your
r
f
T o
service O
N
o
D
6
e
c
r
u
o
S
Web Service layer
g
y
l
n
provides compatibility ri
e
n
t
O
u
between XML-based p
S ng rib
world of the user and
l
t
i
a
i
s
the OO-based
world of
n
i
i
c
i
a tD
f
your service
r
f
T o
O
N
o
D
7
e
c
r
Introduction to Web Services u
o
Why use or build a web service?
S
g
y
Best practices for implementing
a web
service
l
n
i
e
n
r
t
Spring Web Services
O
p
u
b
g
Client access l S
i
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
8
e
c
r
u
o
Start with XSD/WSDL
S
g
y
Widely considered a Best
Practice
l
n
i
e
n
r
t
Solves many interoperability issues
O
p
u
S ng rib
Also consideredl difficult
t
i
a
But isnt
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Contract-first in 3 simple
steps
e
c
r
u
o
S
g
y
Trang
l
n
i
e
n
r
t
Microsoft XML to Schema
O
p
u
XML Spy
S ng rib
l
t
i
a
Tweak resulting
contract
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
10
Sample Message
e
c
r
u
o
S
g
y
<transferRequest xmlns=http://mybank.com/schemas/tr
l
n
e
n
amount=1205.15> ri
t
O
p
u
<credit>S123</credit>
b
S
g
i
l
<debit>C456</debit>
r
n
t
i
a
i
s
</transferRequest>
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Namespace for this message
11
<transferRequest
amount=1205.15>
<credit>S123</credit>
<debit>C456</debit>
</transferRequest>
e
c
r
u
<xs:schema
o
xmlns:xs="http://www.w3.org/2001/XMLSchema"
S
xmlns:tr="http://mybank.com/schemas/tr"
g
y e
l
elementFormDefault="qualified" in
n
r
t
targetNamespace="http://mybank.com/schemas/tr">
O
p
u
<xs:element name="transferRequest">
S ng rib
<xs:complexType> l
t
i
<xs:sequence> ia
s
n
i
i
c
<xs:element
name="credit"
type="xs:string"/>
i
a
D
f
r
f
<xs:element
name="debit"
type="xs:string"/>
t
T
O
</xs:sequence>
o
N type="xs:decimal"/>
<xs:attribute name="amount"
</xs:complexType> o
D
</xs:element>
</xs:schema>
12
Type constraints
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
1 Character + 3 Digits
13
SOAP Message
e
c
r
u
o
Header
S
g
Security
y
l
n
i
e
n
r
t
Routing
O
p
u
S ng rib
l
t
i
Body ia
s
n
i
i
c
TransferRequest
i
a tD
f
r
f
T o
O
N
o
D
Envelope
14
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
<SOAP-ENV:Envelope xmlns:SOAPENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Body>
<tr:transferRequest xmlns:tr="http://mybank.com/schemas/tr"
tr:amount=1205.15>
<tr:credit>S123</tr:credit>
<tr:debit>C456</tr:debit>
</tr:transferRequest>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
15
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Client Process
XML
XML Processing
SOAP
SOAP Framework
XML
SOAP Framework
XML Processing
WS
Template
Server Process
Endpoint
16
Request Processing
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Message
Dispatcher
Endpoint
Mapping
Endpoint
Adapter
Endpoint
getEndpoint(
MessageContext)
invoke(MessageContext, selectedEndpoint)
17
e
c
r
u
o
<context-param>
S
g
<param-name>contextConfigLocation</param-name>
y
l
n
i
<param-value>
e
n
r
t
/WEB-INF/transfer-app-cfg.xml
O
p
u
b
S
</param-value>
g
i
l
r
n
</context-param> a
t
i
i
s
n
i
i
c
a
<listener> fi
D
r
f
t
<listener-class>
T
O
o
org.springframework.web.context.ContextLoaderListener
N
</listener-class>
o
</listener>
D
18
e
c
r
u
o
S
g
<servlet>
y
l
n
i
<servlet-name>transfer-ws</servlet-name>
e
n
r
t
<servlet-class>..ws..MessageDispatcherServlet</servlet-class>
O
p
u
S ng rib
<init-param>
l
<param-name>contextConfigLocation</param-name>
t
i
a
i
s
n
<param-value>/WEB-INF/ws-config.xml</param-value>
i
i
c
i
a tD
f
</init-param>
r
f
</servlet>
T o
O
N
o
D
19
Map the
MessageDispatcherServlet
e
c
r
u
o
<servlet-mapping>
S
<servlet-name>transfer-ws</servlet-name>
g
y
l
n
<url-pattern>/services/*</url-pattern>
i
e
n
r
t
</servlet-mapping>
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
20
Endpoint
e
c
r
u
o
S
g ly
Handle input message n
i
e
n
r
t
Call method on business service
O
p
u
Create response message
S ng rib
l
t
i
a
With Spring-WS
you can
focus
on the Payload
i
s
n
i
i
c
i
Switching
a totPOX
D without code
f from SOAP
r
f
T o
change
O
N
o
D
Endpoints handle SOAP messages
Similar to MVC Controllers
21
e
c
r
u
o
DOM (JDOM, dom4j, XOM)
S
g
y
SAX
l
n
i
e
n
StAX
r
t
O
p
u
Marshalling
S ng rib
l
t
JAXB (1 and 2)
i
a
i
s
n
i
i
c
Castor i
a
D
f
r
f
XMLBeans
t
T
O
o
XPath argument binding
N
o
D
Low-level techniques
22
JAXB 2
e
c
r
JAXB 2 is part of Java EE 5 and u
JDK 6
o
Uses annotations for mapping
metadata
S
g
yand vice-versa
l
Generates classes fromin
a schema
e
n
r
t
O
Supported as part of
Spring-OXM
p
u
b
S
g
i
l
<oxm:jaxb2-marshaller id="marshaller"
contextPath="rewards.ws.types"/>
r
n
t
i
a
i
s
n
i
i
c
i
No explicit
marshaller
bean
definition necessary
a
D
f
r
f
to beO
used in Spring-WS
T ot 2.0 endpoints
N needed for annotation-based
<!-- registers all infrastructure beans
endpoints, incl. JABX2o
(un)marshalling: -->
D
<ws:annotation-driven/>
23
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
@PayloadRoot(localPart="transferRequest",
i
a
D
f
r
f
t
namespace="http://mybank.com/schemas/tr")
T
O
o
public @ResponsePayload TransferResponse
newTransfer(
N
@RequestPayload
TransferRequest request) {
o
// extract necessaryD
info from request and invoke service
@Endpoint
Spring WS Endpoint
public class TransferServiceEndpoint {
private TransferService transferService;
@Autowired
public TransferServiceEndpoint(TransferService transferService) {
this.transferService = transferService;
Mapping
}
e
c
r
u
o
S
y
Saves writing lots of trivial g
XML bean
definitions
l
n
i classesnthat belong
e
Just make sure not to r
scan
in the
t
O
u
root context insteadp
S ng rib
l
<!-- instead of defining
explicitiendpointstbeans
a
i
s
n
i
we rely onicomponent
scanning:
-->
i
c
a base-package="transfers.ws"/>
D
f
<context:component-scan
r
f
t
T
O
o
N beans needed for
<!-- registers all infrastructure
o
annotation-based endpoints,
incl. JAXB2 (un)marshalling:
D
-->
<ws:annotation-driven/>
25
e
c
r
u
Clients
o
S
g
y
l
n
i
e
n
r
t
Web Service
LayerO
p
u
b
S context)
(application
g
i
l
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
TApplicationoLayer
O
(application
N context)
o
D
JVM
26
Further Mappings
e
c
r
u
o
Message Payload
S
g
y
SOAP Action Header
l
n
i
e
n
WS-Adressing
r
t
O
p
u
XPath
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
27
e
c
r
u
o
S
<ws:dynamic-wsdl id="transferDefinition"
g
y
l
n
portTypeName="Transfers"
i
e
n
r
t
locationUri="http://somehost:8080/transferService/">
O
p
u
<ws:xsd location="/WEB-INF/transfer.xsd"/>
b
S
g
i
l
r
</ws:dynamic-wsdl> a
n
t
i
i
s
n
i
i
c
i
abasedtonDgiven XSD
Generates
WSDL
f
r
f
T of WSDL
id becomes
URL
O part
o
Most useful during N
development
o
Just use staticD
WSDL in production
http://somehost:8080/transferService/transferDefinition.wsdl
28
e
c
r
Introduction to Web Services u
o
Why use or build a web service?
S
g
y
Best practices for implementing
a web
service
l
n
i
e
n
r
t
Spring Web Services
O
p
u
b
g
Client access l S
i
r
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
29
e
c
r
u
WebServiceTemplate
o
Simplifies web service accessS
g
y
Works directly with the XML
payload
l
n
i
e
n
r
t
O
p
u
b
S
g
i
l
r
n
Can use marshallers/unmarshallers
t
i
a
i inmethodsisfor sending and
Providesic
convenience
a messages
D
f web service
receiving
r
f
t
T
O callbacks for
o
Provides
more sophisticated usage
N
o
D
Extracts body of a SOAP message
Also works with POX (Plain Old XML)
30
Marshalling with
WebServiceTemplate
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
WebServiceTemplate ws = context.getBean(WebServiceTemplate.class);
N
TransferRequest request = new
TransferRequest(S123, C456, 85.00);
o
Dws.marshalSendAndReceive(request);
Receipt receipt = (Receipt)
<bean id=webServiceTemplate
class=org.springframework.ws.client.core.WebServiceTemplate>
<property name=defaultUri value=http://mybank.com/transfer/>
<property name=marshaller ref=marshaller/>
<property name=unmarshaller ref=marshaller/>
</bean>
31
e
c
r
u
o
S
g
y
l
LAB
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
Exposing SOAP
Endpoints
using
s
n
i
i
c
i
a WebtServices
D
f
Spring
r
f
T o
O
N
o
D
Copyright 2007-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
o
Practical RESTgS
services
y
l
n
i MVC
e
n
with Spring
r
t
O
p
u
S ng rib
l
t
i
a
i
Using Spring MVC
to build
RESTful web
s
n
i
i
c
i
services
a
D
f
r
f
t
T
O
o
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.
e
c
r
u
REST introduction
o
S
REST and Java
g
y
l
n
Spring MVC support for
RESTful
applications
i
e
n
r
t
Request/Response Processing
O
p
u
S ng rib
Using MessageConverters
l
t
i
a
Content Negotiation
i
s
n
i
i
c
i
Puttingfit
all together
a tD
r
f
RESTful
O clientsTwithNthe
o RestTemplate
Conclusion
o
D
2
REST Introduction
e
c
r
u
o
Programmatic clients can alsoS
connect via HTTP
g
y
Such as: mobile applications,
AJAX l
enabled
web-pages
n
i
e
n
r
t
O
p
u
REST is an architectural
style
that
describes best
b
S
g
i
l
r
n
practices to expose
web
services
over HTTP
t
i
a
i
s
n
i
i
c
REpresentational
State Transfer, term by Roy Fielding
i
a
D
f
r
f
HTTP as application protocol,
not just transport
t
T
O
o
Emphasizes scalability
N
Not a frameworko
or specification
D
e
c
r
u
o
Model nouns, not verbs
S
g
y
http://mybank.com/banking/accounts/123456789
l
n
i
e
n
r
t
Resources support limited set
of
operations
O
p
u
GET, PUT, POST, S
DELETE ingcase of HTTP
b
i
l
r
n
t
All have well-defined
semantics
i
a
i
s
n
i
i
c
Example:fiupdate a
an orderD
r
f
to /orders/123
PUTO
T ot
don't POST to /order/edit?id=123
N
o
D
e
c
r
u
o
Resources can support multiple
representations
S
g
y
HTML, XML, JSON,
l
n
i
e
n
r
t
Representations can link to O
other
resources
p
u
Allows for extensions
and discovery,
like
with web sites
b
S
g
i
l
r
n
t
i
a
Hypermedia iAs The Engine ofsApplication State
n
i
i
c
i
HATEOAS:
Probably
the
world's
worst acronym!
a
D
f
r
f
t
RESTful
responses
contain
the links you need just
T
O
o
like HTML pages do N
o
D
e
c
r
Stateless architecture
u
o
No HttpSession usage
S
y
GETs can be cached on URLg
l
n
itrack of state
e
n
r
Requires clients to keep
t
O
p
u
Part of what makes
it
scalable
b
S
g
i
l
r
n
Looser coupling
between
client and
server
t
i
a
i
s
n
i
i
c
HTTP headers
andastatus codes communicate
i
D
f
r
f
t
result to clients
T
O
o
All well-defined in HTTP
N Specification
o
D
6
Why REST?
e
c
r
u
o
Every platform/language supports
HTTP
S
g
y
l
n
i clients
e
n
Easy to support many r
different
t
O
p
u
b
S
g
i
l
Scalability
r
n
t
i
a
i
s
Support for
redirect,in
caching, different
representations,
i
c
i
a t D
resource
identification,
f
r
f
T but also
Support
other formats
O for XML,
o
N
o
D
Benefits of REST
e
c
r
u
REST introduction
o
S
REST and Java
g
y
l
n
Spring MVC support for
RESTful
applications
i
e
n
r
t
O
p
u
RESTful clients with
the RestTemplate
b
S
g
i
l
r
Conclusion
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
8
e
c
r
u
o
S
g
y
Focuses on programmatic clients,
not
browsers
l
n
i
e
n
r
t
Various implementations
O
p
u
Jersey (RI), RESTEasy,
Restlet,
CXF ib
S
g
l
r
n
t
All implementations
provide
Spring
support
i
a
i
s
n
i
i
c
i
Good option
for
full
REST
support
using a
a
D
f
r
f
t
standard
T
O
o
N clients in standard
No support for building
o
Although some implementations
do offer it
D
e
c
r
u
o
Since version 3.0
S
g
y
Using familiar and consistent
programming
model
l
n
i
e
n
Spring MVC does not implement
JAX-RS
r
t
O
p
u
Offers both programmatic
client support
(HTTPb
S
g
i
l
r
n
based web services)
and
browser
support
t
i
a
i
s
n
i
i
c
(RESTful web
applications)
i
a
D
f
r
f
t
Includes
RestTemplate
for
building
T
O
o
programmatic clients
N in Java
o
D
Spring-MVC provides REST support as well
10
e
c
r
u
REST introduction
o
S
REST and Java
g
y
l
n
Spring MVC supportifor RESTful
applications
e
n
r
t
Request/Response Processing
O
p
u
S ng rib
Using MessageConverters
l
t
i
Putting it allia
together
s
n
i
i
c
i rwith
a thet RestTemplate
D
RESTfulffclients
T o
O
Conclusion
N
o
D
11
e
c
r
u
o
Map requests based on HTTP
method
S
g lURLs
y
URI templates to parsen
'RESTful'
i
e
n
r
t
Will now extend SpringpMVC to O
support REST
u
S ng rib
More Annotations
l
t
i
a
Message Converters
i
s
n
i
i
c
i
aweb applications
D
Support for
f
RESTful
targeting
r
f
t
T
browser-based
clients
is
also
offered
O
o
See HttpMethodFilter N
o
D
Some features have been covered already
12
e
c
r
u
REST introduction
o
S
REST and Java
g
y
l
n
Spring MVC support for
RESTful
applications
i
e
n
r
t
Request/Response
Processing
O
p
u
S ng rib
Using MessageConverters
l
t
i
Putting it allia
together
s
n
i
i
c
i rwith
a thet RestTemplate
D
RESTfulffclients
T o
O
Conclusion
N
o
D
13
e
c
r
u
o
Allows same URL to be mapped
to
multiple methods
S
g
y
Often used for form-based controllers
(GET & POST)
l
n
i resource
e
n
Essential to support RESTful
URLs
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@RequestMapping(value="/orders", method=RequestMethod.GET)
public void listOrders(Model model) {
// find all Orders and add them to the model
}
@RequestMapping(value="/orders", method=RequestMethod.POST)
public void createOrder(HttpServletRequest request, Model model) {
// process the order data from the request
}
14
e
c
r
u
o
Success: 200 OK
S
g
y
Redirect: 302/303 for Redirects
l
n
i
e
n
r
t
Client Error: 404 Not FoundO
p
u
b
S (suchngas unhandled
Server Error: 500
Exceptions)
i
l
r
t
i
a
RESTful applications
use
many additional
codes to
i
s
n
i
i
c
i
communicate
with
their
clients
a
D
f
r
f
t
T
Add @ResponseStatus
to
controller method
O
o
N on HttpServletResponse
don't have to set status
o
manually
D
15
e
c
r
u
o
S
201
g
y
l
n
i
e
n
204
r
t
O
p
u
S ng rib
404
l
t
i
a
i
s
n
i
i
c
405 fi
a tD
r
f
T
O
o
409
N
o
415
D
200
16
@ResponseStatus
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a using
D
f
IMPORTANT:
When
@ResponseStatus
r
f
t
Omethods Tno longer
void
imply a default view name!
o
Nat all
There will be no View
o
This example D
gives a response with an empty body
@RequestMapping(value="/orders", method=RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED) // 201
public void createOrder(HttpServletRequest request,
HttpServletResponse response) {
Order order = createOrder(request);
// determine full URI for newly created Order based on request
response.addHeader("Location",
getLocationForChildResource(request, order.getId()));
}
17
e
c
r
u
o
Determine based on request URL
S
g
y
l
n
i
e
n
r
URL of created child resource
usually
a
sub-path
t
O
p
u
POST to http://www.myshop.com/store/orders
b
S
g
i
l
r
gives http://www.myshop.com/store/orders/123
n
t
i
a
i
s
n
UriTemplate
for encoding
where needed
Can use Spring's
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Location header value must be full URL
18
e
c
r
u
o
Given status code used when S
exception is thrown from
controller method
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@ResponseStatus(HttpStatus.NOT_FOUND) // 404
public class OrderNotFoundException extends RuntimeException {
@RequestMapping(value="/orders/{id}", method=GET)
public String showOrder(@PathVariable("id") long id, Model model) {
Order order = orderRepository.findOrderById(id);
if (order == null) throw new OrderNotFoundException(id);
model.addAttribute(order);
return "orderDetail";
}
19
@ExceptionHandler
e
c
r
u
o
S
y
Method signature similar tog
requestlhandling
method
n
i
e
n
Also supports @ResponseStatus
r
t
O
p
u
S ng rib
l
t
i
@ResponseStatus(HttpStatus.CONFLICT)
// 409
a
i
s
n
i
@ExceptionHandler({DataIntegrityViolationException.class})
i
c
i
fconflict() {ra t D
public void
f
// could
add theT
exception,o
response, etc. as method params
O
}
N
o
D
20
e
c
r
u
REST introduction
o
S
REST and Java
g
y
l
n
Spring MVC support for
RESTful
applications
i
e
n
r
t
Request/Response Processing
O
p
u
S ng rib
Using MessageConverters
l
t
i
Putting it allia
together
s
n
i
i
c
i rwith
a thet RestTemplate
D
RESTfulffclients
T o
O
Conclusion
N
o
D
21
HttpMessageConverter
e
c
r
u
o
S
g
y
l
n
ior JAXB2nmappedtobject*)
e
XML (using JAXP Source
r
O
p
u
Feed data*, i.e. Atom/RSS
b
S
g
i
*
Requires 3 party
l
r
Form-based data
n
t
i
a
libraries on classpath
i
s
n
JSON*
i
i
c
i
a tD
Byte[],ffString, BufferedImage
r
T o
DefineO
HandlerAdapter explicitly
to register other
N
HttpMessageConverters
o
D
22
@RequestBody
e
c
r
u
o
S
g
Enables converters for request
dataly
n
i
e
n
Right converter chosenrautomatically
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
23
@ResponseBody
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
24
Automatic Content
Negotiation
e
c
r
u
o
S
g
y
Based on Accept header in request
l
n
i
e
n
r
t
O
p
u
Each converter has list
of supported
media
types
b
S
g
i
l
r
n
Allows multiple
representations
for a single
t
i
a
i
s
n
i
controller imethod
i
c
faffectingracontrollert Dimplementation
f
Without
O forTcontent-based
o
Alternative
View selection as used
N
without @ResponseBody
o
D
25
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
@RequestMapping(value="/orders/{id}", method=RequestMethod.GET)
@ResponseStatus(HttpStatus.OK) // 200
public @ResponseBody Order getOrder(@PathVariable("id") long id) {
return orderRepository.findOrderById(id);
}
GET
GET/store/orders/123
/store/orders/123
Host:
www.myshop.com
Host: www.myshop.com
Accept:
Accept:application/xml,
application/xml,......
GET
GET/store/orders/123
/store/orders/123
Host:
www.myshop.com
Host: www.myshop.com
Accept:
Accept:application/json,
application/json,......
HTTP/1.1
HTTP/1.1200
200OK
OK
Date:
Date:
Content-Length:
Content-Length:1456
1456
Content-Type:
application/xml
Content-Type: application/xml
<order
<orderid=123>
id=123>
</order>
</order>
HTTP/1.1
HTTP/1.1200
200OK
OK
Date:
Date:
Content-Length:
Content-Length:756
756
Content-Type:
application/json
Content-Type: application/json
{{
"order":
"order":{"id":
{"id":123,
123,"items":
"items":[ [
],],
} }
}}
26
e
c ...
REST methods cannot return HTML, PDF,
r
u
No message converter
o
S
Views better for presentation-rich
representations
g
y
l
n
i
Need two methods on controller
fornsame URL
e
r
t
O
p
u
One uses a converter,
the other
a view
b
S
g
i
l
r
Identify using produces
attribute
n
t
i
a
i
s
n
i
Use consumes
i
to
differentiate
RESTful
POST from an
c
i
a tD
f submission
r
f
HTML form
T o
O
N
o
D
@RequestMapping(value="/orders/{id}", method=RequestMethod.GET,
produces = {"application/json"})
@RequestMapping(value="/orders/{id}", method=RequestMethod.POST,
consumes = {"application/json"})
27
e
c
r
u
Identify RESTful method with o
produces
S method
Call RESTful method fromgView
y
l
n
Implement all logic once
in RESTful
method
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Recommendation
@RequestMapping(value="/orders/{id}", method=RequestMethod.GET,
produces = {"application/json", "application/xml"})
@ResponseStatus(HttpStatus.OK) // 200
public @ResponseBody Order getOrder(@PathVariable("id") long id) {
return orderRepository.findOrderById(id);
}
@RequestMapping(value="/orders/{id}", method=RequestMethod.GET)
public String getOrder(Model model, @PathVariable("id") long id) {
model.addAttribute(getOrder(id)); // Use RESTful method
return "orderDetails";
}
28
e
c
r
u
REST introduction
o
S
REST and Java
g
y
l
n
Spring MVC support for
RESTful
applications
i
e
n
r
t
Request/Response Processing
O
p
u
S ng rib
Using MessageConverters
l
t
i
a
Putting it all
together
i
s
n
i
i
c
i rwith
a thet RestTemplate
D
RESTfulffclients
T o
O
Conclusion
N
o
D
29
Retrieving a Representation:
GET
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
GET
GET/store/orders/123
/store/orders/123
Host:
www.myshop.com
Host: www.myshop.com
Accept:
Accept:application/xml,
application/xml,......
HTTP/1.1
HTTP/1.1200
200OK
OK
Date:
Date:
Content-Length:
Content-Length:1456
1456
Content-Type:
application/xml
Content-Type: application/xml
<order
<orderid=123>
id=123>
</order>
</order>
@RequestMapping(value="/orders/{id}", method=RequestMethod.GET)
@ResponseStatus(HttpStatus.OK) // 200: this is the default
public @ResponseBody Order getOrder(@PathVariable("id") long id) {
return orderRepository.findOrderById(id);
}
30
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
POST
POST/store/orders/123/items
/store/orders/123/items
Host:
www.myshop.com
Host: www.myshop.com
Content-Type:
Content-Type:application/xml
application/xml
<item>
<item>
</item>
</item>
HTTP/1.1
HTTP/1.1201
201Created
Created
Date:
Date:
Content-Length:
Content-Length:00
Location:
Location:
http://www.myshop.com/store/orders/123/items/abc
http://www.myshop.com/store/orders/123/items/abc
@RequestMapping(value="/orders/{id}/items", method=RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED) // 201
public void createItem(@PathVariable("id") long id,
@RequestBody Item newItem,
HttpServletRequest request,
HttpServletResponse response) {
orderRepository.findOrderById(id).addItem(newItem); // adds id to Item
response.addHeader("Location",
getLocationForChildResource(request, newItem.getId()));
}
31
e
c
r
u
o
Use @Value for request properties
S
g
y
Use HttpEntity instead of HttpServletResponse
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Simplify POST
@RequestMapping(value="/orders/{id}/items", method=RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED) // 201
public HttpEntity<?> createItem(@PathVariable("id") long id,
@RequestBody Item newItem,
@Value("#{request.requestURL}") StringBuffer originalUrl) {
orderRepository.findOrderById(id).addItem(newItem); // adds id to Item
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setLocation(getLocationForChildResource(originalUrl, newItem.getId());
return new HttpEntity<String>(responseHeaders);
}
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
PUT
PUT/store/orders/123/items/abc
/store/orders/123/items/abc
Host:
www.myshop.com
Host: www.myshop.com
Content-Type:
Content-Type:application/xml
application/xml
<item>
<item>
</item>
</item>
HTTP/1.1
HTTP/1.1204
204No
NoContent
Content
Date:
Date:
Content-Length:
Content-Length:00
@RequestMapping(value="/orders/{orderId}/items/{itemId}",
method=RequestMethod.PUT)
@ResponseStatus(HttpStatus.NO_CONTENT) // 204
public void updateItem(@PathVariable("orderId") long orderId,
@PathVariable("itemId") String itemId
@RequestBody Item item) {
orderRepository.findOrderById(orderId).updateItem(itemId, item);
}
33
Deleting a Resource:
DELETE
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
DELETE
DELETE/store/orders/123/items/abc
/store/orders/123/items/abc
Host:
www.myshop.com
Host: www.myshop.com
......
HTTP/1.1
HTTP/1.1204
204No
NoContent
Content
Date:
Date:
Content-Length:
Content-Length:00
@RequestMapping(value="/orders/{orderId}/items/{itemId}",
method=RequestMethod.DELETE)
@ResponseStatus(HttpStatus.NO_CONTENT) // 204
public void deleteItem(@PathVariable("orderId") long orderId,
@PathVariable("itemId") String itemId) {
orderRepository.findOrderById(orderId).deleteItem(itemId);
}
34
e
c
r
u
REST introduction
o
S
REST and Java
g
y
l
n
Spring MVC support for
RESTful
applications
i
e
n
r
t
p
u
RESTful clients with
the O
RestTemplate
b
S
g
i
l
r
Conclusion
n
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
35
RestTemplate Introduction
e
c
r
u
Supports URI templates, HttpMessageConverters
and
o
S
custom execute() with callbacks
g
yor String
l
Map or String... for vars, ijava.net.URI
for URL
n
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
HTTP Method
DELETE
GET
RestTemplate Method
HEAD
OPTIONS
POST
PUT
Defining a RestTemplate
e
c
r
u
o
RestTemplate template = new RestTemplate();
S
g
y
l
n
i
e
n
Has default HttpMessageConverters
r
t
O
p
u
Same as on the server,
depending
on
classpath
S ng rib
l
Or use external
configuration
t
i
a
i
s
n
i
i
c
To use Apache
Commons
HTTP
Client, for example
i
a tD
f
r
f
T o
O
N
o
D
Just call constructor in your code
37
e
c
r
u
o
S
g
y
l
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
{id} = 1
e
c
r
u
REST introduction
o
S
REST and Java
g
y
l
n
Spring MVC support for
RESTful
applications
i
e
n
r
t
Request/Response Processing
O
p
u
S ng rib
Using MessageConverters
l
t
i
Putting it allia
together
s
n
i
i
c
i rwith
a thet RestTemplate
D
RESTfulffclients
T o
O
Conclusion
N
o
D
39
Conclusion
e
c
r
u
o
S
g
y
Useful for supporting diverse
clientsland
building highly
n
i
e
n
scalable systems
r
t
O
p
u
Java provides JAX-RS
as standard
specification
b
S
g
i
l
n
Spring-MVC adds
REST
supporttrusing a familiar
i
a
i
s
n
i
programming
model
i
c
i
a tD
f
r
f
Extended
by @Request-/@ResponseBody
T
O
o
Use RestTemplate for
N accessing RESTful apps
o
D
40
e
c
r
u
o
S
g
y
l
LAB
n
i
e
n
r
t
O
p
u
S ng rib
l
t
i
a
i
RESTful applications
with
Spring MVC
s
n
i
i
c
i
a tD
f
r
f
T o
O
N
o
D
Copyright 2005-2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited.