Core Spring
Four Day Workshop
Building Enterprise Applications using Spring
 Copyright 2014 Pivotal. All rights reserved.
Copyright Notice
Copyright  2014 Pivotal Software, Inc. All rights reserved. This manual and its accompanying
materials are protected by U.S. and international copyright and intellectual property laws.
Pivotal products are covered by one or more patents listed at http://www.pivotal.io/patents.
Pivotal is a registered trademark or trademark of Pivotal Software, Inc. in the United States and/or
other jurisdictions. All other marks and names mentioned herein may be trademarks of their respective
companies. The training material is provided as is, and all express or implied conditions,
representations, and warranties, including any implied warranty of merchantability, fitness for a
particular purpose or noninfringement, are disclaimed, even if Pivotal Software, Inc., has been advised
of the possibility of such claims. This training material is designed to support an instructor-led training
course and is intended to be used for reference purposes in conjunction with the instructor-led training
course. The training material is not a standalone training tool. Use of the training material for selfstudy without class attendance is not recommended.
These materials and the computer programs to which it relates are the property of, and embody trade
secrets and confidential information proprietary to, Pivotal Software, Inc., and may not be reproduced,
copied, disclosed, transferred, adapted or modified without the express written approval of Pivotal
Software, Inc.
 Copyright 2014 Pivotal. All rights reserved.
Welcome to Core
Spring
A 4-day bootcamp that trains you how to use
the Spring Framework to create welldesigned, testable, business, applications
 Copyright 2014 Pivotal. All rights reserved.
Logistics
Participants list
Self introduction
MyLearn registration
Courseware
Internet access
 Copyright 2014 Pivotal. All rights reserved.
 Working hours
Lunch
Toilets
Fire alarms
Emergency exits
Other questions?
How You will Benefit
 Learn to use Spring for web and other applications
 Gain hands-on experience
 50/50 presentation and labs
 Access to SpringSource professionals
 Copyright 2014 Pivotal. All rights reserved.
Covered in this section
 Agenda
 Spring and Pivotal
 Copyright 2014 Pivotal. All rights reserved.
Course Agenda: Day 1
Introduction to Spring
Using Spring to configure an application
Java-based dependency injection
Annotation-based dependency injection
XML-based dependency injection
 Copyright 2014 Pivotal. All rights reserved.
Course Agenda: Day 2
 Understanding the bean life-cycle
 Testing a Spring-based application using multiple
profiles
 Adding behavior to an application using aspects
 Introducing data access with Spring
 Simplifying JDBC-based data access
 Copyright 2014 Pivotal. All rights reserved.
Course Agenda: Day 3
Driving database transactions in a Spring environment
Introducing object-to-relational mapping (ORM)
Working with JPA in a Spring environment
Effective web application architecture
Getting started with Spring MVC
 Copyright 2014 Pivotal. All rights reserved.
Course Agenda: Day 4
Rapidly start new projects with Spring Boot
Securing web applications with Spring Security
Implementing REST with Spring MVC
Simplifying message applications with Spring JMS
 Copyright 2014 Pivotal. All rights reserved.
Covered in this section
 Agenda
 Spring and Pivotal
 Copyright 2014 Pivotal. All rights reserved.
Spring and Pivotal
 SpringSource, the company behind Spring
 acquired by VMware in 2009
 transferred to Pivotal joint venture 2013
 Spring projects key to Pivotal's big-data and cloud
strategies
 Virtualize your Java Apps
 Save license cost
 Deploy to private, public, hybrid clouds
 Real-time analytics
 Spot trends as they happen
 Spring Data, Spring Hadoop, Spring XD & Pivotal HD
 Copyright 2014 Pivotal. All rights reserved.
10
The Pivotal Platform
 Copyright 2014 Pivotal. All rights reserved.
11
Spring
Projects
Spring
Integration
Spring
Security
Spring
Data
Spring
Batch
Spring
Reactor
Spring
Android
Spring
Mobile
Spring
AMQP
Spring
Framework
Spring
Hateoas
Spring
Social
Spring
Web
Flow
Spring
XD
Spring
Boot
Spring Web Services
 Copyright 2014 Pivotal. All rights reserved.
12
Open Source contributions
 Spring technologies
 Pivotal develops 95% of the code of the Spring framework
 Also leaders on the other Spring projects (Batch, Security,
Web Flow...)
 Tomcat
 60% of code commits in the past 2 years
 80% of bug fixes
 Others
 Apache httpd, Hyperic, Groovy/Grails,
Rabbit MQ, Hadoop ...
 Copyright 2014 Pivotal. All rights reserved.
13
Covered in this section
 Agenda
 Spring and Pivotal
Let's get on with the course..!
 Copyright 2014 Pivotal. All rights reserved.
14
Overview of the
Spring Framework
Introducing Spring in the Context of
Enterprise Application Architecture
What is Spring and why would you use it?
 Copyright 2014 Pivotal. All rights reserved.
Objectives
 After completing this lesson, you should be able to:
 Define the Spring Framework
 Understand what Spring is used for
 Understand why Spring is successful
 Explain where it fits in your world
 Copyright 2014 Pivotal. All rights reserved.
Topics in this session
What is the Spring Framework?
Spring is a Container
Spring Framework history
What is Spring Used For?
 Copyright 2014 Pivotal. All rights reserved.
What is the Spring Framework?
 Spring is an Open Source, Lightweight, Container and
Framework for building Java enterprise applications
Open Source
Lightweight
Container
Framework
 Copyright 2014 Pivotal. All rights reserved.
What is the Spring Framework?
Open Source
 Spring binary and source code is freely available
 Apache 2 license
 Code is available at:
 https://github.com/spring-projects/spring-framework
 Binaries available at Maven Central
 http://mvnrepository.com/artifact/org.springframework
 Documentation available at:
Bookmark
This!
 http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle
The use of a transitive dependency management system (Maven,
Gradle, Ant/Ivy) is recommended for any Java application
 Copyright 2014 Pivotal. All rights reserved.
What is the Spring Framework?
Lightweight
 Spring applications do not require a Java EE application
server
 But they can be deployed on one
 Spring is not invasive
 Does not require you to extend framework classes or
implement framework interfaces for most usage
 You write your code as POJOs
 Spring jars are relatively small
 Spring jars used in this course
are < 8 MB
 Copyright 2014 Pivotal. All rights reserved.
What is the Spring Framework?
Container
 Spring serves as a container for your application objects.
 Your objects do not have to worry about finding /
connecting to each other.
 Spring instantiates and dependency injects your objects
 Serves as a lifecycle manager
 Copyright 2014 Pivotal. All rights reserved.
What is the Spring Framework?
Framework
 Enterprise applications must deal with a wide variety of
technologies / resources
 JDBC, JMS, AMQP, Transactions, ORM / JPA, NoSQL,
Security, Web, Tasks, Scheduling, Mail, Files, XML/JSON
Marshalling, Remoting, REST services, SOAP services,
Mobile, Social, ...
 Spring provides framework classes to simplify working
with lower-level technologies
 Copyright 2014 Pivotal. All rights reserved.
Topics in this session
What is the Spring Framework?
Spring is a Container
Spring Framework History
What is Spring Used For?
 Copyright 2014 Pivotal. All rights reserved.
Application Configuration
 A typical application system consists of several parts
working together to carry out a use case
Transfer
Service
Transfer
Repository
Account
Repository
 Copyright 2014 Pivotal. All rights reserved.
10
Example: Money Transfer System
TransferService
transfer(
300.00,
1, 2)
AccountRepository
loadAccount(1);
a1
loadAccount(2);
a2
new
new
Account 1
Account 2
debit(300.00)
credit(300.00)
updateAccount(a1);
confirmation
 Copyright 2014 Pivotal. All rights reserved.
updateAccount(a2);
11
Springs Configuration Support
 Spring provides support for assembling such an
application system from its parts
 Parts do not worry about finding each other
 Any part can easily be swapped out
 Copyright 2014 Pivotal. All rights reserved.
12
Money Transfer System Assembly
Spring
TransferServiceImpl
Part 2
Assembly
JdbcAccountRepository
Part 1
(1) repository = new JdbcAccountRepository();
(2) service = new TransferServiceImpl();
(3) service.setAccountRepository(repository);
 Copyright 2014 Pivotal. All rights reserved.
13
Parts are Just Plain Old Java Objects
public class JdbcAccountRepository implements
AccountRepository {
Implements a service/business interface
}
Part 1
public class TransferServiceImpl implements TransferService {
private AccountRepository accountRepository;
public void setAccountRepository(AccountRepository ar) {
accountRepository = ar;
}
Depends on interface;
conceals complexity of implementation;
}
allows for swapping out implementation
 Copyright 2014 Pivotal. All rights reserved.
Part 2
14
Swapping Out Part Implementations
Spring
TransferServiceImpl
JdbcAccountRepository
StubAccountRepository
JpaAccountRepository
For Jdbc
Jpa
For For
Unit
Testing
(1)new
new StubAccountRepository();
JdbcAccountRepository();
(1)
JpaAccountRepository();
(2)new
new TransferServiceImpl();
TransferServiceImpl();
(2)
(3)service.setAccountRepository(repository);
service.setAccountRepository(repository);
(3)
 Copyright 2014 Pivotal. All rights reserved.
15
Topics in this session
What is the Spring Framework?
Spring is a Container
Spring Framework History
What is Spring Used For?
 Copyright 2014 Pivotal. All rights reserved.
16
Why is Spring Successful?
A brief history of Java
 The early years:
 1995  Java introduced, Applets are popular
 1997  Servlets introduced
 Efficient, dynamic web pages become possible.
 1999  JSP introduced
 Efficient, dynamic web pages become easy.
 Questions arise regarding Enterprise applications
 How should a Servlet / JSP application handle:
Persistence?
Transactions?
Security?
 Copyright 2014 Pivotal. All rights reserved.
Business Logic?
Messaging?
Etc.?
17
Introducing J2EE and EJB
 Java's answer: J2EE
 1999  J2EE introduced
 Featuring Enterprise Java Beans (EJB)
 Answers the questions of persistence, transactions, business
logic, security, etc
 However EJBs prove to be problematic:
 Difficult to code.
 Must extend / implement specific classes /interfaces
 Complicated programming model required
 Difficult to unit test
 Expensive to run
 Must have application server, resource intensive
 Copyright 2014 Pivotal. All rights reserved.
18
The Birth of Spring
 Rod Johnson publishes J2EE
Development without EJB
 2004 - Spring Framework 1.0 released
 Champions dependency injection
 Encourages POJOs
 Uses XML files to describe application
configuration
 Becomes popular quickly as a EJB
alternative
 Copyright 2014 Pivotal. All rights reserved.
19
Spring Framework History
 Spring 2.0 (2006):
 XML simplification, async JMS, JPA, AspectJ support
 Spring 2.5 (2007, currently 2.5.6)
 Requires Java 1.4+ and supports JUnit 4
 Annotation DI, @MVC controllers, XML namespaces
 Spring 3.x (3.2 released Dec 2012)
 Env. + Profiles, @Cacheable, @EnableXXX 
 Supports Java 7, Hibernate 4, Servlet 3
 Requires Java 1.5+ and JUnit 4.7+
 REST support, JavaConfig, SpEL, more annotations
 Spring 4 (released Dec 2013)
 Support for Java 8, @Conditional, Web-sockets
 Copyright 2014 Pivotal. All rights reserved.
20
Topics in this session
What is the Spring Framework?
Spring is a Container
Spring Framework History
What is Spring Used For?
 Copyright 2014 Pivotal. All rights reserved.
21
What is Spring Used For?
 Spring provides comprehensive infrastructural support
for developing enterprise Java applications
 Spring deals with the plumbing
 So you can focus on solving the domain problem
 Spring used to build enterprise applications dealing with:
Web Interfaces
 Copyright 2014 Pivotal. All rights reserved.
Messaging
Persistence
Batch
Integration
22
The Current World
 Spring is not simply an alternative to J2EE / EJB
 Modern application development challenges are different
today than 2000
 Spring continues to innovate
 Web
 AJAX, WebSockets, REST, Mobile, Social
 Data
 NoSQL, Big Data, stream processing
 Cloud
 Distributed systems
 Productivity
 Spring Boot
 Etc. etc.
 Copyright 2014 Pivotal. All rights reserved.
23
Spring
Projects
Spring
Integration
Spring
Security
Spring
Data
Spring
Batch
Spring
Reactor
Spring
Android
Spring
AMQP
Spring
Mobile
Spring
Framework
Spring
Social
Spring Web
Services
Spring
Hateoas
Spring
Web
Flow
Spring
XD
Spring
Boot
...and many others!
 Copyright 2014 Pivotal. All rights reserved.
24
Lab
Developing an Application from Plain
Java Objects
 Copyright 2014 Pivotal. All rights reserved.
25
Dependency
Injection Using
Spring
Introducing the Spring Application Context
and Spring's Java Configuration capability
@Configuration and ApplicationContext
 Copyright 2014 Pivotal. All rights reserved.
Topics in this session
Spring quick start
Creating an application context
Bean scope
Lab
 Copyright 2014 Pivotal. All rights reserved.
How Spring Works
Your Application Classes
(POJOs)
Configuration
Instructions
Spring
ApplicationContext
Creates
Fully configured
application system
Ready for use
 Copyright 2014 Pivotal. All rights reserved.
Your Application Classes
public class TransferServiceImpl implements TransferService {
public TransferServiceImpl(AccountRepository ar) {
this.accountRepository = ar;
}
Needed to perform money transfers
between accounts
}
public class JdbcAccountRepository implements AccountRepository {
public JdbcAccountRepository(DataSource ds) {
this.dataSource = ds;
}
Needed to load accounts from the database
}
 Copyright 2014 Pivotal. All rights reserved.
Configuration Instructions
 Copyright 2014 Pivotal. All rights reserved.
Creating and Using the Application
// Create the application from the configuration
ApplicationContext context =
SpringApplication.run( ApplicationConfig.class );
Bean ID
// Look up the application service interface
Based on method name
TransferService service =
(TransferService) context.getBean(transferService);
// Use the application
service.transfer(new MonetaryAmount(300.00), 1, 2);
 Copyright 2014 Pivotal. All rights reserved.
Accessing a Bean
 Multiple ways
ApplicationContext context = SpringApplication.run(...);
// Classic way: cast is needed
TransferService ts1 = (TransferService) context.getBean(transferService);
// Use typed method to avoid cast
TransferService ts2 = context.getBean(transferService, TransferService.class);
// No need for bean id if type is unique
TransferService ts3 = context.getBean(TransferService.class );
 Copyright 2014 Pivotal. All rights reserved.
Inside the Spring Application Context
// Create the application from the configuration
ApplicationContext context =
SpringApplication.run( ApplicationConfig.class )
Application Context
transferService
TransferServiceImpl
accountRepository
JdbcAccountRepository
dataSource
BasicDataSource
 Copyright 2014 Pivotal. All rights reserved.
Quick Start Summary
 Spring manages the lifecycle of the application
 All beans are fully initialized before use
 Beans are always created in the right order
 Based on their dependencies
 Each bean is bound to a unique id
 The id reflects the service or role the bean provides to
clients
 Bean id should not contain implementation details
 Copyright 2014 Pivotal. All rights reserved.
Topics in this session
Spring quick start
Creating an application context
Multiple Configuration Files
Bean scope
Lab
 Copyright 2014 Pivotal. All rights reserved.
10
Creating a Spring Application Context
 Spring application contexts can be bootstrapped in any
environment, including
 JUnit system test
 Web application
 Standalone application
 Copyright 2014 Pivotal. All rights reserved.
11
Example: Using an Application Context Inside a
JUnit System Test
public class TransferServiceTests {
private TransferService service;
@Before public void setUp() {
// Create the application from the configuration
ApplicationContext context =
SpringApplication.run( ApplicationConfig.class )
// Look up the application service interface
service = context.getBean(TransferService.class);
}
Bootstraps the
system to test
@Test public void moneyTransfer() {
Tests the system
Confirmation receipt =
service.transfer(new MonetaryAmount(300.00), 1, 2));
Assert.assertEquals(receipt.getNewBalance(), 500.00);
}
 Copyright 2014 Pivotal. All rights reserved.
12
Topics in this session
Spring quick start
Creating an application context
Multiple Configuration Files
Bean scope
Lab
 Copyright 2014 Pivotal. All rights reserved.
13
Creating an Application Context from
Multiple Files
 Your @Configuration class can get very long
 Instead use multiple files combined with @Import
 Defines a single Application Context
 With beans sourced from multiple files
@Configuration
@Import({InfrastructureConfig.class, WebConfig.class })
public class ApplicationConfig {
...
}
@Configuration
public class InfrastructureConfig {
...
}
 Copyright 2014 Pivotal. All rights reserved.
@Configuration
public class WebConfig {
...
}
14
Creating an Application Context from
Multiple Files
 Organize your @Configuration classes however you like
 Best practice: separate out application beans from
infrastructure beans
 Infrastructure often changes between environments
Service beans
Repository beans
Datasource
one single class
 Copyright 2014 Pivotal. All rights reserved.
Service beans
Repository beans
Datasource
application
infra-structure
two Spring configuration classes
15
Mixed Configuration
application beans
Coupled to a local
Postgres environment
infrastructure bean
 Copyright 2014 Pivotal. All rights reserved.
16
Partitioning Configuration
@Configuration
application beans
public class ApplicationConfig {
@Autowired DataSource dataSource;
@Bean public TransferService transferService() {
return new TransferServiceImpl ( accountRepository() );
}
@Bean public AccountRepository accountRepository() {
return new JdbcAccountRepository( dataSource );
}
}
@Configuration
public class TestInfrastructureConfig {
@Bean public DataSource dataSource() {
...
}
}
 Copyright 2014 Pivotal. All rights reserved.
infrastructure bean
17
Referencing beans defined in another file
 Use @Autowired to reference bean defined in a separate
configuration file:
@Configuration
@Configuration
@Import( InfrastructureConfig.class )
public class ApplicationConfig {
@Autowired
DataSource dataSource;
public class InfrastructureConfig {
@Bean
public DataSource dataSource() {
DataSource ds = new BasicDataSource();
...
return ds;
}
}
@Bean
public AccountRepository accountRepository() {
return new JdbcAccountRepository( dataSource );
}
}
 Copyright 2014 Pivotal. All rights reserved.
Or auto-wire a property setter, can't use a constructor
18
Referencing beans defined in another file
 Alternative: Define @Bean method parameters
 Spring will find bean that matches the type and populate the
parameter
@Configuration
@Import( InfrastructureConfig.class )
public class ApplicationConfig {
@Bean
public AccountRepository accountRepository( DataSource dataSource ) {
return new JdbcAccountRepository( dataSource );
}
@Configuration
}
public class InfrastructureConfig {
@Bean
public DataSource dataSource() {
DataSource ds = new BasicDataSource();
...
return ds;
}
}
 Copyright 2014 Pivotal. All rights reserved.
19
Topics in this session
Spring quick start
Creating an application context
Multiple Configuration Files
Bean scope
Lab
 Copyright 2014 Pivotal. All rights reserved.
20
Bean Scope: default
service1 == service2
 Default scope is singleton
@Bean
public AccountService accountService() {
return ...
}
@Bean
One single instance
@Scope(singleton)
public AccountService accountService() {
return ...
}
AccountService service1 = (AccountService) context.getBean(accountService);
AccountService service2 = (AccountService) context.getBean(accountService);
 Copyright 2014 Pivotal. All rights reserved.
21
Bean Scope: prototype
scope="prototype"
service1 != service2
 New instance created every time bean is referenced
@Bean
@Scope(prototype)
public AccountService accountService() {
return ...
}
AccountService service1 = (AccountService) context.getBean(accountService);
AccountService service2 = (AccountService) context.getBean(accountService);
2 instances
 Copyright 2014 Pivotal. All rights reserved.
22
Available Scopes
singleton
A single instance is used
prototype
A new instance is created each time the
bean is referenced
session
A new instance is created once per user
session - web environment
request
A new instance is created once per
request - web environment
custom
scope
name
You define your own rules and a new
scope name - advanced feature
 Copyright 2014 Pivotal. All rights reserved.
23
Dependency Injection Summary
 Your object is handed what it needs to work
 Frees it from the burden of resolving its dependencies
 Simplifies your code, improves code reusability
 Promotes programming to interfaces
 Conceals implementation details of dependencies
 Improves testability
 Dependencies easily stubbed out for unit testing
 Allows for centralized control over object lifecycle
 Opens the door for new possibilities
 Copyright 2014 Pivotal. All rights reserved.
24
Lab
Using Spring to Configure an
Application
 Copyright 2014 Pivotal. All rights reserved.
25
Dependency
Injection Using
Spring 2
Deeper Look into Spring's Java
Configuration Capability
External Properties, Profiles and Proxies
 Copyright 2014 Pivotal. All rights reserved.
Topics in this session
 External Properties
 Profiles
 Proxying
 Copyright 2014 Pivotal. All rights reserved.
Setting property values
 Consider this bean definition from the last chapter:
@Bean
public DataSource dataSource() {
DataSource ds = new BasicDataSource();
ds.setDriverClassName(org.postgresql.Driver);
ds.setUrl(jdbc:postgresql://localhost/transfer );
ds.setUser(transfer-app);
ds.setPassword(secret45 );
return ds;
}
 Unwise to hard-code DB connection parameters
 Externalize these to a properties file
 Copyright 2014 Pivotal. All rights reserved.
Spring's Environment Abstraction  1
 Environment object used to obtain properties from
runtime environment
 Properties from many sources:
JVM System Properties
Java Properties Files
Servlet Context Parameters
System Environment Variables
JNDI
 Copyright 2014 Pivotal. All rights reserved.
Spring's Environment Abstraction  2
@Configuration
public class ApplicationConfig {
@Autowired public Environment env;
@Bean public DataSource dataSource() {
DataSource ds = new BasicDataSource();
ds.setDriverClassName( env.getProperty( db.driver ));
ds.setUrl( env.getProperty( db.url ));
ds.setUser( env.getProperty( db.user ));
ds.setPassword( env.getProperty( db.password ));
return ds;
}
}
 Copyright 2014 Pivotal. All rights reserved.
Accessing Properties using @Value
@Configuration
public class ApplicationConfig {
@Bean
public DataSource dataSource(
@Value("${db.driver}") String dbDriver,
@Value("${db.url}") String dbUrl,
@Value("${db.user}") String dbUser,
@Value("${db.password}") String dbPassword) {
DataSource ds = new BasicDataSource();
ds.setDriverClassName( dbDriver);
ds.setUrl( dbUrl);
ds.setUser( dbUser);
ds.setPassword( dbPassword ));
return ds;
}
}
 Copyright 2014 Pivotal. All rights reserved.
Property Sources
 Environment obtains values from property sources
 System properties & Environment variables populated
automatically
 Use @PropertySources to contribute additional
properties
 Available resource prefixes: classpath: file: http:
@Configuration
@PropertySource ( classpath:/com/organization/config/app.properties )
public class ApplicationConfig {
...
}
 Copyright 2014 Pivotal. All rights reserved.
${...} Placeholders
 ${...} placeholders in a @PropertySource are resolved
against existing properties
 Such as System properties & Environment variables
@PropertySource ( classpath:/com/acme/config/app-${ENV}.properties )
db.driver=org.postgresql.Driver
db.url=jdbc:postgresql://localhost/transfer
db.user=transfer-app
db.driver=org.postgresql.Driver
db.password=secret45
db.url=jdbc:postgresql://qa/transfer
app-dev.properties
db.user=transfer-app
db.password=secret88
app-prod.properties
app-qa.properties
 Copyright 2014 Pivotal. All rights reserved.
Topics in this session
 External Properties
 Profiles
 Proxying
 Copyright 2014 Pivotal. All rights reserved.
Profiles
 Beans can be grouped into Profiles
 Profiles can represent purpose: web, offline
 Or environment: dev, qa, uat, prod
 Beans included / excluded based on profile membership
Transfer
Service
Beans with
no profile
always
available
Account
Repository
Customer
Repository
Other
Other
Other
dev
dataSource
Connection
Factory
Performance
Monitor
 Copyright 2014 Pivotal. All rights reserved.
ApplicationContext
Account
Service
web
ErrorHandler
Other
qa
dataSource
Connection
Factory
prod
dataSource
Connection
Factory
10
Defining Profiles  1
 Using @Profile annotation on configuration class
 All beans in Configuration belong to the profile
@Configuration
@Profile("dev")
public class DevConfig {
@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();
}
 Copyright 2014 Pivotal. All rights reserved.
11
Defining Profiles - 2
 Using @Profile annotation on @Bean methods
@Configuration
public class DataSourceConfig {
Explicit bean-name
overrides method name
@Bean(name="dataSource")
@Profile("dev")
public DataSource dataSourceForDev() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setName("testdb") ...
}
@Bean(name="dataSource")
@Profile("prod")
public DataSource dataSourceForProd() {
DataSource dataSource = new BasicDataSource();
...
return dataSource;
}
 Copyright 2014 Pivotal. All rights reserved.
Both profiles define
same bean id, so only
one profile should be
activated at a time.
12
Ways to Activate Profiles
 Profiles must be activated at run-time
 Integration Test: Use @ActiveProfiles (covered later)
 System property
-Dspring.profiles.active=dev,jpa
 In web.xml (Web-based application)
<context-param>
<param-name>spring.profiles.active</param-name>
<param-value>jpa,web</param-value>
web.xml
</context-param>
 Programmatically on ApplicationContext
 Simply set spring.profiles.active system property before
instantiating ApplicationContext.
 Copyright 2014 Pivotal. All rights reserved.
13
Quiz:
Which of the Following is/are Selected?
-Dspring.profiles.active=jpa
?
@Configuration
public class
Config { ...}
 Copyright 2014 Pivotal. All rights reserved.
?
@Configuration
@Profile("jpa")
public class
JpaConfig
{ ...}
?
@Configuration
@Profile("jdbc")
public class
JdbcConfig
{ ...}
14
Property Source selection
 @Profile can control which @PropertySources are
included in the Environment
@Configuration
@Profile(dev)
@PropertySource ( dev.properties )
@Configuration
@Profile(prod)
@PropertySource ( prod.properties )
db.driver=org.postgresql.Driver
db.url=jdbc:postgresql://localhost/transfer
db.user=transfer-app
db.password=secret45
dev.properties
 Copyright 2014 Pivotal. All rights reserved.
prod.properties
15
Topics in this session
 External Properties
 Profiles
 Proxying
 Copyright 2014 Pivotal. All rights reserved.
16
Quiz
@Bean
public AccountRepository accountRepository()
{ return new JdbcAccountRepository(); }
Which is the best
implementation?
@Bean
public TransferService transferService1() {
TransferServiceImpl service = new TransferServiceImpl();
service.setAccountRepository(accountRepository());
return service;
}
@Bean
public TransferService transferService2() {
return new TransferServiceImpl( new JdbcAccountRepository() );
}
Method call
New instance
Prefer call to dedicated method.
Let's discuss why ...
 Copyright 2014 Pivotal. All rights reserved.
17
Working with Singletons
@Bean
AccountRepository
accountRepository()
public
singleton
is the default
scope {
return new JdbcAccountRepository(); }
@Bean
public TransferService transferService() {
TransferServiceImpl service = new TransferServiceImpl();
service.setAccountRepository(accountRepository());
return service;
}
Singleton??
Method
called twice
more
@Bean
public AccountService accountService() {
return new AccountServiceImpl( accountRepository() );
}
HOW IS IT POSSIBLE?
 Copyright 2014 Pivotal. All rights reserved.
18
Inheritance-based Proxies
 At startup time, a child class is created
 For each bean, an instance is cached in the child class
 Child class only calls super at first instantiation
@Configuration
public class AppConfig {
@Bean public AccountRepository accountRepository() { ... }
@Bean public TransferService transferService() { ... }
}
public class AppConfig$$EnhancerByCGLIB$ extends AppConfig {
public AccountRepository accountRepository() { // ... }
public TransferService transferService() { // ... }
...
 Copyright 2014 Pivotal. All rights reserved.
19
Inheritance-based Proxies
 Child class is the entry point
public class AppConfig$$EnhancerByCGLIB$ extends AppConfig {
public AccountRepository accountRepository() {
// if bean is in the applicationContext
// return bean
// else call super.accountRepository() and store bean in context
}
public TransferService transferService() {
// if bean is in the applicationContext, return bean
// else call super.transferService() and store bean in context
}
Java Configuration uses cglib for inheritance-based proxies
 Copyright 2014 Pivotal. All rights reserved.
20
Summary
 Property values are easily externalized using Spring's
Environment abstraction
 Profiles are used to group sets of beans
 Spring proxies your @Configuration classes to allow for
scope control.
 Copyright 2014 Pivotal. All rights reserved.
21
Annotations in
Spring
Annotations for Dependency Injection and
Interception
Component scanning and auto-injection
 Copyright 2014 Pivotal. All rights reserved.
Topics in this Session
 Fundamentals
Annotation-based Configuration
Best practices for component-scanning
Java Config versus annotations: when to use what?
Mixing Java Config and annotations for Dep. Injection
@PostConstruct and @PreDestroy
Stereotypes and meta annotations
 Lab
 Advanced features
 @Resource
 Standard annotations (JSR 330
 Copyright 2014 Pivotal. All rights reserved.
Before  Explicit Bean Definition
 Configuration is external to bean-class
 Separation of concerns
 Java-based dependency injection
@Configuration
public class TransferModuleConfig {
@Bean public TransferService transService() {
TransferServiceImpl service = new TransferServiceImpl();
service.setAccountRepository(accountRepository());
return service;
}
}
 Copyright 2014 Pivotal. All rights reserved.
After - Implicit Configuration
 Annotation-based configuration within bean-class
@Component
public class TransferServiceImpl implements TransferService {
@Autowired
public TransferServiceImpl(AccountRepository repo) {
this.accountRepository = repo;
Annotations embedded
}
with POJOs
}
@Configuration
@ComponentScan ( com.bank )
public class AnnotationConfig {
// No bean definition needed any more
}
 Copyright 2014 Pivotal. All rights reserved.
Find @Component classes
within designated (sub)packages
Usage of @Autowired
Unique dependency of
correct type must exist
 Constructor-injection
@Autowired
public TransferServiceImpl(AccountRepository a) {
this.accountRepository = a;
}
 Method-injection
@Autowired
public void setAccountRepository(AccountRepository a) {
this.accountRepository = a;
}
 Field-injection
@Autowired
private AccountRepository accountRepository;
 Copyright 2014 Pivotal. All rights reserved.
Even when field is private!!
 but hard to unit test.
@Autowired dependencies:
required or not?
 Default behavior: required
Exception if no
dependency found
@Autowired
public void setAccountRepository(AccountRepository a) {
this.accountRepository = a;
}
 Use required attribute to override default behavior
@Autowired(required=false)
public void setAccountRepository(AccountRepository a) {
this.accountRepository = a;
}
Only inject if
dependency exists
 Copyright 2014 Pivotal. All rights reserved.
Constructor vs Setter Dependency Injection
 Spring doesn't care  can use either
 But which is best?
 Follow the same rules as standard Java
 Be consistent across your project team
 Many classes use both
Constructors
Setters
Mandatory dependencies
Optional / changeable dependencies
Immutable dependencies
Circular dependencies
Concise (pass several params at once)
Inherited automatically
 Copyright 2014 Pivotal. All rights reserved.
Autowiring and Disambiguation
 What happens here?
@Component
public class TransferServiceImpl implements TransferService {
@Autowired
public TransferServiceImpl(AccountRepository accountRepository) {  }
}
@Component
public class JpaAccountRepository implements AccountRepository {..}
Which one should get injected?
@Component
public class JdbcAccountRepository implements AccountRepository {..}
At startup: NoSuchBeanDefinitionException, no unique bean of type
[AccountRepository] is defined: expected single bean but found 2...
 Copyright 2014 Pivotal. All rights reserved.
Autowiring and Disambiguation
 Use of the @Qualifier annotation
@Component("transferService")
public class TransferServiceImpl implements TransferService {
@Autowired
public TransferServiceImpl( @Qualifier("jdbcAccountRepository")
AccountRepository accountRepository) {  }
qualifier
bean ID
@Component("jdbcAccountRepository")
public class JdbcAccountRepository implements AccountRepository {..}
@Component("jpaAccountRepository")
public class JpaAccountRepository implements AccountRepository {..}
@Qualifier also available with method injection and field injection
Component names should not show implementation details unless
there are 2 implementations of the same interface (as here)
 Copyright 2014 Pivotal. All rights reserved.
Component names
 When not specified
 Names are auto-generated
 De-capitalized non-qualified classname by default
 But will pick up implementation details from classname
 Recommendation: never rely on generated names!
 When specified
 Allow disambiguation when 2 bean classes implement the
same interface
Common strategy: avoid using qualifiers when possible.
Usually rare to have 2 beans of same type in ApplicationContext
 Copyright 2014 Pivotal. All rights reserved.
10
Java Config vs Annotations syntax
 Similar options are available
@Component("transferService")
@Scope("prototype")
@Profile("dev")
@Lazy(false)
public class TransferServiceImpl
implements TransferService {
@Autowired
public TransferServiceImpl
(AccountRepository accRep) ...
}
 Copyright 2014 Pivotal. All rights reserved.
Annotations
@Bean
@Scope("prototype")
@Profile("dev")
@Lazy(false)
public TransferService transferService() {
return
new TransferServiceImpl(
accountRepository());
}
Java Configuration
11
Topics in this Session
 Fundamentals
Annotation-based Configuration
Best practices for component-scanning
Java Config versus annotations: when to use what?
Mixing Java Config and annotations for Dep. Injection
@PostConstruct and @PreDestroy
Stereotypes and meta annotations
 Lab
 Advanced features
 @Resource
 Standard annotations (JSR 330)
 Copyright 2014 Pivotal. All rights reserved.
12
Component scanning
 Components are scanned at startup
 Jar dependencies also scanned!
 Could result in slower startup time if too many files
scanned
 Especially for large applications
 A few seconds slower in the worst case
 What are the best practices?
 Copyright 2014 Pivotal. All rights reserved.
13
Best practices
 Really bad:
@ComponentScan ( { "org", "com" } )
 Still bad:
All org and com
packages in the
classpath will be
scanned!!
@ComponentScan ( "com" )
 OK:
@ComponentScan ( "com.bank.app" )
 Optimized:
@ComponentScan ( { "com.bank.app.repository",
"com.bank.app.service", "com.bank.app.controller" } )
 Copyright 2014 Pivotal. All rights reserved.
14
Topics in this Session
 Fundamentals
Annotation-based Configuration
Best practices for component-scanning
Java Config versus annotations: when to use what?
Mixing Java Config and annotations for Dep. Injection
@PostConstruct and @PreDestroy
Stereotypes and meta annotations
 Lab
 Advanced features
 @Resource
 Standard annotations (JSR 330)
 Copyright 2014 Pivotal. All rights reserved.
15
When to use what?
Java
Java Configuration
 Pros:
Is centralized in one (or a few) places
Write any Java code you need
Strong type checking enforced by compiler (and IDE)
Can be used for all classes (not just your own)
 Cons:
 More verbose than annotations
 Copyright 2014 Pivotal. All rights reserved.
16
When to use what?
Annotations
 Nice for frequently changing beans
 Pros:
 Single place to edit (just the class)
 Allows for very rapid development
 Cons:
 Configuration spread across your code base
 Harder to debug/maintain
 Only works for your own code
 Merges configuration and code (bad sep. of concerns)
 Copyright 2014 Pivotal. All rights reserved.
17
Topics in this Session
 Fundamentals
Annotation-based Configuration
Best practices for component-scanning
Java Config versus annotations: when to use what?
Mixing Java Config and annotations for Dep. Injection
@PostConstruct and @PreDestroy
Stereotypes and meta annotations
 Lab
 Advanced features
 @Resource
 Standard annotations (JSR 330)
 Copyright 2014 Pivotal. All rights reserved.
18
Mixing Java Config and annotations
 You can mix and match in many ways. A few options:
 Use annotations for Spring MVC beans
 Beans that are not referenced elsewhere
 Use Java Configuration for Service and Repository beans
 Use annotations when possible, but still use Java
Configuration for legacy code that can't be changed
 Copyright 2014 Pivotal. All rights reserved.
19
Topics in this Session
 Fundamentals
Annotation-based Configuration
Best practices for component-scanning
Java Config versus annotations: when to use what?
Mixing Java Confg and annotations for Dep. Injection
@PostConstruct and @PreDestroy
Stereotypes and meta annotations
 Lab
 Advanced features
 @Resource
 Standard annotations (JSR 330)
 Copyright 2014 Pivotal. All rights reserved.
20
@PostConstruct and @PreDestroy
 Add behavior at startup and shutdown
public class JdbcAccountRepository {
@PostConstruct
Method called at startup after
dependency injection
void populateCache() { }
@PreDestroy
void clearCache() { }
}
Method called at shutdown
prior to destroying the bean
instance
Annotated methods can have any visibility but must take no
parameters and only return void
 Copyright 2014 Pivotal. All rights reserved.
21
@PostConstruct / @PreDestroy
configuration
 @ComponentScan required.
public class JdbcAccountRepository {
@PostConstruct void populateCache() {  }
JSR-250 annotations
@PreDestroy void clearCache() {  }
 EJB3 also uses them
}
@Configuration
@ComponentScan ( "..." )
public class AnnotationConfig {
...
}
 Copyright 2014 Pivotal. All rights reserved.
Automatically enables processing of
@PostConstruct and @PreDestroy
22
@PostConstruct
 Called after setter methods are called
public class JdbcAccountRepository {
private DataSource dataSource;
@Autowired
public void setDataSource(DataSource dataSource)
{ this.dataSource = dataSource; }
@PostConstruct
public void populateCache()
{ Connection conn = dataSource.getConnection(); //... }
}
Constructor
called
 Copyright 2014 Pivotal. All rights reserved.
Setter(s) called
@PostConstruct
method(s) called
23
@PreDestroy
 Called when ApplicationContext is closed
 Useful for releasing resources and 'cleaning up'
ConfigurableApplicationContext context = 
// Destroy the application
context.close();
Triggers call of all
@PreDestroy annotated methods
public class JdbcAccountRepository {
@PreDestroy
public void clearCache() {
//...
Tells Spring to call this method prior
to destroying the bean instance
}
}
- Called only when ApplicationContext / JVM exit normally
- Not called for prototype beans
 Copyright 2014 Pivotal. All rights reserved.
24
Lifecycle Methods via @Bean
 Alternatively, @Bean has options to define these lifecycle methods
@Bean (initMethod="populateCache, destroyMethod="clearCache")
public AccountRepository accountRepository() {
// ...
}
 Common Usage:
 Use @PostConstruct/@PreDestroy for your own
classes
 Use @Bean properties for classes you didn't write and can't
annotate
 Copyright 2014 Pivotal. All rights reserved.
25
Topics in this Session
 Fundamentals
Annotation-based Configuration
Best practices for component-scanning
Java Config versus annotations: when to use what?
Mixing Java Config and annotations for Dep. Injection
@PostConstruct and @PreDestroy
Stereotypes and meta annotations
 Lab
 Advanced features
 @Resource
 Standard annotations (JSR 330)
 Copyright 2014 Pivotal. All rights reserved.
26
Stereotype annotations
 Component scanning also checks for annotations that
are themselves annotated with @Component
 So-called stereotype annotations
@ComponentScan ( "" )
scans
@Service("transferService")
public class TransferServiceImpl
implements TransferService {...}
Declaration of the
@Service annotation
@Target({ElementType.TYPE})
...
@Component
public @interface Service {...}
@Service annotation is part of the Spring framework
 Copyright 2014 Pivotal. All rights reserved.
27
Stereotype annotations
 Spring framework stereotype annotations
@Component
@Service
@Configuration
Service classes
Java Configuration
@Repository
Data access classes
@Controller
Web classes (Spring MVC)
Other Spring projects provide their own stereotype annotations
(Spring Web-Services, Spring Integration...)
 Copyright 2014 Pivotal. All rights reserved.
28
Meta-annotations
 Annotation which can be used to annotate other annotations
 e.g. all service beans should be configurable using
component scanning and be transactional
@ComponentScan ( "...." )
scans
recognizes
@MyTransactionalService
public class TransferServiceImpl
implements TransferService {...}
 Copyright 2014 Pivotal. All rights reserved.
Custom annotation
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Service
@Transactional(timeout=60)
public @interface
MyTransactionalService {
String value() default "";
}
29
Lab
Using Spring Annotations
To Configure and Test an application
 Copyright 2014 Pivotal. All rights reserved.
30
Topics in this Session
 Fundamentals
Annotation-based Configuration
Best practices for component-scanning
Java Config versus annotations: when to use what?
Mixing Java Config and annotations for Dep. Injection
@PostConstruct and @PreDestroy
Stereotypes and meta annotations
 Lab
 Advanced features
 @Resource
 Standard annotations (JSR 330)
 Copyright 2014 Pivotal. All rights reserved.
31
Using @Resource
 From JSR-250, supported by EJB 3.0 and Spring
 Identifies dependencies by name, not by type
 Name is Spring bean-name
 @Autowired matches by type
 Supports setter and field injection only
@Resource(name="jdbcAccountRepository)
public void setAccountRepository(AccountRepository repo) {
this.accountRepository = repo;
}
@Resource(name="jdbcAccountRepository)
private AccountRepository accountRepository;
 Copyright 2014 Pivotal. All rights reserved.
Setter
Injection
Field
injection
32
Qualifying @Resource
 When no name is supplied
 Inferred from property/field name
 Or falls back on injection by type
 Example
 Looks for bean called accountRepository
 because method is setAccountRepository
 Then looks for bean of type AccountRepository
@Resource
public void setAccountRepository(AccountRepository repo) {
this.accountRepository = repo;
}
 Copyright 2014 Pivotal. All rights reserved.
33
Topics in this Session
 Fundamentals
Annotation-based Configuration
Best practices for component-scanning
Java Config versus annotations: when to use what?
Mixing Java Config and annotations for Dep. Injection
@PostConstruct and @PreDestroy
Stereotypes and meta annotations
 Lab
 Advanced features
 @Resource
 Standard annotations (JSR 330)
 Copyright 2014 Pivotal. All rights reserved.
34
JSR 330
 Java Specification Request 330
Also known as @Inject
Joint JCP effort by Google and SpringSource
Standardizes internal DI annotations
Published late 2009
 Spring is a valid JSR-330 implementation
 Subset of functionality compared to Spring's @Autowired
support
 @Inject has 80% of what you need
 Rely on @Autowired for the rest
 Copyright 2014 Pivotal. All rights reserved.
35
JSR 330 annotations
Also scans JSR-330 annotations
@ComponentScan ( "...." )
import javax.inject.Inject;
import javax.inject.Named;
Should be specified for component
scanning (even without a name)
@Named
public class TransferServiceImpl implements TransferService {
@Inject
public TransferServiceImpl( @Named("accountRepository")
AccountRepository accountRepository) {  }
}
import javax.inject.Named;
@Named("accountRepository")
public class JdbcAccountRepository implements
AccountRepository {..}
 Copyright 2014 Pivotal. All rights reserved.
36
From @Autowired to @Inject
Spring
JSR 330
Comments
@Autowired
@Inject
@Inject always mandatory, has no
required option
@Component
@Named
Spring also scans for @Named
@Scope
@Scope
JSR 330 Scope for meta-annotation
and injection points only
@Scope
(singleton)
@Singleton
JSR 330 default scope is like
Spring's 'prototype'
@Qualifer
@Named
@Value
No equivalent
SpEL specific
@Required
Redundant
@Inject always required
@Lazy
No equivalent
Useful when needed, often abused
 Copyright 2014 Pivotal. All rights reserved.
37
Summary
 Springs configuration directives can be written using
Java, annotations, or XML (next)
 You can mix and match Java, annotations, and XML as
you please
 Autowiring with @Component allows for almost empty
Java configuration files
 Copyright 2014 Pivotal. All rights reserved.
38
Dependency
Injection Using XML
Spring's XML Configuration Language
Introducing Spring's Application Context
 Copyright 2014 Pivotal. All rights reserved.
Topics in this session
Writing bean definitions in XML
Creating an application context
Controlling Bean Behavior
Namespaces
Lab
Advanced Topics
 Copyright 2014 Pivotal. All rights reserved.
XML Configuration
 Original form of Configuration / Dependency Injection
 Dating back to before 2004
 Still fully supported
 Most commonly seen in existing applications
 ...and in older blogs, books, etc.
 External configuration as with Java Config
 Uses custom XML instead of Java
 Copyright 2014 Pivotal. All rights reserved.
@Configuration Comparison
Java configuration class
@Configuration
@Profile(prod)
public class AppConfig {
XML configuration file
profile
bean id
@Bean
public TransferService transferService()
{
TransferService service
= new TransferServiceImpl();
service.setRepository(repository());
return service;
}
bean id
@Bean(name=accountRepository)
public AccountRepository repository()
{ //... }
}
<beans profile=prod>
<bean id=transferService
class=com.acme.TransferServiceImpl>
<property name=repository
ref=accountRepository />
</bean>
Dependency injection
<bean id=accountRepository
class=com.acme.JdbcAccountRepository>
...
</bean>
</beans>
 Copyright 2014 Pivotal. All rights reserved.
Constructor Injection Configuration
 One parameter
<bean id=transferService class=com.acme.TransferServiceImpl>
<constructor-arg ref=accountRepository/>
</bean>
<bean id=accountRepository class=com.acme.AccountRepositoryImpl/>
 Multiple parameters
<bean id=transferService class=com.acme.TransferServiceImpl>
<constructor-arg ref=accountRepository/>
Parameters injected
<constructor-arg ref=customerRepository/>
according to their type
</bean>
<bean id=accountRepository class=com.acme.AccountRepositoryImpl/>
<bean id=customerRepository class=com.acme.CustomerRepositoryImpl/>
 Copyright 2014 Pivotal. All rights reserved.
Constructor Injection 'Under the Hood'
<bean id=service class=com.acme.ServiceImpl>
<constructor-arg ref=repository/>
</bean>
<bean id=repository class=com.acme.RepositoryImpl/>
Equivalent to:
@Bean public Repository repository() {
return new RepositoryImpl();
}
@Bean public Service service() {
return new ServiceImpl( repository() );
}
 Copyright 2014 Pivotal. All rights reserved.
Setter Injection
<bean id=service class=com.acme.ServiceImpl>
<property name=repository ref=repository/>
</bean>
Convention: implicitly refers to method setRepository(...)
<bean id=repository class=com.acme.RepositoryImpl/>
Equivalent to:
@Bean public Repository repository() {
return new RepositoryImpl();
}
@Bean public Service service() {
Service svc = new ServiceImpl();
svc.setRepository( repository() );
return svc;
}
 Copyright 2014 Pivotal. All rights reserved.
Combining Constructor and Setter Injection
<bean id=service class=com.acme.ServiceImpl>
<constructor-arg ref=required />
<property name=optional ref=optional />
</bean>
<bean id=required class=com.acme.RequiredImpl />
<bean id=optional class=com.acme.OptionalImpl />
Equivalent to:
@Bean public RequiredImpl required() {  }
@Bean public OptionalImpl optional() {  }
@Bean public Service service() {
Service svc = new ServiceImpl( required() );
svc.setOptional( optional() );
return svc;
}
 Copyright 2014 Pivotal. All rights reserved.
Injecting Scalar Values
<bean id=service class=com.acme.ServiceImpl>
Equivalent
<property name=stringProperty value=foo />
</bean>
<property name=stringProperty>
<value>foo</value>
</property>
public class ServiceImpl {
public void setStringProperty(String s) { ... }
Equivalent
to:
// ...
Equivalent to:
 Copyright 2014 Pivotal. All rights reserved.
@Bean
public Service service() {
Service svc = new ServiceImpl( );
svc.setStringProperty( foo );
return svc;
}
Automatic Value Type Conversion
<bean id=service class=com.acme.ServiceImpl>
<property name=intProperty value=29 />
</bean>
public class ServiceImpl {
public void setIntProperty(int i) { ... }
// ...
}
Equivalent to:
@Bean public Service service() {
Service svc = new ServiceImpl( );
int val = // Integer parsing logic, 29.
svc.setIntProperty( val );
return svc;
}
 Copyright 2014 Pivotal. All rights reserved.
Spring can convert:
Numeric types
BigDecimal,
boolean: true, false
Date
Locale
Resource
10
Topics in this session
Writing bean definitions in XML
Creating an application context
Controlling Bean Behavior
Namespaces
Lab
Advanced Topics
 Copyright 2014 Pivotal. All rights reserved.
11
Creating an ApplicationContext using XML
 Use a Java Configuration class, then use
@ImportResource to specify XML files:
SpringApplication.run(MainConfig.class);
@Configuration
@ImportResource( {
classpath:com/acme/application-config.xml,
file:C:/Users/alex/application-config.xml } )
@Import(DatabaseConfig.class)
public class MainConfig {  }
Multiple files possible
Prefixes allowed
(classpath: (default), file:, http:)
Combine with
@Configuration
imports
Older applications may use ClassPathXmlApplicationContext or
FileSystemXmlApplicationContext, still valid, see advanced topics.
 Copyright 2014 Pivotal. All rights reserved.
12
Remember @Import?
@Configuration
@Import(DatabaseConfig.class)
public class MainConfig {
...
}
 Use <import /> to import other XML configuration files
<beans>
<import resource=db-config.xml />
</beans>
 Uses relative path by default
 Same prefixes available (file, classpath, http)
 Copyright 2014 Pivotal. All rights reserved.
13
Topics in this session
Writing bean definitions
Creating an application context
Controlling Bean Behavior
Namespaces
Lab
Advanced Topics
 Copyright 2014 Pivotal. All rights reserved.
14
Remember @PostConstruct?
@PostConstruct
public void setup() {
...
}
 Same option available in XML
 But called init-method:
<bean id=accountService class=com.acme.ServiceImpl init-method=setup>
...
</bean>
Same rules: method can have any visibility, must take no
parameters, must return void. Called after dependency injection.
 Copyright 2014 Pivotal. All rights reserved.
15
Remember @PreDestroy?
@PreDestroy
public void teardown() {
...
}
 Same option available in XML
 But called destroy-method:
<bean id=Service class=com.acme.ServiceImpl destroy-method=teardown>
...
</bean>
Same rules: method can have any visibility, must take no
parameters, must return void.
 Copyright 2014 Pivotal. All rights reserved.
16
Remember Bean Scope?
@Bean
@Scope(prototype)
public AccountService accountService() {
return ...
@Component
}
@Scope(prototype)
public class AccountServiceImpl {
...
}
 Same options available in XML
 singleton, prototype, request, session, (custom)
<bean id=accountService class=com.acme.ServiceImpl scope=prototype>
...
</bean>
 Copyright 2014 Pivotal. All rights reserved.
17
Remember @Lazy?
@Bean
@Lazy(true)
public AccountService accountService() {
return ...
@Component
}
@Lazy(true)
public class AccountServiceImpl {
...
}
 Same option available in XML
 Still not recommended, often misused
<bean id=accountService class=com.acme.ServiceImpl lazy=true>
...
</bean>
 Copyright 2014 Pivotal. All rights reserved.
18
Remember @Profile?
@Configuration
@Profile(dev)
public class MainConfig {
...
}
@Component
@Profile(dev)
public class AccountServiceImpl {
...
}
 Set profile attribute on the <beans > element
 Or child element:
<beans profile=dev>
</beans>
<beans >
<beans profile=dev>
</beans>
</beans>
 Copyright 2014 Pivotal. All rights reserved.
19
Topics in this session
Writing bean definitions in XML
Creating an application context
Controlling Bean Behavior
Namespaces
Lab
Advanced Topics
 Copyright 2014 Pivotal. All rights reserved.
20
Default namespace
 The default namespace in a Spring configuration
file is typically the beans namespace
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd>
<!-- ... -->
</beans>
dozens of other namespaces are available!
 Copyright 2014 Pivotal. All rights reserved.
21
Other namespaces
 Defined for subsets of framework functionality*
aop (Aspect Oriented Programming)
tx (transactions)
util
jms
context
 They allow hiding of actual bean definitions
 Greatly reduce size of bean files (see next slides)
* see http://www.springframework.org/schema/ for a complete list
 Copyright 2014 Pivotal. All rights reserved.
22
Namespace provides shortcut
 The namespace is just an elegant way to hide the
corresponding bean declaration
<context:property-placeholder location=db-config.properties />
<bean class="org.springframework...PropertySourcesPlaceholderConfigurer">
<property name="location" value="db-config.properties"/>
</bean>
 Same functionality, less typing
 Copyright 2014 Pivotal. All rights reserved.
23
property-placeholder example
<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>
 Copyright 2014 Pivotal. All rights reserved.
24
Power of Namespaces
 Greatly simplifies Spring configuration
 Many advanced features of Spring need to declare a large
number of beans
hides 1 bean definition
<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
<context:property-placeholder location="db-config.properties" />
<aop:aspectj-autoproxy />
AOP configuration: hides 5+ bean definitions
<tx:annotation-driven />
Transactions configuration: hides more than 15 bean definitions!
</beans>
tx and aop namespaces will be discussed later
 Copyright 2014 Pivotal. All rights reserved.
25
XML Profiles and Properties
<import resource="classpath:config/${current.env}-config.xml"/>
<context:property-placeholder properties-ref=configProps/>
<beans profile="dev">
<util:properties id="configProps" location="config/app-dev.properties">
</beans>
<beans profile="prod">
<util:properties id="configProps" location="config/app-prod.properties">
</beans>
current.env=dev
current.env=prod
database.url=jdbc:derby:/test
database.url=jdbc:oracle:thin:...
database.user=tester
database.user=admin
Equivalent to ...
@PropertySource ( classpath:/com/acme/config/app-${ENV}.properties )
 Copyright 2014 Pivotal. All rights reserved.
26
Adding namespace declaration
 XML syntax is error-prone
xsi:schemaLocation="..."
 Use the dedicated STS wizard!
Click here and select
appropriate namespaces
 Copyright 2014 Pivotal. All rights reserved.
27
Schema version numbers
OR spring-beans.xsd ?
 Common practice: do not use a version number
spring-beans-3.1.xsd
 Triggers use of most recent schema version
 Easier migration
 Will make it easier to upgrade to the next version of Spring
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<!-- ... -->
</beans>
Not needed!
 Copyright 2014 Pivotal. All rights reserved.
28
Remember @ComponentScan?
@Configuration
@ComponentScan ( { com.acme.app.repository,
com.acme.app.service, com.acme.app.controller } )
public class MainConfig {
...
}
 Available in the context namespace
Array of Strings
Single String
<context:component-scan base-package=com.acme.app.repository,
com.acme.app.service, com.acme.app.controller />
 Copyright 2014 Pivotal. All rights reserved.
29
Lab (optional)
Using XML to Configure an
Application
 Copyright 2014 Pivotal. All rights reserved.
30
Topics in this session
Writing bean definitions in XML
Creating an application context
Controlling Bean Behavior
Namespaces
Lab
Advanced Topics
 Creating ApplicationContext
 Constructor Arguments
 Copyright 2014 Pivotal. All rights reserved.
31
Creating the ApplicationContext
 So far, you have seen the ApplicationContext created like this:
ApplicationContext context = SpringApplication.run(MainConfig.class);
 Older classic techniques available as well:
new AnnotationConfigApplicationContext(MainConfig.class);
// Load from $CLASSPATH/com/acme/application-config.xml
new ClassPathXmlApplicationContext(com/acme/application-config.xml);
// Load from absolute path: C:/Users/alex/application-config.xml
new FileSystemXmlApplicationContext(C:/Users/alex/application-config.xml);
// path relative to the JVM working directory
new FileSystemXmlApplicationContext(./application-config.xml);
 Older techniques not intended to work with Spring Boot
 (covered later)
 Copyright 2014 Pivotal. All rights reserved.
32
Spring's Flexible Resource Loading
Mechanism
 ApplicationContext implementations have default
resource loading rules
new ClassPathXmlApplicationContext(com/acme/application-config.xml);
$CLASSPATH/com/acme/application-config.xml
new FileSystemXmlApplicationContext(C:/Users/alex/application-config.xml);
// absolute path: C:/Users/alex/application-config.xml
new FileSystemXmlApplicationContext(./application-config.xml);
// path relative to the JVM working directory
XmlWebApplicationContext is also available
- The path is relative to the Web application
- Usually created indirectly via a declaration in web.xml
 Copyright 2014 Pivotal. All rights reserved.
33
More on Constructor Args
 Constructor args matched by type
 <constructor-arg> elements can be in any order
 When ambiguous: indicate order with index
Both look like Strings to XML
class MailService {
public MailService(int maxEmails, String email) {  }
<bean name=example class=com.app.MailService>
<constructor-arg index=0 value=10000/>
<constructor-arg index=1 value=foo@foo.com/>
</bean>
Index from zero
 Copyright 2014 Pivotal. All rights reserved.
34
Using Constructor Names
 Constructor args can have names
 Since Spring 3.0 they can be used for arg matching
 BUT: need to compile with debug-symbols enabled
 OR: Use @java.beans.ConstructorProperties
Specify arg names in order
class MailService {
@ConstructorProperties( { maxEmails, email } )
public MailService(int maxEmails, String email) {  }
<bean name=example class=com.app.MailService>
<constructor-arg name=maxEmails value=10000/>
<constructor-arg name=email value=foo@foo.com/>
</bean>
 Copyright 2014 Pivotal. All rights reserved.
35
XML Dependency
Injection
Advanced Features & Best Practices
Techniques for Creating Reusable and Concise
Bean Definitions
 Copyright 2014 Pivotal. All rights reserved.
Topics in this session
Factory Beans / Factory Method
'p' and 'c' namespaces
Profiles
Externalizing values into properties files
Using Bean definition inheritance
Lab
Advanced Features
 Inner beans, collections, SpEL
 Copyright 2014 Pivotal. All rights reserved.
Advanced XML Bean Instantiation
 How can Spring instantiate the following?
 Classes with private constructors (such as Singleton
pattern)
 Objects from Factories
public class AccountServiceSingleton implements AccountService {
private static AccountServiceSingleton inst = new AccountServiceSingleton();
private AccountServiceSingleton() { ... }
public static AccountService getInstance() {
// ...
return inst;
}
}
 Copyright 2014 Pivotal. All rights reserved.
Advanced XML Bean Instantiation
 3 techniques:
 @Bean method in @Configuration class
 100% Java code available
 XML factory-method attribute
 No need to update Java class
 Implement FactoryBean interface
 Instantiation logic coded within FactoryBean
 Spring auto-detects FactoryBean implementations
 Copyright 2014 Pivotal. All rights reserved.
The factory-method Attribute
 Non-intrusive
 Useful for existing Singletons or Factories
public class AccountServiceSingleton implements AccountService {
public static AccountService getInstance() { //  }
}
<bean id=accountService class=com.acme.AccountServiceSingleton
factory-method="getInstance" />
Spring configuration
AccountService service1 = (AccountService) context.getBean(accountService);
AccountService service2 = (AccountService) context.getBean(accountService);
Spring uses getInstance() method  so
service1 and service2 point to the same object
 Copyright 2014 Pivotal. All rights reserved.
Test class
The FactoryBean interface
 Used when factory-method unavailable
 Or other complex cases inexpressible in XML
 Used before @Bean methods introduced
public class AccountServiceFactoryBean
implements FactoryBean <AccountService>
{
public AccountService getObject() throws Exception {
//...
return accountService;
}
//...
}
<bean id=accountService
class=com.acme.AccountServiceFactoryBean />
 Copyright 2014 Pivotal. All rights reserved.
The FactoryBean interface
 Beans implementing FactoryBean are
auto-detected
 Dependency injection using the factory bean id causes
getObject() to be invoked transparently
<bean id=accountService
class=com.acme.AccountServiceFactoryBean/>
<bean id=customerService class=com.acme.CustomerServiceImpl>
<property name=service ref=accountService />
</bean>
getObject()
called by Spring
automatically
 Copyright 2014 Pivotal. All rights reserved.
EmbeddedDatabaseFactoryBean
 Common example of a FactoryBean
 Spring framework class for creating in-memory databases
<bean id="dataSource" class="org.springframework.jdbc.datasource.
embedded.EmbeddedDatabaseFactoryBean">
<property name="databasePopulator" ref="populator"/>
</bean>
FactoryBean
<bean id="populator"
class="org.springframework.jdbc.datasource.init.ResourceDatabasePopulator">
<property name="scripts">
<list>
<value>classpath:testdb/setup.sql</value>
</list>
Populate with test-data
</property>
</bean>
 Copyright 2014 Pivotal. All rights reserved.
FactoryBeans in Spring
 FactoryBeans are widely used within Spring
 EmbeddedDatabaseFactoryBean
 JndiObjectFactoryBean
 One option for looking up JNDI objects
 FactoryBeans for creating remoting proxies
 FactoryBeans for configuring data access technologies like
JPA, Hibernate or MyBatis
 Copyright 2014 Pivotal. All rights reserved.
Topics in this session
Factory Beans / Factory Method
'p' and 'c' namespaces
Profiles
Externalizing values into properties files
Using Bean definition inheritance
Lab
Advanced Features
 Inner beans, collections, SpEL
 Copyright 2014 Pivotal. All rights reserved.
10
The c and p namespaces
 Before
<bean id="transferService" class="com.acme.BankServiceImpl">
<constructor-arg ref="bankRepository" />
<property name="accountService" ref="accountService" />
<property name="customerService" ref="customerService" />
</bean>
 After
<bean id="transferService" class="com.acme.BankServiceImpl"
c:bankRepository-ref="bankRepository"
p:accountService-ref="accountService"
p:customerService-ref="customerService" />
Use camel case or hyphens
c namespace was introduced in Spring 3.1
 Copyright 2014 Pivotal. All rights reserved.
11
The c and p namespaces
 c and p namespaces should be declared on top
 Use '-ref' suffix for references
Namespace declaration
<beans xmlns:c="http://www.springframework.org/schema/c"
xmlns:p="http://www.springframework.org/schema/p"
...>
<bean id="transferService" class="com.acme.ServiceImpl"
p:url="jdbc://..." p:service-ref="service" />
</beans>
Inject value for property 'url'
 Copyright 2014 Pivotal. All rights reserved.
Inject reference for bean 'service'
12
No schemaLocation needed
<?xml version="1.0" encoding="UTF-8"?>
p and c
<beans xmlns="http://www.springframework.org/schema/beans
namespace
xmlns:p="http://www.springframework.org/schema/p"
definitions
xmlns:c="http://www.springframework.org/schema/c"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- ... -->
</beans>
 Copyright 2014 Pivotal. All rights reserved.
no extra schemaLocation
entry required (no xsd)
13
'c' and 'p' Pros and Cons
 Pros
 More concise
 Well supported in STS
 CTRL+space works well
 Cons
 Less widely known that the usual XML configuration syntax
 Copyright 2014 Pivotal. All rights reserved.
14
Topics in this session
Factory Beans / Factory Method
'p' and 'c' namespaces
Profiles
Externalizing values into properties files
Using Bean definition inheritance
Lab
Advanced Features
 Inner beans, collections, SpEL
 Copyright 2014 Pivotal. All rights reserved.
15
Profile Configuration XML
 All bean definitions
<beans xmlns=http://www.springframework.org/schema/beans 
profile="dev">  </beans>
Profile applies to all beans
 Subset of bean definitions
<beans xmlns=http://www.springframework.org/schema/beans ...>
<bean id="rewardNetwork"  /> <!-- Available to all profiles -->
...
<beans profile="dev"> ... </beans>
<beans profile="prod"> ... </beans>
</beans>
 Copyright 2014 Pivotal. All rights reserved.
Different subset
of beans for each
profile, plus some
shared beans
16
Sample XML Configuration
<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
xmlns:jee=http://www.springframework.org/schema/jee
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">
<jee:jndi-lookup id="dataSource" jndi-name="java:comp/env/jdbc/datasource" />
</beans>
</beans>
 Copyright 2014 Pivotal. All rights reserved.
17
Topics in this session
Factory Beans / Factory Method
'p' and 'c' namespaces
Profiles
Externalizing values into properties files
Using Bean definition inheritance
Lab
Advanced Features
 Inner beans, collections, SpEL
 Copyright 2014 Pivotal. All rights reserved.
18
Externalizing values to a properties file (1)
 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 ... />
Context namespace
</beans>
 Copyright 2014 Pivotal. All rights reserved.
19
Externalizing values to a properties file (2)
<beans ...>
<context:property-placeholder location="db-config.properties" />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="URL" value="${db.url}" />
<property name="user" value="${db.user.name}" />
</bean>
</beans>
db.url=jdbc:postgresql:...
db.user.name=moneytransfer-app
db-config.properties
Resolved at
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource"> startup time
<property name="URL" value="jdbc:postgresql:..." />
<property name="user" value="moneytransfer-app" />
</bean>
 Copyright 2014 Pivotal. All rights reserved.
20
Topics in this session
Factory Beans / Factory Method
'p' and 'c' namespaces
Profiles
Externalizing values into properties files
Using Bean definition inheritance
Lab
Advanced Features
 Inner beans, collections, SpEL
 Copyright 2014 Pivotal. All rights reserved.
21
Bean Definition Inheritance (1)
 Sometimes several beans need to be configured in the
same way
 Use bean definition inheritance to define the common
configuration once
 Inherit it where needed
 Copyright 2014 Pivotal. All rights reserved.
22
Without Bean Definition Inheritance
<beans>
<bean id="pool-A" class="org.apache.commons.dbcp.BasicDataSource">
<property name="URL" value="jdbc:postgresql://server-a/transfer" />
<property name="user" value="moneytransfer-app" />
</bean>
<bean id="pool-B" class="org.apache.commons.dbcp.BasicDataSource">
<property name="URL" value="jdbc:postgresql://server-b/transfer" />
<property name="user" value="moneytransfer-app" />
</bean>
<bean id="pool-C" class="org.apache.commons.dbcp.BasicDataSource">
<property name="URL" value="jdbc:postgresql://server-c/transfer" />
<property name="user" value="moneytransfer-app" />
</bean>
Can you find the duplication?
</beans>
 Copyright 2014 Pivotal. All rights reserved.
23
Abstract Parent bean
<beans>
<bean id="abstractPool"
class="org.apache.commons.dbcp.BasicDataSource" abstract="true">
<property name="user" value="moneytransfer-app" />
</bean>
Will not be instantiated
<bean id="pool-A" parent="abstractPool">
<property name="URL" value="jdbc:postgresql://server-a/transfer" />
</bean>
<bean id="pool-B" parent="abstractPool">
<property name="URL" value="jdbc:postgresql://server-b/transfer" />
</bean>
<bean id="pool-C" parent="abstractPool">
<property name="URL" value="jdbc:postgresql://server-c/transfer" />
<property name="user" value="bank-app" />
Can override
</bean>
</beans>
Each pool inherits its parent configuration
 Copyright 2014 Pivotal. All rights reserved.
24
Default Parent Bean
<beans>
<bean id="defaultPool" class="org.apache.commons.dbcp.BasicDataSource">
<property name="URL" value="jdbc:postgresql://server-a/transfer" />
<property name="user" value="moneytransfer-app" />
</bean>
Overrides URL property
<bean id="pool-B" parent="defaultPool">
<property name="URL" value="jdbc:postgresql://server-b/transfer" />
</bean>
<bean id="pool-C" parent="defaultPool" class="example.SomeOtherPool">
<property name="URL"
value="jdbc:postgresql://server-c/transfer" />
</bean>
</beans>
 Copyright 2014 Pivotal. All rights reserved.
Overrides class as well
25
Inheritance for service and repository beans
 Bean inheritance commonly used for definition of Service
and Repository (or DAO) beans
<bean id="abstractRepo"  />
<bean id=
"rewardsRepo" />
 Copyright 2014 Pivotal. All rights reserved.
<bean id=
"orderRepo" />
<bean id="abstractService"  />
<bean id=
"rewardsService" />
<bean id=
"orderService" />
26
Lab (Optional)
Using Bean Definition Inheritance and
Property Placeholders
 Copyright 2014 Pivotal. All rights reserved.
27
Topics in this session
Factory Beans / Factory Method
'p' and 'c' namespaces
Profiles
Externalizing values into properties files
Using Bean definition inheritance
Lab
Advanced Features
 Inner beans
 Collections
 SpEL
 Copyright 2014 Pivotal. All rights reserved.
28
Inner beans
 Inner bean only visible from surrounding bean
<bean id="restaurantRepository"
class="rewards.internal.restaurant.JdbcRestaurantRepository">
<property name="benefitAvailabilityPolicy">
<bean class="rewards...DefaultBenefitAvailabilityPolicyFactory" />
</property>
No bean id
</bean>
 Cannot be accessed from the applicationContext
OK
applicationContext.getBean(RestaurantRepository.class);
applicationContext.getBean(DefaultBenefitAvailabilityPolicyFactory.class);
NoSuchBeanDefinitionException!!
 Copyright 2014 Pivotal. All rights reserved.
29
Without an Inner Bean
<beans>
<bean id="restaurantRepository"
class="rewards.internal.restaurant.JdbcRestaurantRepository">
<property name="dataSource" ref="dataSource" />
<property name="benefitAvailabilityPolicyFactory" ref="factory" />
</bean>
Can be referenced by other beans
(even if it should not be)
<bean id="factory"
class="rewards.internal.restaurant.availability.
DefaultBenefitAvailabilityPolicyFactory">
<constructor-arg ref="rewardHistoryService" />
</bean>
</beans>
 Copyright 2014 Pivotal. All rights reserved.
30
With an Inner Bean
<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 ref="rewardHistoryService" />
</bean>
</property> Inner bean has no id (it is anonymous)
</bean>
Cannot be referenced outside this
scope
</beans>
 Copyright 2014 Pivotal. All rights reserved.
31
Multiple Levels of Nesting
<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>
 Copyright 2014 Pivotal. All rights reserved.
32
Inner Beans: pros and cons
 Pros
 You only expose what needs to be exposed
 Cons
 Harder to read
 General recommendation
 Use them sparingly
 As for inner classes in Java
 Common choice: Complex "infrastructure beans"
configuration
 Copyright 2014 Pivotal. All rights reserved.
33
Topics in this session
Factory Beans / Factory Method
'p' and 'c' namespaces
Profiles
Externalizing values into properties files
Using Bean definition inheritance
Lab
Advanced Features
 Inner beans
 Collections
 SpEL
 Copyright 2014 Pivotal. All rights reserved.
34
beans and util collections
 beans collections
 From the default beans namespace
 Simple and easy
 util collections
 From the util namespace
 Requires additional namespace declaration
 More features available
Both offer support for set, map, list and properties collections
 Copyright 2014 Pivotal. All rights reserved.
35
Using the beans namespace
<bean id="service" class="com.acme.service.TransferServiceImpl">
<property name="customerPolicies">
<list>
<ref bean="privateBankingCustomerPolicy"/>
<ref bean="retailBankingCustomerPolicy"/>
<bean class="com.acme.DefaultCustomerPolicy"/>
</list>
public void setCustomerPolicies(java.util.List policies) { .. }
</property>
</bean>
Equivalent to:
TransferServiceImpl service = new TransferServiceImpl();
service.setCustomerPolicies(list); // create list with bean references
ApplicationContext
service -> instance of TransferServiceImpl
 Copyright 2014 Pivotal. All rights reserved.
36
beans collections limitation
 Can't specify the collection type
 eg. for java.util.List the implementation is ArrayList
 Collection has no bean id
 Can't be accessed from the ApplicationContext
 Only valid as inner beans
<bean id="service" class="com.acme.service.TransferServiceImpl">
<property name="customerPolicies">
<list> ... </list>
</property>
</bean>
OK
NoSuchBeanDefinitionException!!
applicationContext.getBean("service");
applicationContext.getBean("customerPolicies");
 Copyright 2014 Pivotal. All rights reserved.
37
Injecting a Set or Map
 Similar support available for Set
<property name="customerPolicies">
<set>
<ref bean="privateBankingCustomerPolicy"/>
<ref bean="retailBankingCustomerPolicy"/>
</set>
</property>
 Map (through map / entry / key elements)
<property name="customerPolicies">
<map>
<entry key="001-pbcp" value-ref="privateBankingCustomerPolicy"/>
<entry key-ref="keyBean" value-ref="retailBankingCustomerPolicy"/>
</map>
Key can use primitive
</property>
type or ref to bean
 Copyright 2014 Pivotal. All rights reserved.
38
Injecting a collection of type Properties
 Convenient alternative to a dedicated properties file
 Use when property values are unlikely to change
<property name="config">
<value>
server.host=mailer
server.port=1010
</value>
</property>
<property name="config">
<props>
<prop key="server.host">mailer</prop>
<prop key="server.port">1010</prop>
</props>
</property>
public void setConfig(java.util.Properties props) { .. }
 Copyright 2014 Pivotal. All rights reserved.
39
util collections
 util: collections allow:
 specifying collection implementation-type and scope
 declaring a collection as a top-level bean
<bean id="service" class="com.acme.service.TransferServiceImpl"
p:customerPolicies-ref="customerPolicies"/>
bean id
<util:set id="customerPolicies" set-class="java.util.TreeSet">
<ref bean="privateBankingCustomerPolicy"/>
<ref bean="retailBankingCustomerPolicy"/>
</util:set>
 Copyright 2014 Pivotal. All rights reserved.
Implementation class
Also: util:list, util:map, util:properties
40
beans or util collections?
 In most cases, the default beans collections will suffice
 But can only be inner beans
 Just remember the additional features of collections from the
<util/> namespace in case you would need them
 Declare a collection as a top-level bean
 Specify collection implementation-type
 Copyright 2014 Pivotal. All rights reserved.
41
Topics in this session
Factory Beans / Factory Method
'p' and 'c' namespaces
Profiles
Externalizing values into properties files
Using Bean definition inheritance
Lab
Advanced Features
 Inner beans
 Collections
 SpEL
 Copyright 2014 Pivotal. All rights reserved.
42
Spring Expression Language
 SpEL for short
 Inspired by the Expression Language used in
Spring WebFlow
 Pluggable/extendable by other Spring-based
frameworks
SpEL was introduced in Spring 3.0
 Copyright 2014 Pivotal. All rights reserved.
43
SpEL examples  XML
<bean id="rewardsDb" class="com.acme.RewardsTestDatabase">
<property name="keyGenerator"
value="#{strategyBean.databaseKeyGenerator}" />
</bean>
Can refer a
nested property
<bean id="strategyBean" class="com.acme.DefaultStrategies">
<property name="databaseKeyGenerator" ref="myKeyGenerator"/>
</bean>
<bean id="taxCalculator" class="com.acme.TaxCalculator">
<property name="defaultLocale" value="#{ systemProperties['user.region'] }"/>
</bean>
 Copyright 2014 Pivotal. All rights reserved.
Equivalent to
System.getProperty(...)
44
SpEL examples  Using @Value
<bean id="rewardsDb" class="com.acme.RewardsTestDatabase">
<property name="databaseName" value="#{systemProperties['database.name']}" />
<property name="keyGenerator" value="#{strategyBean.databaseKeyGenerator}" />
</bean>
@Repository
public class RewardsTestDatabase {
@Value("#{systemProperties.databaseName}")
public void setDatabaseName(String dbName) { ... }
@Value("#{strategyBean.databaseKeyGenerator}")
public void setKeyGenerator(KeyGenerator kg) { ... }
@Configuration
}
class RewardConfig
{
@Bean public RewardsDatabase rewardsDatabase
(@Value("#{systemProperties.databaseName}") String databaseName, ) {
...
}
}
 Copyright 2014 Pivotal. All rights reserved.
45
SpEL
 EL Attributes can be:
 Named Spring beans
 Implicit references
 systemProperties and systemEnvironment available by
default
 SpEL allows to create custom functions and references
 Widely used in Spring projects
Spring
Spring
Spring
Spring
...
 Copyright 2014 Pivotal. All rights reserved.
Security
WebFlow
Batch
Integration
46
Using SpEL functions
 In Spring Security
<security:intercept-url pattern="/accounts/**"
access="isAuthenticated() and hasIpAddress('192.168.1.0/24')" />
 In Spring Batch
<bean id="flatFileItemReader" scope="step"
class="org.springframework.batch.item.file.FlatFileItemReader">
<property name="resource" value="#{jobParameters['input.file.name'] }" />
</bean>
Spring Security will be discussed later in this course. Spring Batch is
part of the "Spring Enterprise" course
 Copyright 2014 Pivotal. All rights reserved.
47
Summary
 Spring offers many techniques to simplify XML
configuration
 We've seen just a few here
 It's about expressiveness and elegance, just like code
 Best practices we've discussed can be used daily in
most Spring XML projects
 Imports, Bean inheritance...
 Advanced features are more specialized
 Copyright 2014 Pivotal. All rights reserved.
48
Understanding the
Bean Lifecycle
An In-Depth Look Under the Hood
Using Bean Pre- and Post-Processors
 Copyright 2014 Pivotal. All rights reserved.
Topics in this session
Introduction
The initialization phase
The use phase
The destruction phase
 Copyright 2014 Pivotal. All rights reserved.
Phases of the Application Lifecycle
Initialization
 Prepares for use
 Application services
 Are created
 Configured
 May allocate
system resources
 Application is not
usable until this
phase is complete
 Copyright 2014 Pivotal. All rights reserved.
Use
 Used by clients
 Application
services
 Process client
requests
 Carry out
application
behaviors
 99.99% of the
time is spent in
this phase
Destruction
 Shuts down
 Application
services
 Release any
system resources
 Are eligible for
garbage
collection
Springs Role as a Lifecycle Manager
 This lifecycle applies to any class of application
 Standalone Java application
 JUnit System Test
 Java EE (web or full profile)
 Spring fits in to manage application lifecycle
 Plays an important role in all phases
 Lifecycle is the same in all these configurations
 Lifecycle is the same for all 3 dependency injection
styles
 XML, annotations and Java Configuration
Initialization
 Copyright 2014 Pivotal. All rights reserved.
Use
Destruction
Topics in this session
Introduction
The initialization phase
The use phase
The destruction phase
Initialization
 Copyright 2014 Pivotal. All rights reserved.
Use
Destruction
Lifecycle of a Spring Application Context (1) - The
Initialization Phase
 When a context is created the initialization phase
completes
// Create the application from the configuration
ApplicationContext context =
new SpringApplication.run(AppConfig.class);
 But what exactly happens in this phase?
 Copyright 2014 Pivotal. All rights reserved.
Bean Initialization Steps
for-each bean ...
Bean
Definitions
Loaded
Post Process
Bean
Definitions
Instantiate
Beans
Load Bean Definitions
What you've seen before
Bean
Ready
For Use
Dependency
Injection
BPP
BPP
Setters
Called
Initializer
BPP
BPP
Bean Post Processors
Create and Initialize Beans
 Copyright 2014 Pivotal. All rights reserved.
Inside The Application Context
- Initialization Lifecycle
 Load bean definitions
 Initialize bean instances
Bean
Definitions
Loaded
Post Process
Bean
Definitions
Load Bean Definitions
Bean
Ready
For Use
 Copyright 2014 Pivotal. All rights reserved.
After
Init
Initializers
Called
Instantiate
Beans
Setters
Called
Before
Init
Load Bean Definitions
 The @Configuration classes are processed
 And/or @Components are scanned for
 And/or XML files are parsed
 Bean definitions added to BeanFactory
 Each indexed under its id
 Special BeanFactoryPostProcessor beans invoked
 Can modify the definition of any bean
Bean
Definitions
Loaded
Post Process
Bean
Definitions
Load Bean Definitions
 Copyright 2014 Pivotal. All rights reserved.
Load Bean Definitions
AppConfig.java
@Bean
public TransferService transferService() {  }
@Bean
public AccountRepository
accountRepository() {  }
TestInfrastructureConfig.java
@Bean
public DataSource dataSource () {  }
Can modify the definition of
any bean in the factory
before any objects are created
 Copyright 2014 Pivotal. All rights reserved.
Application Context
BeanFactory
transferService
accountRepository
dataSource
postProcess(BeanFactory)
BeanFactoryPostProcessors
10
BeanFactoryPostProcessor Extension Point
 Applies transformations to bean definitions
 Before objects are actually created
 Several useful implementations provided in Spring
 You can write your own (not common)
 Implement BeanFactoryPostProcessor interface
public interface BeanFactoryPostProcessor {
public void postProcessBeanFactory
(ConfigurableListableBeanFactory beanFactory);
}
 Copyright 2014 Pivotal. All rights reserved.
11
Most Common Example of
BeanFactoryPostProcessor
Remember the
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>
 Copyright 2014 Pivotal. All rights reserved.
12
Inside the Application Context Initialization
Lifecycle
 Load bean definitions
 Initialize bean instances
Bean
Definitions
Loaded
for-each bean
Post Process
Bean
Definitions
Instantiate
Beans
Setters
Called
Create Beans
Bean
Ready
For Use
After
Init
Initializers
Called
Before
Init
Bean Post-Processor(s)
 Copyright 2014 Pivotal. All rights reserved.
13
Initializing Bean Instances
 Each bean is eagerly instantiated by default
 Created in right order with its dependencies injected
 After dependency injection each bean goes through a
post-processing phase
 Further configuration and initialization may occur
 After post processing the bean is fully initialized and
ready for use
 Tracked by its id until the context is destroyed
Lazy beans are supported  only created when getBean() called.
Not recommended, often misused: @Lazy or <bean lazy-init=true ...>
 Copyright 2014 Pivotal. All rights reserved.
14
Bean Post Processing
 There are two types of bean post processors
 Initializers
 Initialize the bean if instructed (i.e. @PostConstruct)
 All the rest!
 Allow for additional configuration
 May run before or after the initialize step
BPP
BPP
Initializer
BPP
BPP
Bean Post Processors
 Copyright 2014 Pivotal. All rights reserved.
15
The Initializer Extension Point
 All init methods are called
Initializer
BPP
BPP
BPP
BPP
Bean Post Processors
public class JdbcAccountRepo {
@PostConstruct
public void populateCache() {
//...
}
...
}
By Annotation
<bean id=accountRepository
class=com.acme.JdbcAccountRepo
init-method=populateCache>
</bean>
Using XML only
<context:annotation-config/>
Declares several BPPs including
CommonAnnotationBeanPostProcessor
 Copyright 2014 Pivotal. All rights reserved.
16
The BeanPostProcessor Extension Point
BPP
BPP
Initializer
Bean Post Processors
BPP
BPP
 An important extension point in Spring
Course
will show
several
BPPs
 Can modify bean instances in any way
 Powerful enabling feature
 Spring provides several implementations
 You can write your own (not common)
 Must implement the BeanPostProcessor interface
public interface BeanPostProcessor {
public Object postProcessAfterInitialization(Object bean, String beanName);
public Object postProcessBeforeInitialization(Object bean,String beanName);
}
Post-processed bean
 Copyright 2014 Pivotal. All rights reserved.
Original bean
17
Configuration Lifecycle
Bean
detection
XML
config
Load xml
definitions
BeanFacPP
Bean instantiation and
dependency injection
Instantiation &
constr. injection
Property
injection
Annotation
config
@Component
scanning
Instantiation &
@Autowired
on constructor
Java
config
Read @Bean
method
signatures
Call @Bean method implementations
BeanFacPP 
BeanPP 
 Copyright 2014 Pivotal. All rights reserved.
BeanPP
Injection of
@Autowired
methods & fields
BeanFactoryPostProcessor
BeanPostProcessor
18
The Full Initialization Lifecycle
for-each bean ...
Bean
Definitions
Loaded
Post Process
Bean
Definitions
Instantiate
Beans
Load Bean Definitions
Dependency
Injection
Bean
Ready
For Use
BPP
BPP
Setters
Called
Initializer
BPP
BPP
Bean Post Processors
Create and Initialize Beans
 Copyright 2014 Pivotal. All rights reserved.
19
Topics in this session
Introduction
The initialization phase
The use phase
The destruction phase
Initialization
 Copyright 2014 Pivotal. All rights reserved.
Use
Destruction
20
Lifecycle of a Spring Application Context (2)
- The Use Phase
 When you invoke a bean obtained from the context the
application is used
ApplicationContext context = // get it from somewhere
// Lookup the entry point into the application
TransferService service =
(TransferService) context.getBean(transferService);
// Use it!
service.transfer(new MonetaryAmount(50.00), 1, 2);
 But exactly what happens in this phase?
 Copyright 2014 Pivotal. All rights reserved.
21
Inside The Bean Request (Use) Lifecycle
 The bean is just your raw object
 it is simply invoked directly (nothing special)
transfer($50, 1, 2)
TransferServiceImpl
 Your bean has been wrapped in a proxy
 things become more interesting
transfer($50, 1, 2)
Spring Proxy
TransferServiceImpl
Proxy classes are created in the init phase by dedicated
BeanPostProcessors
 Copyright 2014 Pivotal. All rights reserved.
22
Proxy Power
 A BeanPostProcessor may wrap
your beans in a dynamic proxy
TransferService
 adds behavior to your bean
transparently
Spring Proxy
transfer($50, 1, 2)
Spring
TransactionInterceptor
begin
commit
TransactionManager
 Copyright 2014 Pivotal. All rights reserved.
Target
TransferServiceImpl
Transactional
behavior is added
around the target
(your bean)
23
Kinds of Proxies
 Spring will create either JDK or CGLib proxies
JDK Proxy
 Also called dynamic
proxies
 API is built into the JDK
 Requirements: Java
interface(s)
CGLib Proxy
 NOT built into JDK
 Included in Spring jars
 Used when interface not
available
 Cannot be applied to final
classes or methods
Recommendation: Code to interfaces / Use JDK proxies (default)
See Spring Reference - 10.5.3 JDK- and CGLIB-based proxies
 Copyright 2014 Pivotal. All rights reserved.
24
JDK vs CGLib Proxies
 JDK Proxy
 CGLib Proxy
 Interface based
 subclass based
TransferServiceImpl
TransferService
implements
Spring Proxy
Extra
Logic
 Copyright 2014 Pivotal. All rights reserved.
implements
Target
TransferServiceImpl
extends
Spring Proxy
Extra
Logic
Target
TransferServiceImpl
25
Topics in this session
Introduction
The initialization phase
The use phase
The destruction phase
Initialization
 Copyright 2014 Pivotal. All rights reserved.
Use
Destruction
26
The Lifecycle of a Spring Application Context (3)
- The Destruction Phase
 When you close a context the destruction phase
completes
ConfigurableApplicationContext context = 
// Destroy the application
context.close();
 But exactly what happens in this phase?
 Copyright 2014 Pivotal. All rights reserved.
27
Application Context Destruction Lifecycle (1)
 Destroy bean instances if instructed
 Call their destroy (clean-up) methods
 Beans must have a destroy method defined
Remember:
only GC actually
destroys objects
 A no-arg method returning void
 Context then destroys (cleans-up) itself
 The context is not usable again
A method on the
AccountRepository
@Bean (destroyMethod=clearCache)
public AccountRepository accountRepository() {
// ...
JavaConfig
}
- Called only when ApplicationContext / JVM exit normally
- Not called for prototype beans
 Copyright 2014 Pivotal. All rights reserved.
28
Application Context Destruction Lifecycle (2)
 Can do the same using XML or annotations
 Annotations require annotation-driven or the component
scanner to be activated
Using XML
By Annotation
public class AccountRepository {
<bean id=accountRepository
class=app.impl.AccountRepository
destroy-method=clearCache>
</bean>
@PreDestroy
void clearCache() {
// close files, connections ...
// remove external resources ...
}
}
<context:annotation-driven/>
<context:component-scan  />
 Copyright 2014 Pivotal. All rights reserved.
29
Topics Covered
 Spring Lifecycle
 The initialization phase
 Bean Post Processors for initialization and proxies
 The use phase
 Proxies at Work  most of Spring's magic uses a proxy
 The destruction phase
 Allow application to terminate cleanly
Initialization
 Copyright 2014 Pivotal. All rights reserved.
Use
Destruction
30
Testing Spring
Applications
Unit Testing without Spring
Integration Testing with Spring
Testing in General, Spring and JUnit, Profiles
 Copyright 2014 Pivotal. All rights reserved.
Topics in this Session
Test Driven Development
Unit Testing vs. Integration Testing
Integration Testing with Spring
Testing with Profiles
Testing with Databases
 Copyright 2014 Pivotal. All rights reserved.
What is TDD
 TDD = Test Driven Development
 Is it writing tests before the code? Is it writing tests at the
same time as the code?
 That is not what is most important
 TDD is about:
 writing automated tests that verify code actually works
 Driving development with well defined requirements in the
form of tests
 Copyright 2014 Pivotal. All rights reserved.
But I Dont Have Time to
Write Tests!
 Every development process includes testing
 Either automated or manual
 Automated tests result in a faster development cycle
overall
 Your IDE is better at this than you are
 Properly done TDD is faster than development without
tests
 Copyright 2014 Pivotal. All rights reserved.
TDD and Agility
 Comprehensive test coverage provides confidence
 Confidence enables refactoring
 Refactoring is essential to agile development
 Copyright 2014 Pivotal. All rights reserved.
TDD and Design
 Testing makes you think about your design
 If your code is hard to test then the design should be
reconsidered
 Copyright 2014 Pivotal. All rights reserved.
TDD and Focus
 A test case helps you focus on what matters
 It helps you not to write code that you don't need
 Find problems early
 Copyright 2014 Pivotal. All rights reserved.
Benefits of Continuous Integration
 The cost to fix a bug grows exponentially in proportion to
the time before it is discovered
time
to fix
time until discovered
 Continuous Integration (CI) focuses on reducing the time
before the bug is discovered
 Effective CI requires automated tests
 Copyright 2014 Pivotal. All rights reserved.
Topics in this Session
Test Driven Development
Unit Testing vs. Integration Testing
Integration Testing with Spring
Testing with Profiles
Testing with Databases
 Copyright 2014 Pivotal. All rights reserved.
Unit Testing vs.
Integration Testing
 Unit Testing
 Tests one unit of functionality
 Keeps dependencies minimal
 Isolated from the environment (including Spring)
 Integration Testing
 Tests the interaction of multiple units working together
 Integrates infrastructure
 Copyright 2014 Pivotal. All rights reserved.
10
Unit Testing
 Remove links with dependencies
 The test shouldn't fail because of external dependencies
 Spring is also considered as a dependency
 2 ways to create a testing-purpose implementation of
your dependencies:
 Stubs Create a simple test implementation
 Mocks Dependency class generated at startup-time using
a Mocking framework
 Copyright 2014 Pivotal. All rights reserved.
11
Unit Testing example
 Production mode
 Unit test with Stubs
AuthenticatorImplTest
AuthenticatorImpl
AuthenticatorImpl
JUnit
Injected by Spring
JpaAccountRepo
Spring config
JPA config
AccountRepoStub
fake implementation
NO Database!!
Production DB
 Copyright 2014 Pivotal. All rights reserved.
12
Example Unit to be Tested
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;
External dependency
}}
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);
Unit business logic
 2 paths: success or fail
Note: Validation failure paths ignored for simplicity
 Copyright 2014 Pivotal. All rights reserved.
13
Implementing a Stub
 Class created manually
 Implements Business interface
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;
}}
Simple state
}}
AccountRepository
JPA
AccountRepository
 Copyright 2014 Pivotal. All rights reserved.
Stub
AccountRepository
14
Unit Test using a Stub
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;
Spring not in charge of
injecting dependencies
@Before
@Before public
public void
void setUp()
setUp() {{
authenticator
authenticator == new
new AuthenticatorImpl(
AuthenticatorImpl( new
new StubAccountRepository()
StubAccountRepository() ););
}}
OK scenario
@Test
@Test public
public void
void successfulAuthentication()
successfulAuthentication() {{
assertTrue(authenticator.authenticate(lisa,
assertTrue(authenticator.authenticate(lisa, secret));
secret));
}}
KO scenario
}}
@Test
@Test public
public void
void invalidPassword()
invalidPassword() {{
assertFalse(authenticator.authenticate(lisa,
assertFalse(authenticator.authenticate(lisa, invalid));
invalid));
}}
 Copyright 2014 Pivotal. All rights reserved.
15
Unit Testing with Stubs
 Advantages
 Easy to implement and understand
 Reusable
 Disadvantages
 Change to an interface requires change to stub
 Your stub must implement all methods
 even those not used by a specific scenario
 If a stub is reused refactoring can break other tests
 Copyright 2014 Pivotal. All rights reserved.
16
Steps to Testing with a Mock
1. Use a mocking library to generate a mock object
 Implements the dependent interface on-the-fly
2. Record the mock with expectations of how it will be used
for a scenario
 What methods will be called
 What values to return
3. Exercise the scenario
4. Verify mock expectations were met
 Copyright 2014 Pivotal. All rights reserved.
17
Example: Using a Mock - I
 Setup
 A Mock class is created at startup time
import static org.easymock.classextensions.EasyMock.*;
public class AuthenticatorImplTests {
private AccountRepository accountRepository
= createMock(AccountRepository.class);
static import
private AuthenticatorImpl authenticator
= new AuthenticatorImpl(accountRepository);
// continued on next slide ...
 Copyright 2014 Pivotal. All rights reserved.
Implementation of interface
AccountRepository is created
18
Example: Using a Mock - II
//  continued from previous slide
@Test public void validUserWithCorrectPassword() {
expect(accountRepository.getAccount(lisa)).
andReturn(new Account(lisa, secret));
replay(accountRepository);
boolean res = authenticator.
authenticate(lisa, secret);
assertTrue(res);
verify(accountRepository);
}
}
 Copyright 2014 Pivotal. All rights reserved.
Recording
What behavior to
expect?
Recording
Playback
playback
mode
Mock now fully available
Verification
No planned method call
has been omitted
19
Mock Considerations
 Several mocking libraries available
 Mockito, JMock, EasyMock
 Advantages
 No additional class to maintain
 You only need to setup what is necessary for the scenario
you are testing
 Test behavior as well as state
 Were all mocked methods used? If not, why not?
 Disadvantages
 A little harder to understand at first
 Copyright 2014 Pivotal. All rights reserved.
20
Mocks or Stubs?
 You will probably use both
 General recommendations
 Favor mocks for non-trivial interfaces
 Use stubs when you have simple interfaces with repeated
functionality
 Always consider the specific situation
 Read Mocks Arent Stubs by Martin Fowler
 http://www.martinfowler.com/articles/mocksArentStubs.html
 Copyright 2014 Pivotal. All rights reserved.
21
Topics in this Session
Test Driven Development
Unit Testing vs. Integration Testing
Integration Testing with Spring
Testing with Profiles
Testing with Databases
 Copyright 2014 Pivotal. All rights reserved.
22
Integration Testing
 Tests the interaction of multiple units
 Tests application classes in the context of their
surrounding infrastructure
 Infrastructure may be scaled down
 e.g. use Apache DBCP connection pool instead of
container-provider pool obtained through JNDI
 Copyright 2014 Pivotal. All rights reserved.
23
Integration test example
 Production mode
caller
Injected
by Spring
AuthenticatorImpl
Injected
by Spring
JpaAccountRepo
Production DB
 Copyright 2014 Pivotal. All rights reserved.
 Integration test
AuthenticatorTest
Injected
by Spring
AuthenticatorImpl
Injected
by Spring
JpaAccountRepo
Test DB
24
Springs Integration Test Support
 Packaged as a separate module
 spring-test.jar
 Consists of several JUnit test support classes
 Central support class is SpringJUnit4ClassRunner
 Caches a shared ApplicationContext across test methods
See: Spring Framework Reference  Integration Testing
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#integration-testing
 Copyright 2014 Pivotal. All rights reserved.
25
Using Spring's Test Support
Run with Spring support
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=SystemTestConfig.class)
@ContextConfiguration(classes=SystemTestConfig.class)
public
public final
final class
class TransferServiceTests
TransferServiceTests {{
@Autowired
@Autowired
private
private TransferService
TransferService transferService;
transferService;
Point to system test
configuration file
Inject bean to test
@Test
@Test
public
public void
void successfulTransfer()
successfulTransfer() {{
TransferConfirmation
TransferConfirmation conf
conf == transferService.transfer(...);
transferService.transfer(...);
...
...
}} Test the system as normal
}}
 Copyright 2014 Pivotal. All rights reserved.
No need for @Before method
26
@ContextConfiguration and JavaConfig
 Testing Java Configuration defined beans
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={AppConfig.class,
@ContextConfiguration(classes={AppConfig.class, SystemConfig.class})
SystemConfig.class})
public
public class
class TransferServiceTests
TransferServiceTests {{ 
 }}
For @Configuration classes
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@ContextConfiguration
public
Inner class must be static
public class
class MyTest
MyTest {{
@Configuration
@Configuration
public
public static
static class
class TestConfiguration
TestConfiguration {{
@Bean
@Bean public
public DataSource
DataSource dataSource()
dataSource() {{ 
 }}
}}
}}
Inner @Configuration
automatically detected
 Copyright 2014 Pivotal. All rights reserved.
27
@ContextConfiguration XML Examples
 Tests when using XML based configuration
@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 {{ 
 }}
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@ContextConfiguration
public
public class
class TransferServiceTests
TransferServiceTests {{ 
 }}
Defaults to
${classname}-context.xml
in same package
Loads TransferServiceTests-context.xml
 Copyright 2014 Pivotal. All rights reserved.
28
Multiple test methods
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=SystemTestConfig.class)
@ContextConfiguration(classes=SystemTestConfig.class)
public
public final
final class
class TransferServiceTests
TransferServiceTests {{
@Autowired
@Autowired
private
private TransferService
TransferService transferService;
transferService;
@Test
@Test
public
public void
void successfulTransfer()
successfulTransfer() {{
...
...
}}
The ApplicationContext is
instantiated only once for
all tests that use the same
set of config files
(even across test classes)
@Test
@Test
public
public void
void failedTransfer()
failedTransfer() {{
...
...
}}
}}
Annotate test method with @DirtiesContext to force recreation of the
cached ApplicationContext if method changes the contained beans
 Copyright 2014 Pivotal. All rights reserved.
29
Topics in this Session
Test Driven Development
Unit Testing vs. Integration Testing
Integration Testing with Spring
Testing with Profiles
Testing with Databases
 Copyright 2014 Pivotal. All rights reserved.
30
Activating Profiles For a Test
 @ActiveProfiles inside the test class
 Define one or more profiles
 Beans associated with that profile are instantiated
 Also beans not associated with any profile
 Example: Two profiles activated  jdbc and dev
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=DevConfig.class)
@ActiveProfiles( { "jdbc", "dev" } )
public class TransferServiceTests {  }
 Copyright 2014 Pivotal. All rights reserved.
31
Profiles Activation with JavaConfig
 @ActiveProfiles inside the test class
 @Profile inside the @Configuration class
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=DevConfig.class)
@ActiveProfiles("jdbc")
public class TransferServiceTests
{...}
@Configuration
@Profile("jdbc")
public class DevConfig {
@Bean
{...}
}
Remember: only @Configurations matching an active profile or
with no profile are loaded
 Copyright 2014 Pivotal. All rights reserved.
32
Profiles Activation with Annotations
 @ActiveProfiles inside the test class
 @Profile inside the Component class
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=DevConfig.class)
@ActiveProfiles("jdbc")
public class TransferServiceTests
{...}
@Repository
@Profile("jdbc")
public class
JdbcAccountRepository
{ ...}
Only beans with current profile / no profile are component-scanned
 Copyright 2014 Pivotal. All rights reserved.
33
Profiles Activation with XML
 @ActiveProfiles inside the test class
 profile attribute inside <bean> tag
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(infra-test-conf.xml)
@ActiveProfiles("jdbc")
public class TransferServiceTests
{...}
<beans xmlns=...>
<!-- Available to all profiles 
<bean id="rewardNetwork"  />
...
<beans profile="jdbc"> ... </beans>
<beans profile="jpa"> ... </beans>
</beans>
Only beans with current profile / no profile are loaded
 Copyright 2014 Pivotal. All rights reserved.
34
Topics in this Session
Test Driven Development
Unit Testing vs. Integration Testing
Integration Testing with Spring
Testing with Profiles
Testing with Databases
 Copyright 2014 Pivotal. All rights reserved.
35
Spring 4.1
Testing with Databases
 Integration testing against SQL database is common.
 In-memory databases useful for this kind of testing
 No prior install needed
 Common requirement: populate DB before test runs
 Use the @Sql annotation:
@Test
@Test
@Sql
@Sql (( /testfiles/test-data.sql
/testfiles/test-data.sql ))
public
public void
void successfulTransfer()
successfulTransfer() {{
...
...
}}
Run this SQL command
Before this test method executes.
See: Spring Framework Reference, Executing SQL Scripts
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#testcontext-executing-sql
 Copyright 2014 Pivotal. All rights reserved.
36
Spring 4.1
@Sql Examples
Run these scripts before
each @Test method
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(...)
@ContextConfiguration(...)
@Sql({
@Sql({ /testfiles/schema.sql,
/testfiles/schema.sql, /testfiles/general-data.sql
/testfiles/general-data.sql }} ))
public
public final
final class
class MainTests
MainTests {{
@Test
@Test
@Sql
@Sql
public
public void
void success()
success() {{ 
 }}
Run script named
MainTests.success.sql
in same package
Run before @Test method...
}}
@Test
@Test
...run after @Test method
@Sql
@Sql (( /testfiles/error.sql
/testfiles/error.sql ))
@Sql
@Sql (( scripts=/testfiles/cleanup.sql,
scripts=/testfiles/cleanup.sql,
executionPhase=Sql.ExecutionPhase.AFTER_TEST_METHOD
executionPhase=Sql.ExecutionPhase.AFTER_TEST_METHOD ))
public
public void
void transferError()
transferError() {{ 
 }}
 Copyright 2014 Pivotal. All rights reserved.
37
Benefits of Testing with Spring
 No need to deploy to an external container to test
application functionality
 Run everything quickly inside your IDE
 Allows reuse of your configuration between test
and production environments
 Application configuration logic is typically reused
 Infrastructure configuration is environment-specific
 DataSources
 JMS Queues
 Copyright 2014 Pivotal. All rights reserved.
38
Summary
 Testing is an essential part of any development
 Unit testing tests a class in isolation
 External dependencies should be minimized
 Consider creating stubs or mocks to unit test
 You dont need Spring to unit test
 Integration testing tests the interaction of multiple units
working together
 Spring provides good integration testing support
 Profiles for different test & deployment configurations
 Copyright 2014 Pivotal. All rights reserved.
39
Lab
Testing Spring Applications
 Copyright 2014 Pivotal. All rights reserved.
40
Developing Aspects
with Spring AOP
Aspect Oriented Programming For
Declarative Enterprise Services
Using and Implementing Spring Proxies
 Copyright 2014 Pivotal. All rights reserved.
Topics in this session
What Problem Does AOP Solve?
Core AOP Concepts
Quick Start
Defining Pointcuts
Implementing Advice
Advanced topics
 Named Pointcuts
 Context selecting pointcuts
 Working with annotations
 Copyright 2014 Pivotal. All rights reserved.
What Problem Does AOP Solve?
 Aspect-Oriented Programming (AOP) enables
modularization of cross-cutting concerns
 Copyright 2014 Pivotal. All rights reserved.
What are Cross-Cutting Concerns?
 Generic functionality that is needed in many places
in your application
 Examples
Logging and Tracing
Transaction Management
Security
Caching
Error Handling
Performance Monitoring
Custom Business Rules
 Copyright 2014 Pivotal. All rights reserved.
An Example Requirement
 Perform a role-based security check before
every application method
A sign this requirement is a cross-cutng concern
 Copyright 2014 Pivotal. All rights reserved.
Implementing Cross Cutting Concerns
Without Modularization
 Failing to modularize cross-cutting concerns leads to two
things
 Code tangling
 A coupling of concerns
 Code scattering
 The same concern spread across modules
 Copyright 2014 Pivotal. All rights reserved.
Symptom #1: Tangling
public class RewardNetworkImpl implements RewardNetwork {
public RewardConfirmation rewardAccountFor(Dining dining) {
if (!hasPermission(SecurityContext.getPrincipal()) {
throw new AccessDeniedException();
Mixing of concerns
}
Account a = accountRepository.findByCreditCard(
Restaurant r = restaurantRepository.findByMerchantNumber(
MonetaryAmount amt = r.calculateBenefitFor(account, dining);
}
}
 Copyright 2014 Pivotal. All rights reserved.
Symptom #2: Scattering
public class JpaAccountManager implements AccountManager {
public Account getAccountForEditing(Long id) {
if (!hasPermission(SecurityContext.getPrincipal()) {
throw new AccessDeniedException();
}
Duplication
public class JpaMerchantReportingService
implements MerchantReportingService {
public List<DiningSummary> findDinings(String merchantNumber,
DateInterval interval) {
if (!hasPermission(SecurityContext.getPrincipal()) {
throw new AccessDeniedException();
}
 Copyright 2014 Pivotal. All rights reserved.
System Evolution Without Modularization
Security
Transactions
Logging
Code
scattering
Code
tangling
BankService
 Copyright 2014 Pivotal. All rights reserved.
CustomerService
ReportingService
Aspect Oriented Programming (AOP)
 Aspect-Oriented Programming (AOP) enables
modularization of cross-cutting concerns
 To avoid tangling
 To eliminate scattering
 Copyright 2014 Pivotal. All rights reserved.
10
How AOP Works
 Implement your mainline application logic
 Focusing on the core problem
 Write aspects to implement your cross-cutting concerns
 Spring provides many aspects out-of-the-box
 Weave the aspects into your application
 Adding the cross-cutting behaviours to the right places
 Copyright 2014 Pivotal. All rights reserved.
11
System Evolution: AOP based
BankService
Security
Aspect
 Copyright 2014 Pivotal. All rights reserved.
CustomerService
Transaction
Aspect
ReportingService
Logging
Aspect
12
Leading AOP Technologies
 AspectJ
 Original AOP technology (first version in 1995)
 Offers a full-blown Aspect Oriented Programming
language
 Uses byte code modification for aspect weaving
 Spring AOP
 Java-based AOP framework with AspectJ integration
 Uses dynamic proxies for aspect weaving
 Focuses on using AOP to solve enterprise problems
 The focus of this session
See: Spring Framework Reference  Aspect Oriented Programming
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#aop
 Copyright 2014 Pivotal. All rights reserved.
13
Topics in this session
What Problem Does AOP Solve?
Core AOP Concepts
Quick Start
Defining Pointcuts
Implementing Advice
Advanced topics
 Named Pointcuts
 Context selecting pointcuts
 Working with annotations
 Copyright 2014 Pivotal. All rights reserved.
14
Core AOP Concepts
 Join Point
 A point in the execution of a program such as a method
call or exception thrown
 Pointcut
 An expression that selects one or more Join Points
 Advice
 Code to be executed at each selected Join Point
 Aspect
 A module that encapsulates pointcuts and advice
 Weaving
 Technique by which aspects are combined with main code
 Copyright 2014 Pivotal. All rights reserved.
15
Topics in this session
What Problem Does AOP Solve?
Core AOP Concepts
Quick Start
Defining Pointcuts
Implementing Advice
Advanced topics
 Named Pointcuts
 Context selecting pointcuts
 Working with annotations
 Copyright 2014 Pivotal. All rights reserved.
16
AOP Quick Start
 Consider this basic requirement
Log a message every time a property is about to change
 How can you use AOP to meet it?
 Copyright 2014 Pivotal. All rights reserved.
17
An Application Object Whose Properties
Could Change
public interface Cache {
public void setCacheSize(int size);
}
 Copyright 2014 Pivotal. All rights reserved.
18
Implement the Aspect
@Aspect
@Component
public class PropertyChangeTracker {
private Logger logger = Logger.getLogger(getClass());
@Before(execution(void set*(*)))
public void trackChange() {
logger.info(Property about to change);
}
}
 Copyright 2014 Pivotal. All rights reserved.
19
Configure Aspect as a Bean
Using Java
Configures Spring
to apply @Aspect
to your beans
@Configuration
@EnableAspectJAutoProxy
@ComponentScan(basePackages=com.example)
public class AspectConfig {
...
}
OR
Using XML
<beans>
<aop:aspectj-autoproxy />
<context:component-scan base-package=com.example />
</beans>
 Copyright 2014 Pivotal. All rights reserved.
20
Include the Aspect Configuration
@Configuration
@Import(AspectConfig.class)
public class MainConfig {
Include aspect
configuration
@Bean
public Cache cacheA() { return new SimpleCache(cacheA); }
@Bean
public Cache cacheB() { return new SimpleCache(cacheB); }
@Bean
public Cache cacheC() { return new SimpleCache(cacheC); }
}
Could also use XML to create SimpleCache beans
 Copyright 2014 Pivotal. All rights reserved.
21
Test the Application
ApplicationContext context = SpringApplication.run(MainConfig.class);
@Autowired @Qualifier(cacheA);
private Cache cache;
cache.setCacheSize(2500);
INFO: Property about to change
 Copyright 2014 Pivotal. All rights reserved.
22
How Aspects are Applied
setCacheSize()
3. All calls routed
through proxy
interceptor
<<interface>>
Cache
2. Proxy implements
target interface(s)
Spring AOP Proxy (this)
setCacheSize(2500)
1. Spring creates a
proxy 'weaving'
aspect & target
 Copyright 2014 Pivotal. All rights reserved.
Method
Interceptor
Target
SimpleCache
Simple
(target)
Cache
PropertyChange
Tracker (aspect)
5. Target method
is executed
4. Matching advice
is executed
23
Tracking Property Changes  With Context
 Context provided by the JoinPoint parameter
@Aspect
public class PropertyChangeTracker {
private Logger logger = Logger.getLogger(getClass());
Context about the intercepted point
@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  +
toString() returns bean-name
point.getTarget());
}
}
INFO: setCacheSize about to change to 2500 on cacheA
 Copyright 2014 Pivotal. All rights reserved.
24
Topics in this session
What Problem Does AOP Solve?
Core AOP Concepts
Quick Start
Defining Pointcuts
Implementing Advice
Advanced topics
 Named Pointcuts
 Context selecting pointcuts
 Working with annotations
 Copyright 2014 Pivotal. All rights reserved.
25
Defining Pointcuts
 Spring AOP uses AspectJs pointcut expression
language
 For selecting where to apply advice
 Complete expression language reference available at
 http://www.eclipse.org/aspectj/docs.php
 Spring AOP supports a practical subset
See: Spring Framework Reference  Declaring a Pointcut
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#aop-pointcuts
 Copyright 2014 Pivotal. All rights reserved.
26
Common Pointcut Designator
 execution(<method pattern>)
 The method must match the pattern
 Can chain together to create composite pointcuts
 && (and), || (or), ! (not)
 Method Pattern
 [Modifiers] ReturnType [ClassType]
MethodName ([Arguments]) [throws ExceptionType]
 Copyright 2014 Pivotal. All rights reserved.
27
Writing Expressions
execution(* rewards.restaurant.*Service.find*(..))
designator
package
return type
 Copyright 2014 Pivotal. All rights reserved.
method
type
params
28
Execution Expression Examples
execution(void send*(String))
 Any method starting with send that takes a single String
parameter and has a void return type
execution(* send(*))
 Any method named send that takes a single parameter
execution(* send(int, ..))
 Any method named send whose first parameter is an int (the
.. signifies 0 or more parameters may follow)
 Copyright 2014 Pivotal. All rights reserved.
29
Execution Expression Examples
execution(void example.MessageServiceImpl.*(..))
Any visible void method in the MessageServiceImpl class
execution(void example.MessageService.send(*))
Any void method named send in any object of type
MessageService (that include possible child classes or
implementors of MessageService)
execution(@javax.annotation.security.RolesAllowed void send*(..))
Any void method starting with send that is annotated
with the @RolesAllowed annotation
 Copyright 2014 Pivotal. All rights reserved.
30
Execution Expression Examples
 Working with Packages
execution(* rewards.*.restaurant.*.*(..))
 There is one directory between rewards and restaurant
execution(* rewards..restaurant.*.*(..))
 There may be several directories between rewards
and restaurant
execution(* *..restaurant.*.*(..))
 Any sub-package called restaurant
 Copyright 2014 Pivotal. All rights reserved.
31
Topics in this session
What Problem Does AOP Solve?
Core AOP Concepts
Quick Start
Defining Pointcuts
Implementing Advice
Advanced topics
 Named Pointcuts
 Context selecting pointcuts
 Working with annotations
 Copyright 2014 Pivotal. All rights reserved.
32
Advice Types: Before
Proxy
Proxy
 Copyright 2014 Pivotal. All rights reserved.
BeforeAdvice
BeforeAdvice
Target
Target
33
Before Advice Example
 Use @Before annotation
 If the advice throws an exception, target will not be called
Track calls to all setter methods
@Aspect
public class PropertyChangeTracker {
private Logger logger = Logger.getLogger(getClass());
@Before(execution(void set*(*)))
public void trackChange() {
logger.info(Property about to change);
}
}
 Copyright 2014 Pivotal. All rights reserved.
34
Advice Types:After Returning
Proxy
Proxy
AfterReturningAdvice
AfterReturningAdvice
Target
Target
Successful return
 Copyright 2014 Pivotal. All rights reserved.
35
After Returning Advice - Example
 Use @AfterReturning annotation with the returning
attribute
Audit all operations in the service package that return a Reward object
@AfterReturning(value=execution(* service..*.*(..)),
returning=reward)
public void audit(JoinPoint jp, Reward reward) {
auditService.logEvent(jp.getSignature() +
 returns the following reward object : + reward.toString() );
}
 Copyright 2014 Pivotal. All rights reserved.
36
Advice Types: After Throwing
Proxy
Proxy
AfterThrowingAdvice
AfterThrowingAdvice
Target
Target
Exception
 Copyright 2014 Pivotal. All rights reserved.
37
After Throwing Advice - Example
 Use @AfterThrowing annotation with the throwing
attribute
Send an email every time a Repository class throws an exception of
type DataAccessException
@AfterThrowing(value=execution(* *..Repository.*(..)), throwing=e)
public void report(JoinPoint jp, DataAccessException e) {
mailService.emailFailure(Exception in repository, jp, e);
}
 Copyright 2014 Pivotal. All rights reserved.
38
After Throwing Advice - Propagation
 The @AfterThrowing advice will not stop the exception
from propagating
 However it can throw a different type of exception
@AfterThrowing(value=execution(* *..Repository.*(..)), throwing=e)
public void report(JoinPoint jp, DataAccessException e) {
mailService.emailFailure(Exception in repository, jp, e);
throw new RewardsException(e);
}
If you wish to stop the exception from propagating any further, you can
use an @Around advice (see later)
 Copyright 2014 Pivotal. All rights reserved.
39
Advice Types: After
Proxy
Proxy
AfterAdvice
AfterAdvice
Target
Target
Successful return or Exception
 Copyright 2014 Pivotal. All rights reserved.
40
After Advice Example
 Use @After annotation
 Called regardless of whether an exception has been
thrown by the target or not
Track calls to all update methods
@Aspect
public class PropertyChangeTracker {
private Logger logger = Logger.getLogger(getClass());
@After(execution(void update*(..)))
public void trackUpdate() {
logger.info(An update has been attempted );
}
}
We don't know how the method terminated
 Copyright 2014 Pivotal. All rights reserved.
41
Advice Types: Around
Proxy
Proxy
AroundAdvice
AroundAdvice
Target
Target
proceed()
 Copyright 2014 Pivotal. All rights reserved.
42
Around Advice Example
 Use @Around annotation
 ProceedingJoinPoint parameter
 Inherits from JoinPoint and adds the proceed() method
Cache values returned by cacheable services
@Around(execution(@example.Cacheable * rewards.service..*.*(..)))
public Object cache(ProceedingJoinPoint point) throws Throwable {
Object value = cacheStore.get(cacheKey(point));
if (value == null) {
Proceed only if not already cached
value = point.proceed();
cacheStore.put(cacheKey(point), value);
}
return value;
}
 Copyright 2014 Pivotal. All rights reserved.
43
Alternative Spring AOP Syntax - XML
 XML Based Alternative to @Annotations
 More centralized configuration
 Approach
 Aspect logic defined Java
 Aspect configuration in XML
 Uses the aop namespace
 Copyright 2014 Pivotal. All rights reserved.
44
Tracking Property Changes - Java Code
public class PropertyChangeTracker {
public void trackChange(JoinPoint point) {
}
}
Aspect is a Plain Java Class with no annotations
 Copyright 2014 Pivotal. All rights reserved.
45
Tracking Property Changes - XML
Configuration
 XML configuration uses the aop namespace
<aop:config>
<aop:aspect ref=propertyChangeTracker>
<aop:before pointcut=execution(void set*(*)) method=trackChange/>
</aop:aspect>
</aop:config>
<bean id=propertyChangeTracker class=example.PropertyChangeTracker />
 Copyright 2014 Pivotal. All rights reserved.
46
Limitations of Spring AOP
 Can only advise non-private methods
 Can only apply aspects to Spring Beans
 Limitations of weaving with proxies
 When using proxies, suppose method a() calls method b()
on the same class/interface
 advice will never be executed for method b()
 Copyright 2014 Pivotal. All rights reserved.
47
Lab
Developing Aspects using Spring AOP
 Copyright 2014 Pivotal. All rights reserved.
48
Topics in this session
What Problem Does AOP Solve?
Core AOP Concepts
Quick Start
Defining Pointcuts
Implementing Advice
Advanced topics
 Named Pointcuts
 Context selecting pointcuts
 Working with annotations
 Copyright 2014 Pivotal. All rights reserved.
49
Named Pointcuts in XML
 A pointcut expression can have a name
 Reuse it in multiple places
<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 />
 Copyright 2014 Pivotal. All rights reserved.
50
Named Pointcut Annotation
@Aspect
public class PropertyChangeTracker {
private Logger logger = Logger.getLogger(getClass());
@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() {}
}
 Copyright 2014 Pivotal. All rights reserved.
The method name becomes the pointcut ID.
The method is not executed.
51
Named Pointcuts
 Expressions can be externalized
public class SystemArchitecture {
@Pointcut(execution(* rewards.service..*Service.*(..)))
public void serviceMethods() {}
}
@Aspect
public class ServiceMethodInvocationMonitor {
private Logger logger = Logger.getLogger(getClass());
@Before( com.acme.SystemArchitecture.serviceMethods() )
public void monitor() {
logger.info(A service method has been accessed);
}
}
 Copyright 2014 Pivotal. All rights reserved.
Fully-qualified pointcut name
52
Named pointcuts - Summary
 Can break one complicated expression into several subexpressions
 Allow pointcut expression reusability
 Best practice: consider externalizing expressions into
one dedicated class
 When working with many pointcuts
 When writing complicated expressions
 Copyright 2014 Pivotal. All rights reserved.
53
Topics in this session
What Problem Does AOP Solve?
Core AOP Concepts
Quick Start
Defining Pointcuts
Implementing Advice
Advanced topics
 Named Pointcuts
 Context selecting pointcuts
 Working with annotations
 Copyright 2014 Pivotal. All rights reserved.
54
Context Selecting Pointcuts
 Pointcuts may also select useful join point context
The currently executing object (proxy)
The target object
Method arguments
Annotations associated with the method, target, or
arguments
 Allows for simple POJO advice methods
 Alternative to working with a JoinPoint object directly
 Copyright 2014 Pivotal. All rights reserved.
55
Context Selecting Example
 Consider this basic requirement
Log a message every time Server is about to start
public interface Server {
public void start(Map input);
public void stop();
}
In the advice, how do we access Server? Map?
 Copyright 2014 Pivotal. All rights reserved.
56
Without Context Selection
 All needed info must be obtained from JoinPoint object
 No type-safety guarantees
 Write advice defensively
@Before(execution(void example.Server.start(java.util.Map)))
public void logServerStartup(JoinPoint jp) {
// A 'safe' implementation would check target type
Server server = (Server) jp.getTarget();
// Don't assume args[0] exists
Object[] args= jp.getArgs();
Map map = args.length > 0 ? (Map) args[0] : new HashMap();
logger.info( server +  starting  params:  + map);
}
 Copyright 2014 Pivotal. All rights reserved.
57
With Context Selection
 Best practice: use context selection
 Method attributes are bound automatically
 Types must match or advice skipped
@Before(execution(void example.Server.start(java.util.Map))
&& target(server) && args(input))
public void logServerStartup(Server server, Map input) {
}
- target(server) selects the target of the execution (your object)
- this(server) would have selected the proxy
 Copyright 2014 Pivotal. All rights reserved.
58
Context Selection - Named Pointcut
@Before(serverStartMethod(server, input))
public void logServerStartup(Server server, Map input) {
} target binds the server starting up
args binds the argument value
@Pointcut(execution(void example.Server.start(java.util.Map))
&& target(server) && args(input))
public void serverStartMethod (Server server, Map input) {}
 Copyright 2014 Pivotal. All rights reserved.
59
Topics in this session
What Problem Does AOP Solve?
Core AOP Concepts
Quick Start
Defining Pointcuts
Implementing Advice
Advanced topics
 Named Pointcuts
 Context selecting pointcuts
 Working with annotations
 Copyright 2014 Pivotal. All rights reserved.
60
Pointcut Expression Examples using
Annotations
 Can match annotations everywhere
 annotated methods, methods with annotated arguments,
returning annotated objects, on annotated classes
 execution(@org..transaction.annotation.Transactional * *(..))
 Any method marked with the @Transactional annotation
 execution( (@example.Sensitive *) *(..))
 Any method that
returns a type
marked as
@Sensitive
 Copyright 2014 Pivotal. All rights reserved.
@Sensitive
public class MedicalRecord {  }
public class MedicalService {
public MedicalRecord lookup(...) {  }
}
61
AOP and annotations - Example
 Use of the annotation() designator
@Around(execution(* *(..)) && @annotation(txn))
public Object execute(ProceedingJoinPoint jp, Transactional txn) {
TransactionStatus tx;
try {
TransactionDefinition defintion = new DefaultTransactionDefinition();
definition.setTimout(txn.timeout());
definition.setReadOnly(txn.readOnly());
...
tx = txnMgr.getTransaction(definition);
return jp.proceed();
No need for @Transactional in
}
execution expression  the
 // commit or rollback
@annotation matches it instead
}
 Copyright 2014 Pivotal. All rights reserved.
62
AOP and Annotations  Named pointcuts
 Same example using a named-pointcut
@Around(transactionalMethod(txn))
public Object execute(ProceedingJoinPoint jp, Transactional txn) {
...
}
@Pointcut(execution(* *(..)) && @annotation(txn))
public void transactionalMethod(Transactional txn) {}
 Copyright 2014 Pivotal. All rights reserved.
63
Summary
 Aspect Oriented Programming (AOP) modularizes
cross-cutting concerns
 An aspect is a module containing cross-cutting
behavior
 Behavior is implemented as advice
 Pointcuts select where advice applies
 Five advice types: Before, AfterThrowing, AfterReturning,
After and Around
 Aspects can be defined using Java with annotations
and/or in XML configuration
 Copyright 2014 Pivotal. All rights reserved.
64
Introduction to Data
Management with
Spring
Implementing Data Access and Caching
Spring's Role in Supporting Data Access in an
Enterprise Application
 Copyright 2014 Pivotal. All rights reserved.
Topics in this Session
The Role of Spring in Enterprise Data Access
The DataAccessExceptionHierarchy
The jdbc Namespace
Implementing Caching
NoSQL databases
 Copyright 2014 Pivotal. All rights reserved.
Spring Resource Management Works Everywhere
Works consistently with leading data access technologies
Jdbc
Repository
JDBC
Hibernate
Repository
Hibernate
Mybatis
Repository
MyBatis
JPA
OpenJPA
DataNucleus
Hibernate
EclipseLink
 Copyright 2014 Pivotal. All rights reserved.
other ...
JPA
Repository
Relational
Database
Java Database
Connectivity (JDBC)
JBoss Hibernate
Java Persistence
API (JPA)
EclipseLink
Data Nucleus
Apache MyBatis
Key Resource Management Features
 Limited resources need to be managed
 Doing it manually risks resource leakage
 Spring does it all for you!
 Declarative transaction management
 Transactional boundaries declared via configuration
 Enforced by a Spring transaction manager
 Automatic connection management
 Connections acquired/released automatically
 No possibility of resource leak
 Intelligent exception handling
 Root cause failures always reported
 Resources always released properly
 Copyright 2014 Pivotal. All rights reserved.
Declarative Transaction Management
public class TransferServiceImpl implements TransferService {
@Transactional // marks method as needing a txn
public void transfer() { // your application logic }
}
Spring Proxy
transfer($50, 1, 2)
Spring
TransactionInterceptor
begin
commit
Transaction
Manager
 Copyright 2014 Pivotal. All rights reserved.
Target
TransferServiceImpl
Transaction
management
behavior is added
around your code
The Resource Management Problem
 To access a data source an application must
 Establish a connection
 To start its work the application must
 Begin a transaction
 When done with its work the application must
 Commit or rollback the transaction
 Close the connection
 Copyright 2014 Pivotal. All rights reserved.
Template Design Pattern
 Widely used and useful pattern
 http://en.wikipedia.org/wiki/Template_method_pattern
 Define the outline or skeleton of an algorithm
 Leave the details to specific implementations later
 Hides away large amounts of boilerplate code
 Spring provides many template classes
 JdbcTemplate
 JmsTemplate, RestTemplate, WebServiceTemplate 
 Most hide low-level resource management
 Copyright 2014 Pivotal. All rights reserved.
Where are my Transactions?
 Every thread needs its own transaction
 Typically: a web-driven request
 Spring transaction management
 Transaction manager handles transaction
 Puts it into thread-local storage
 Data-access code, like JdbcTemplate, finds it
automatically
 Or you can get it yourself:
DataSourceUtils.getConnection(dataSource)
 Hibernate sessions, JTA (Java EE) work similarly
 Copyright 2014 Pivotal. All rights reserved.
Data Access in a Layered Architecture
 Spring enables layered application architecture
 Most enterprise applications consist of three logical
layers
 Service layer (or application layer)
 Exposes high-level application functions
 Use-cases and business logic defined here
 Data access layer
 Defines the interface to the applications data repository
(such as a relational database)
 Infrastructure layer
 Exposes low-level services needed by the other layers
 Copyright 2014 Pivotal. All rights reserved.
Layered Application Architecture
 Classic example of a
Separation of Concerns
Service Layer
 Each layer is abstracted
from the others
 Spring configures it how you
want
Data Access Layer
Infrastructure Layer
 Copyright 2014 Pivotal. All rights reserved.
10
Topics in this Session
The Role of Spring in Enterprise Data Access
The DataAccessExceptionHierarchy
The jdbc Namespace
Implementing Caching
NoSQL databases
 Copyright 2014 Pivotal. All rights reserved.
11
Exception Handling
 Checked Exceptions
 Force developers to handle errors
 But if you can't handle it, must declare it
 Bad: intermediate methods must declare
exception(s) from all methods below
 A form of tight-coupling
 Unchecked Exceptions
 Can be thrown up the call hierarchy to the best place to handle it
 Good: Methods in between don't know about it
 Better in an Enterprise Application
 Spring throws Runtime (unchecked) Exceptions
 Copyright 2014 Pivotal. All rights reserved.
12
Data Access Exceptions
 SQLException
 Too general  one exception for every database error
 Calling class 'knows' you are using JDBC
 Tight coupling
 Would like a hierarchy of exceptions
 Consistent among all Data Access technologies
 Needs to be unchecked
 Not just one exception for everything
 Spring provides DataAccessException hierarchy
 Hides whether you are using JPA, Hibernate, JDBC ...
 Copyright 2014 Pivotal. All rights reserved.
13
Example: BadSqlGrammarException
Select iddd from T_ACCOUNT
Plain JDBC
java.sql.SQLException
Message: Column not found:
IDDD in statement
errorCode: -28
Spring
java.sql.SQLException
Message: Column not found:
IDDD in statement
errorCode: -28
Error code mapping
BadSqlGrammarException
Message: PreparedStatementCallback;
bad SQL grammar  Column not found:
IDDD in statement
For more details on error codes: see spring-jdbc.jar/
org/springframework/jdbc/support/sql-error-codes.xml
 Copyright 2014 Pivotal. All rights reserved.
14
Spring Data Access Exceptions
RuntimeException
DataAccessException
DataAccessResource
FailureException
DataIntegrity
ViolationException
BadSqlGrammar
Exception
CleanupFailure
DataAccessException
OptimisticLocking
FailureException
 Copyright 2014 Pivotal. All rights reserved.
...
15
Topics in this Session
The Role of Spring in Enterprise Data Access
The DataAccessExceptionHierarchy
The jdbc Namespace
Implementing Caching
NoSQL databases
 Copyright 2014 Pivotal. All rights reserved.
16
JDBC Namespace
 Introduced with Spring 3.0
 Especially useful for testing
 Supports H2, HSQL and Derby
<bean class=example.order.JdbcOrderRepository >
<property name=dataSource ref=dataSource />
</bean>
<jdbc:embedded-database id=dataSource type=H2>
<jdbc:script location=classpath:schema.sql />
<jdbc:script location=classpath:test-data.sql />
</jdbc:embedded-database>
 Copyright 2014 Pivotal. All rights reserved.
In memory database
(created at startup)
17
JDBC Namespace
 Allows populating other DataSources, too
<bean id=dataSource class=org.apache.commons.dbcp.BasicDataSource>
<property name=url value=${dataSource.url} />
<property name=username value=${dataSource.username} />
<property name=password value=${dataSource.password} />
</bean>
<jdbc:initialize-database data-source=dataSource>
<jdbc:script location=classpath:schema.sql />
<jdbc:script location=classpath:test-data.sql />
</jdbc:initialize-database>
 Copyright 2014 Pivotal. All rights reserved.
Initializes an
external
database
18
Topics in this Session
The Role of Spring in Enterprise Data Access
The DataAccessExceptionHierarchy
The jdbc Namespace
Implementing Caching
NoSQL databases
 Copyright 2014 Pivotal. All rights reserved.
19
About Caching
 What is a cache?
 In this context: a key-value store = Map
 Where do we use this caching?
 Any method that always returns the same result for the
same argument(s)
 This method could do anything
 Calculate data on the fly
 Execute a database query
 Request data via RMI, JMS, a web-service ...
 A unique key must be generated from the arguments
 That's the cache key
 Copyright 2014 Pivotal. All rights reserved.
20
Spring 3.1
Caching Support
 Available since Spring 3.1
 Transparently applies caching to Spring beans (AOP)
 Define one or more caches in Spring configuration
 Mark methods cacheable
 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
See: Spring Framework Reference  Cache Abstraction
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#cache
 Copyright 2014 Pivotal. All rights reserved.
21
Caching with @Cacheable
 @Cacheable marks a method for caching
 its result is stored in a cache
 subsequent invocations (with the same arguments)
 fetch data from cache using key, method not executed
 @Cacheable attributes
 value: name of cache to use
 key: the key for each cached data-item
 Uses SpEL and argument(s) of method
@Cacheable(value="books", key="#refId.toUpperCase()")
public Book findBook(String refId) {...}
 Copyright 2014 Pivotal. All rights reserved.
22
Caching via Annotations
Use 'books' cache
public class BookService {
Only cache if condition true
@Cacheable(value="books", key="#title" condition="#title.length < 32")
public Book findBook(String title, boolean checkWarehouse);
@Cacheable(value="books", key="#author.name")
public Book findBook2(Author author, boolean checkWarehouse);
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();
...
 Copyright 2014 Pivotal. All rights reserved.
clear cache before method invoked
23
Enabling Caching Proxy
 Caching must be enabled ...
@Configuration
@EnableCaching
public class MyConfig {
@Bean
public BookService bookService() {  }
}
OR
<cache:annotation-driven />
<bean id="bookService" class="example.BookService" />
 Copyright 2014 Pivotal. All rights reserved.
24
Pure XML Cache Setup
 Or use XML instead
 For example with third-party class
<bean id="bookService" class="example.BookService">
<aop:config>
<aop:advisor advice-ref="bookCache"
pointcut="execution(* *..BookService.*(..))"/>
</aop:config>
<cache:advice id="bookCache" cache-manager="cacheManager">
<cache:caching cache="books">
<cache:cacheable method="findBook" key="#refId"/>
<cache:cache-evict method="loadBooks" all-entries="true" key="#refId"/>
</cache:caching>
</cache:advice>
XML Cache Setup  no @Cachable
 Copyright 2014 Pivotal. All rights reserved.
25
Setup Cache Manager
 Must specify a cache-manager
 Some provided, or write your own
 See org.springframework.cache package.
<bean id="cacheManager" class="o.s.cache.support.SimpleCacheManager">
<property name="caches">
<set>
<bean class="o.s.cache.concurrent.ConcurrentMapCacheFactoryBean"
p:name="authors" />
<bean class="o.s.cache.concurrent.ConcurrentMapCacheFactoryBean"
p:name="books" />
</set>
</property>
</bean>
Or use Java Config,
Concurrent Map Cache
but less verbose in XML
 Copyright 2014 Pivotal. All rights reserved.
26
Third-Party Cache Managers
 Two are provided already
<bean id="cacheManager" class="...EhCacheCacheManager"
EHcache
p:cache-manager-ref="ehcache" />
<bean id="ehcache"
class="o.s.cache.ehcache.EhCacheCacheManagerFactoryBean"
p:config-location="ehcache.xml" />
<gfe:cache-manager p:cache-ref="gemfire-cache"/>
<gfe:cache id="gemfire-cache/>
Pivotal Gemfire
Cache
<gfe:replicated-region id="authors p:cache-ref="gemfire-cache"/>
<gfe:partitioned-region id="books p:cache-ref="gemfire-cache"/>
 Copyright 2014 Pivotal. All rights reserved.
27
Spring Gemfire Project
 GemFire configuration in Spring config files
 Also enables configuration injection for environments
 Features
Exception translation
GemfireTemplate
Transaction management (GemfireTransactionManager)
Injection of transient dependencies during deserialization
Gemfire Cache Manager class
 Copyright 2014 Pivotal. All rights reserved.
28
Topics in this Session
The Role of Spring in Enterprise Data Access
The DataAccessExceptionHierarchy
The jdbc Namespace
Implementing Caching
NoSQL databases
 Copyright 2014 Pivotal. All rights reserved.
29
Not Only SQL!
 NoSQL
 Relational databases only store some data
 LDAP, data-warehouses, files
 Most documents and spreadsheets aren't in any database
 Other database products exist
 Have strengths where RDB are weak
 Non-tabular data
 Hierarchical data: parts inventory, org chart
 Network structures: telephone cables, roads, molecules
 Documents: XML, spreadsheets, contracts, ...
 Geographical data: maps, GPS navigation
 Many more ...
 Copyright 2014 Pivotal. All rights reserved.
30
So Many Databases ...
 Many options  each has a particular strength
 Document databases
 MongoDB, CouchDB coming
 Distributed key-value Stores (smart caches)
 Redis, Riak
 Network (graph) database
 Neo4j
 Big Data
 Apache Hadoop (VMware Serengeti)
 Data Grid
 Gemfire
 Column Stores coming: HBase, Cassandra
 Copyright 2014 Pivotal. All rights reserved.
31
Summary
 Data Access with Spring
 Enables layered architecture principles
 Higher layers should not know about data management
below
 Isolate via Data Access Exceptions
 Hierarchy makes them easier to handle
 Provides consistent transaction management
 Supports most leading data-access technologies
 Relational and non-relational (NoSQL)
 A key component of the core Spring libraries
 Automatic caching facility
 Copyright 2014 Pivotal. All rights reserved.
32
Introduction to
Spring JDBC
Using JdbcTemplate
Simplifying JDBC-based data-access with Spring
 Copyright 2014 Pivotal. All rights reserved.
Topics in this Session
 Problems with traditional JDBC
 Results in redundant, error prone code
 Leads to poor exception handling
 Springs JdbcTemplate
Configuration
Query execution
Working with result sets
Exception handling
See: Spring Framework Reference  Data access with JDBC
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#jdbc
 Copyright 2014 Pivotal. All rights reserved.
Redundant, Error Prone Code
 Copyright 2014 Pivotal. All rights reserved.
Redundant, Error Prone Code
public List findByLastName(String lastName) {
List personList = new ArrayList();
Connection conn = null;
String sql = "select first_name, age from PERSON where last_name=?";
try {
DataSource dataSource = DataSourceUtils.getDataSource();
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, lastName);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
personList.add(new Person(rs.getString(first_name), ...));
}
} catch (SQLException e) { /* ??? */ }
finally {
try {
The bold matters - the
conn.close();
rest is boilerplate
} catch (SQLException e) { /* ??? */ }
}
return personList;
}
 Copyright 2014 Pivotal. All rights reserved.
Poor Exception Handling
public List findByLastName(String lastName) {
List personList = new ArrayList();
Connection conn = null;
String sql = "select first_name, age from PERSON where last_name=?";
try {
DataSource dataSource = DataSourceUtils.getDataSource();
conn = dataSource.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, lastName);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
personList.add(new Person(rs.getString("first_name"), ...));
}
} catch (SQLException e) { /* ??? */ }
finally {
What can
try {
conn.close();
you do?
} catch (SQLException e) { /* ??? */ }
}
return personList;
}
 Copyright 2014 Pivotal. All rights reserved.
Topics in this session
 Problems with traditional JDBC
 Results in redundant, error prone code
 Leads to poor exception handling
 Springs JdbcTemplate
Configuration
Query execution
Working with result sets
Exception handling
 Copyright 2014 Pivotal. All rights reserved.
Springs JdbcTemplate
 Greatly simplifies use of the JDBC API
 Eliminates repetitive boilerplate code
 Alleviates common causes of bugs
 Handles SQLExceptions properly
 Without sacrificing power
 Provides full access to the standard JDBC constructs
 Copyright 2014 Pivotal. All rights reserved.
JdbcTemplate in a Nutshell
int count = jdbcTemplate.queryForObject(
SELECT COUNT(*) FROM CUSTOMER, Integer.class);
Acquisition of the connection
Participation in the transaction
Execution of the statement
Processing of the result set
Handling any exceptions
Release of the connection
 Copyright 2014 Pivotal. All rights reserved.
All handled
by Spring
JdbcTemplate Approach Overview
List<Customer> results = jdbcTemplate.query(someSql,
new RowMapper<Customer>() {
public Customer mapRow(ResultSet rs, int row) throws SQLException {
// map the current row to a Customer object
}
class JdbcTemplate {
});
public List<Customer> query(String sql, RowMapper rowMapper) {
try {
// acquire connection
// prepare statement
// execute statement
// for each row in the result set
results.add(rowMapper.mapRow(rs, rowNumber));
return results;
} catch (SQLException e) {
// convert to root cause exception
} finally {
// release connection
}
}
 Copyright 2014 Pivotal. All rights reserved.
Creating a JdbcTemplate
 Requires a DataSource
JdbcTemplate template = new JdbcTemplate(dataSource);
 Create a template once and re-use it
 Do not create one for each thread
 Thread safe after construction
 Copyright 2014 Pivotal. All rights reserved.
10
When to use JdbcTemplate
 Useful standalone
 Anytime JDBC is needed
 In utility or test code
 To clean up messy legacy code
 Useful for implementing a repository in a layered
application
 Also known as a data access object (DAO)
 Copyright 2014 Pivotal. All rights reserved.
11
Implementing a JDBC-based Repository
public class JdbcCustomerRepository implements CustomerRepository {
private JdbcTemplate jdbcTemplate;
public JdbcCustomerRepository(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
public int getCustomerCount() {
String sql = select count(*) from customer;
return jdbcTemplate.queryForObject(sql, Integer.class);
}
}
 Copyright 2014 Pivotal. All rights reserved.
No try / catch needed
(unchecked exception)
12
Querying with JdbcTemplate
 JdbcTemplate can query for
 Simple types (int, long, String, Date, ...)
 Generic Maps
 Domain Objects
 Copyright 2014 Pivotal. All rights reserved.
13
Query for Simple Java Types
 Query with no bind variables: queryForObject
public Date getOldest() {
String sql = select min(dob) from PERSON;
return jdbcTemplate.queryForObject(sql, Date.class);
}
public long getPersonCount() {
String sql = select count(*) from PERSON;
return jdbcTemplate.queryForObject(sql, Long.class);
}
queryForInt, queryForLong deprecated since Spring 3.2, just as easy to
queryForObject instead (API improved in Spring 3)
 Copyright 2014 Pivotal. All rights reserved.
14
Query With Bind Variables
 Can query using bind variables: ?
 Note the use of a variable argument list
private JdbcTemplate jdbcTemplate;
public int getCountOfNationalsOver(Nationality nationality, int age) {
String sql = select count(*) from PERSON  +
where age > ? and nationality = ?;
return jdbcTemplate.queryForObject
(sql, Integer.class, age, nationality.toString());
}
Bind to first ?
 Copyright 2014 Pivotal. All rights reserved.
Bind to second ?
15
Generic Queries
 JdbcTemplate returns each row of a ResultSet as a Map
 When expecting a single row
 Use queryForMap(..)
 When expecting multiple rows
 Use queryForList(..)
 Useful for reporting, testing, and window-on-data use
cases
 The data fetched does not need mapping to a Java object
 Be careful with very large data-sets
 Copyright 2014 Pivotal. All rights reserved.
16
Querying for Generic Maps (1)
 Query for a single row
public Map<String,Object> getPersonInfo(int id) {
String sql = select * from PERSON where id=?;
return jdbcTemplate.queryForMap(sql, id);
}
 returns:
Map { ID=1, FIRST_NAME=John, LAST_NAME=Doe }
A Map of [Column Name | Field Value ] pairs
 Copyright 2014 Pivotal. All rights reserved.
17
Querying for Generic Maps (2)
 Query for multiple rows
public List<Map<String,Object>> getAllPersonInfo() {
String sql = select * from PERSON;
return jdbcTemplate.queryForList(sql);
}
 returns:
List {
0 - Map { ID=1, FIRST_NAME=John, LAST_NAME=Doe }
1 - Map { ID=2, FIRST_NAME=Jane, LAST_NAME=Doe }
2 - Map { ID=3, FIRST_NAME=Junior, LAST_NAME=Doe }
}
A List of Maps of [Column Name | Field Value ] pairs
 Copyright 2014 Pivotal. All rights reserved.
18
Domain Object Queries
 Often it is useful to map relational data into domain
objects
 e.g. a ResultSet to an Account
 Springs JdbcTemplate supports this using a callback
approach
 You may prefer to use ORM for this
 Need to decide between JdbcTemplate queries and JPA
(or similar) mappings
 Some tables may be too hard to map with JPA
 Copyright 2014 Pivotal. All rights reserved.
19
RowMapper
 Spring provides a RowMapper interface for mapping a
single row of a ResultSet to an object
 Can be used for both single and multiple row queries
 Parameterized as of Spring 3.0
public interface RowMapper<T> {
T mapRow(ResultSet rs, int rowNum)
throws SQLException;
}
 Copyright 2014 Pivotal. All rights reserved.
20
Querying for Domain Objects (1)
 Query for single row with JdbcTemplate
public Person getPerson(int id) {
return jdbcTemplate.queryForObject(
select first_name, last_name from PERSON where id=?,
new PersonMapper(), id);
}
No need to cast
Maps rows to Person objects
Parameterizes return type
class PersonMapper implements RowMapper<Person> {
public Person mapRow(ResultSet rs, int rowNum) throws SQLException
{
return new Person(rs.getString("first_name"),
rs.getString("last_name"));
}
}
 Copyright 2014 Pivotal. All rights reserved.
21
Querying for Domain Objects (2)
 Query for multiple rows
No need to cast
public List<Person> getAllPersons() {
return jdbcTemplate.query(
"select first_name, last_name from PERSON",
new PersonMapper());
Same row mapper can be used
class PersonMapper implements RowMapper<Person> {
public Person mapRow(ResultSet rs, int rowNum) throws SQLException {
return new Person(rs.getString("first_name"),
rs.getString("last_name"));
}
}
 Copyright 2014 Pivotal. All rights reserved.
22
Querying for Domain Objects (3)
 Simplify using Java 8 Lambda Expressions
 No need for Mapper class
 Use inline code instead
Replace RowMapper
by lambda
public List<Person> getAllPersons() {
return jdbcTemplate.query(
"select first_name, last_name from PERSON",
(rs, rowNum) -> {
return new Person(rs.getString("first_name"),
rs.getString("last_name"));
});
public interface RowMapper<T> {
public T mapRow(ResultSet rs, int rowNum) throws SQLException;
}
 Copyright 2014 Pivotal. All rights reserved.
23
RowCallbackHandler
 Spring provides a simpler RowCallbackHandler interface
when there is no return object
 Streaming rows to a file
 Converting rows to XML
 Filtering rows before adding to a Collection
 but filtering in SQL is much more efficient
 Faster than JPA equivalent for big queries
 avoids result-set to object mapping
public interface RowCallbackHandler {
void processRow(ResultSet rs) throws SQLException;
}
 Copyright 2014 Pivotal. All rights reserved.
24
Using a RowCallbackHandler (1)
public class JdbcOrderRepository {
public void generateReport(Writer out) {
// select all orders of year 2009 for a full report
jdbcTemplate.query(select * from order where year=?,
new OrderReportWriter(out), 2009);
}
}
returns "void"
class OrderReportWriter implements RowCallbackHandler {
public void processRow(ResultSet rs) throws SQLException {
// parse current row from ResultSet and stream to output
}
/* stateful object: may add convenience methods like getResults(), getCount() etc. */
 Copyright 2014 Pivotal. All rights reserved.
25
Using a RowCallbackHandler (2)
 Or using a Lambda  if no state needed
public class JdbcOrderRepository {
public void generateReport(final Writer out) {
// select all orders of year 2009 for a full report
jdbcTemplate.query(select * from order where year=?,
(rs) -> { out.write( rs.getString(customer)  ); },
2009);
}
}
public interface RowCallbackHandler {
void processRow(ResultSet rs) throws SQLException;
}
 Copyright 2014 Pivotal. All rights reserved.
26
ResultSetExtractor
 Spring provides a ResultSetExtractor interface for
processing an entire ResultSet at once
 You are responsible for iterating the ResultSet
 e.g. for mapping entire ResultSet to a single object
public interface ResultSetExtractor<T> {
T extractData(ResultSet rs) throws SQLException,
DataAccessException;
}
 Copyright 2014 Pivotal. All rights reserved.
27
Using a ResultSetExtractor (1)
public class JdbcOrderRepository {
public Order findByConfirmationNumber(String number) {
// execute an outer join between order and item tables
return jdbcTemplate.query(
select...from order o, item i...conf_id = ?,
new OrderExtractor(), number);
}
class OrderExtractor implements ResultSetExtractor<Order> {
}
public Order extractData(ResultSet rs) throws SQLException {
Order order = null;
while (rs.next()) {
if (order == null) {
order = new Order(rs.getLong("ID"), rs.getString("NAME"), ...);
}
order.addItem(mapItem(rs));
}
return order;
}
}
 Copyright 2014 Pivotal. All rights reserved.
28
Using a ResultSetExtractor (2)
Or using a lambda
public class JdbcOrderRepository {
public Order findByConfirmationNumber(String number) {
// execute an outer join between order and item tables
return jdbcTemplate.query(
select...from order o, item i...conf_id = ?,
(rs) -> {
Order order = null;
while (rs.next()) {
if (order == null)
order = new Order(rs.getLong("ID"), rs.getString("NAME"), ...);
order.addItem(mapItem(rs));
}
return order;
},
number);
}
}
 Copyright 2014 Pivotal. All rights reserved.
public interface ResultSetExtractor<T> {
T extractData(ResultSet rs)
throws SQLException, DataAccessException;
}
29
Summary of Callback Interfaces
 RowMapper
 Best choice when each row of a ResultSet maps to a
domain object
 RowCallbackHandler
 Best choice when no value should be returned from the
callback method for each row
 ResultSetExtractor
 Best choice when multiple rows of a ResultSet map to a
single object
 Copyright 2014 Pivotal. All rights reserved.
30
Inserts and Updates (1)
 Inserting a new row
 Returns number of rows modified
public int insertPerson(Person person) {
return jdbcTemplate.update(
insert into PERSON (first_name, last_name, age) +
values (?, ?, ?),
person.getFirstName(),
person.getLastName(),
person.getAge());
}
 Copyright 2014 Pivotal. All rights reserved.
31
Inserts and Updates (2)
 Updating an existing row
public int updateAge(Person person) {
return jdbcTemplate.update(
update PERSON set age=? where id=?,
person.getAge(),
person.getId());
}
 Copyright 2014 Pivotal. All rights reserved.
32
Exception Handling
 The JdbcTemplate transforms SQLExceptions into
DataAccessExceptions
DataAccessException
CleanupFailure
DataAccessException
DataIntegrity
ViolationException
...
DataAccessException hierarchy was discussed in module Introduction
to Data Access. You can refer to it for more information on this topic.
 Copyright 2014 Pivotal. All rights reserved.
33
Lab
Reimplementing repositories using
Spring's JdbcTemplate
 Copyright 2014 Pivotal. All rights reserved.
34
Transaction
Management with
Spring
Spring's Consistent Approach
Transactional Proxies and @Transactional
 Copyright 2014 Pivotal. All rights reserved.
Topics in this session
Why use Transactions?
Java Transaction Management
Spring Transaction Management
Annotations or XML
Isolation Levels
Transaction Propagation
Rollback rules
Testing
Advanced topics
 Copyright 2014 Pivotal. All rights reserved.
What is a Transaction?
 A set of tasks which take place as a single, atomic,
consistent, isolated, durable operation.
 Copyright 2014 Pivotal. All rights reserved.
Why use Transactions?
To Enforce the ACID Principles:
 Atomic
 Each unit of work is an all-or-nothing operation
 Consistent
 Database integrity constraints are never violated
 Isolated
 Isolating transactions from each other
 Durable
 Committed changes are permanent
 Copyright 2014 Pivotal. All rights reserved.
Transactions in the RewardNetwork
 The rewardAccountFor(Dining) method represents a
unit-of-work that should be atomic
 Copyright 2014 Pivotal. All rights reserved.
RewardNetwork Atomicity
 The rewardAccountFor(Dining) unit-of-work:
Reward
Network
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
 Copyright 2014 Pivotal. All rights reserved.
Nave Approach: Connection per Data
Access Operation
 This unit-of-work contains 4 data access operations
 Each acquires, uses, and releases a distinct Connection
 The unit-of-work is non-transactional
 Copyright 2014 Pivotal. All rights reserved.
Running non-Transactionally
Reward
Network
Account
Repository
Restaurant
Repository
Reward
Repository
DataSource
Connection
findByCreditCard(String)
getConnection()
close()
connection-1
findByMerchantNumber(String)
getConnection()
close()
connection-2
updateBeneficiaries(Account)
1. SELECT
2. SELECT
3. UPDATE
getConnection()
close()
connection-3
4. INSERT
confirmReward(AccountContribution, Dining)
getConnection()
close()
 Copyright 2014 Pivotal. All rights reserved.
connection-4
DATABASE
Partial Failures
 Suppose an Account is being rewarded
X
 If the beneficiaries are updated
 But the reward confirmation fails
 There will be no record of the reward!
 Copyright 2014 Pivotal. All rights reserved.
The unit-of-work
is not atomic
Correct Approach:
Connection per Unit-of-Work
 More efficient
 Same Connection reused for each operation
 Operations complete as an atomic unit
 Either all succeed or all fail
 The unit-of-work can run in a transaction
 Copyright 2014 Pivotal. All rights reserved.
10
Running in a Transaction
TX
Reward
Network
Account
Repository
Restaurant
Repository
Reward
Repository
getConnection()
DataSource
Connection
connection-1
findByCreditCard(String)
1. SELECT
findByMerchantNumber(String)
2. SELECT
updateBeneficiaries(Account)
confirmReward(AccountContribution, Dining)
close()
 Copyright 2014 Pivotal. All rights reserved.
3. UPDATE
4. INSERT
DATABASE
11
Topics in this session
Why use Transactions?
Java Transaction Management
Spring Transaction Management
Annotations or XML
Isolation Levels
Transaction Propagation
Rollback rules
Testing
Advanced topics
 Copyright 2014 Pivotal. All rights reserved.
12
Java Transaction Management
 Java has several APIs which handle transactions
differently
 JDBC, JMS, JTA, Hibernate, JPA, etc.
 Each uses program code to mark the start and end of
the transaction
 Transaction Demarcation
 Different APIs for Global vs Local transactions
 Copyright 2014 Pivotal. All rights reserved.
13
Local and Global Transaction Management
 Local Transactions  Single Resource
 Transactions managed by underlying resource
Your
Application
Database
 Global (distributed) Transactions  Multiple
 Transaction managed by separate, dedicated transaction
manager
Your
Application
 Copyright 2014 Pivotal. All rights reserved.
Transaction
Manager
Oracle
DB
Message
Queue
SQL
Server
14
JDBC Transaction Management Example
try {
conn = dataSource.getConnection();
conn.setAutoCommit(false);
Specific To
JDBC API
conn.commit();
} catch (Exception e) {
conn.rollback();
...
}
Programatic
Transaction
Demarcation
Checked
Exceptions
Code cannot 'join' a transaction already in progress
Code cannot be used with global transaction
 Copyright 2014 Pivotal. All rights reserved.
15
JMS Transaction Management Example
try {
session = connection.createSession ( true, false );
Specific To
JMS API
session.commit();
} catch (Exception e) {
session.rollback();
...
}
Programatic
Transaction
Demarcation
Checked
Exceptions
Code cannot 'join' a transaction already in progress
Code cannot be used with global transaction
 Copyright 2014 Pivotal. All rights reserved.
16
JPA / Hibernate Transaction Management
Example
API
Specific
// Hibernate
Transaction tx =
session.beginTransaction();
tx.commit();
 Copyright 2014 Pivotal. All rights reserved.
Programatic
Transaction
Demarcation
// JPA
Transaction tx =
entityManager.getTransaction()
tx.begin();
tx.commit();
17
Java Transaction API (JTA)
Example
try {
UserTransaction ut =
(UserTransaction) new InitialContext()
.lookup(java:comp/UserTransaction);
ut.begin();
ut.commit();
} catch (Exception e) {
ut.rollback();
...
}
Programatic
Transaction
Demarcation
Checked
Exceptions
Requires a JTA implementation:
 Full application server (WebSphere, WebLogic, JBoss, etc.)
 Standalone implementation (Atomikos, JTOM, etc.)
 Copyright 2014 Pivotal. All rights reserved.
18
Problems with Java Transaction
Management
 Multiple APIs for different local resources
 Programatic transaction demarcation
 Usually located in the repository layer
 Usually repeated (cross-cutting concern)
 Service layer more appropriate
 Multiple data access methods may be called within a
transaction
 Orthogonal concerns
 Transaction demarcation should be independent of
transaction implementation
 Copyright 2014 Pivotal. All rights reserved.
19
Topics in this session
Why use Transactions?
Java Transaction Management
Spring Transaction Management
Annotations or XML
Isolation Levels
Transaction Propagation
Rollback rules
Testing
Advanced topics
 Copyright 2014 Pivotal. All rights reserved.
20
Spring Transaction Management
 Spring separates transaction demarcation from
transaction implementation
 Demarcation expressed declaratively via AOP
 Programatic approach also available
 PlatformTransactionManager abstraction hides
implementation details.
 Several implementations available
 Spring uses the same API for global vs. local.
 Change from local to global is minor.
 Copyright 2014 Pivotal. All rights reserved.
21
Spring Transaction Management
 There are only 2 steps
 Declare a PlatformTransactionManager bean
 Declare the transactional methods
 Using Annotations, XML, Programmatic
 Can mix and match
 Copyright 2014 Pivotal. All rights reserved.
22
PlatformTransactionManager
 Springs PlatformTransactionManager is the base
interface for the abstraction
 Several implementations are available
DataSourceTransactionManager
HibernateTransactionManager
JpaTransactionManager
JtaTransactionManager
WebLogicJtaTransactionManager
WebSphereUowTransactionManager
and more
Spring allows you to configure whether you use JTA or not. It does not
have any impact on your Java classes
 Copyright 2014 Pivotal. All rights reserved.
23
Deploying the Transaction Manager
 Pick the specific implementation
@Bean
public PlatformTransactionManager transactionManager() {
return new DataSourceTransactionManager(dataSource);
}
 XML:
A dataSource
must be defined
elsewhere
<bean id=transactionManager
class=org.springframework.jdbc.datasource.DataSourceTransactionManager>
<property name=dataSource ref=dataSource/>
</bean>
Bean id transactionManager is default name. Can change it but must
specify alternative name everywhere  easier not to!
 Copyright 2014 Pivotal. All rights reserved.
24
Automatic JTA Implementation Resolution
For JTA, also possible to use custom XML tag:
<tx:jta-transaction-manager/>
 Resolves to appropriate impl for environment
OC4JJtaTransactionManager
WebLogicJtaTransactionManager
WebSphereUowTransactionManager
JtaTransactionManager
 Copyright 2014 Pivotal. All rights reserved.
25
@Transactional configuration using Java
Configuration
 In the code:
public class RewardNetworkImpl implements RewardNetwork {
@Transactional
public RewardConfirmation rewardAccountFor(Dining d) {
// atomic unit-of-work
}
}
 In the configuration:
Defines a Bean Post-Processor
 proxies @Transactional beans
@Configuration
@EnableTransactionManagement
public class TxnConfig {
@Bean
public PlatformTransactionManager transactionManager(DataSource ds);
return new DataSourceTransactionManager(ds) {
}
 Copyright 2014 Pivotal. All rights reserved.
26
@Transactional configuration using XML
 In the code:
public class RewardNetworkImpl implements RewardNetwork {
@Transactional
public RewardConfirmation rewardAccountFor(Dining d) {
// atomic unit-of-work
}
}
 In the configuration:
<tx:annotation-driven/>
Defines a Bean Post-Processor
 proxies @Transactional beans
<bean id=transactionManager
class=org.springframework.jdbc.datasource.DataSourceTransactionManager>
<property name=dataSource ref=dataSource/>
</bean>
<jdbc:embedded-database id="dataSource">  </jdbc:embedded-database>
 Copyright 2014 Pivotal. All rights reserved.
27
@Transactional: what happens exactly?
 Target object wrapped in a proxy
 Uses an Around advice
Spring Proxy
Reward
NetworkImpl
 Proxy implements the following behavior
 Transaction started before entering the method
 Commit at the end of the method
 Rollback if method throws a RuntimeException
 Default behavior
 Can be overridden (see later)
 Transaction context bound to current thread.
 All controlled by configuration
 Copyright 2014 Pivotal. All rights reserved.
28
Local JDBC Configuration
Spring Proxy
Reward
NetworkImpl
JdbcAccount
Repository
BasicData
Source
JdbcCustomer
Repository
DataSource
Transaction
Manager
 How?
 Define local data
source
 DataSource
Transaction Manager
 Purpose
 Integration testing
 Deploy to Tomcat or
other servlet container
<bean id="transactionManager"
class="...DataSourceTransactionManager"> ...
<jdbc:embedded-database id="dataSource"> ...
 Copyright 2014 Pivotal. All rights reserved.
29
JDBC Java EE Configuration
No code changes
Just configuration
Spring Proxy
Reward
NetworkImpl
JdbcAccount
Repository
JdbcCustomer
Repository
 How?
 Use container-managed
datasource (JNDI)
 JTA Transaction
Manager
 Purpose
JEE Container
Managed
DataSource
JTA
Transaction
Manager
 Deploy to JEE container
<tx:jta-transaction-manager/>
<jee:jndi-lookup id=dataSource ... />
 Copyright 2014 Pivotal. All rights reserved.
30
Topics in this session
Why use Transactions?
Java Transaction Management
Spring Transaction Management
Annotations or XML
Isolation Levels
Transaction Propagation
Rollback rules
Testing
Advanced topics
 Copyright 2014 Pivotal. All rights reserved.
31
@Transactional  Class Level
 Applies to all methods declared by the interface(s)
@Transactional
public class RewardNetworkImpl implements RewardNetwork {
public RewardConfirmation rewardAccountFor(Dining d) {
// atomic unit-of-work
}
public RewardConfirmation updateConfirmation(RewardConfirmantion rc) {
// atomic unit-of-work
}
}
@Transactional can also be declared at the interface/parent class level
 Copyright 2014 Pivotal. All rights reserved.
32
@Transactional
 Class and method levels
 Combining class and method levels
default settings
@Transactional(timeout=60)
public class RewardNetworkImpl implements RewardNetwork {
public RewardConfirmation rewardAccountFor(Dining d) {
// atomic unit-of-work
overriding attributes at
}
the method level
@Transactional(timeout=45)
public RewardConfirmation updateConfirmation(RewardConfirmantion rc) {
// atomic unit-of-work
}
}
 Copyright 2014 Pivotal. All rights reserved.
33
XML-based Spring Transactions
 Cannot always use @Transactional
 Annotations require JDK 5
 Someone else may have written the service (without
annotations)
 Spring also provides an option for XML
 An AOP pointcut declares what to advise
 Springs tx namespace enables a concise definition of
transactional advice
 Can add transactional behavior to any class used as a
Spring Bean
 Copyright 2014 Pivotal. All rights reserved.
34
Declarative Transactions: XML
AspectJ named pointcut expression
<aop:config>
<aop:pointcut id=rewardNetworkMethods
expression=execution(* rewards.RewardNetwork.*(..))/>
<aop:advisor pointcut-ref=rewardNetworkMethods advice-ref=txAdvice/>
</aop:config>
Method-level configuration
for transactional advice
<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>
 Copyright 2014 Pivotal. All rights reserved.
35
Topics in this session
Why use Transactions?
Java Transaction Management
Spring Transaction Management
Annotations or XML
Isolation Levels
Transaction Propagation
Rollback rules
Testing
Advanced topics
 Copyright 2014 Pivotal. All rights reserved.
36
Isolation levels
 4 isolation levels can be used:
READ_UNCOMMITTED
READ_COMMITTED
REPEATABLE_READ
SERIALIZABLE
 Some DBMSs do not support all isolation levels
 Isolation is a complicated subject
 DBMS all have differences in the way their isolation
policies have been implemented
 We just provide general guidelines
 Copyright 2014 Pivotal. All rights reserved.
37
Dirty Reads
Transactions
should be
isolated 
unable to see
the results of
another
uncommitted
unit-of-work
 Copyright 2014 Pivotal. All rights reserved.
rollback X
38
READ_UNCOMMITTED
 Lowest isolation level
 Allows dirty reads
 Current transaction can see the results of another
uncommitted unit-of-work
public class RewardNetworkImpl implements RewardNetwork {
@Transactional (isolation=Isolation.READ_UNCOMMITTED)
public RewardConfirmation rewardAccountFor(Dining dining)
// atomic unit-of-work
}
}
 Copyright 2014 Pivotal. All rights reserved.
39
READ_COMMITTED
 Does not allow dirty reads
 Only committed information can be accessed
 Default strategy for most databases
public class RewardNetworkImpl implements RewardNetwork {
@Transactional (isolation=Isolation.READ_COMMITTED)
public RewardConfirmation rewardAccountFor(Dining dining)
// atomic unit-of-work
}
}
 Copyright 2014 Pivotal. All rights reserved.
40
Highest isolation levels
 REPEATABLE_READ
 Does not allow dirty reads
 Non-repeatable reads are prevented
 If a row is read twice in the same transaction, result will
always be the same
 Might result in locking depending on the DBMS
 SERIALIZABLE
 Prevents non-repeatable reads and dirty-reads
 Also prevents phantom reads
 Copyright 2014 Pivotal. All rights reserved.
41
Topics in this session
Why use Transactions?
Java Transaction Management
Spring Transaction Management
Annotations or XML
Isolation Levels
Transaction Propagation
Rollback rules
Testing
Advanced topics
 Copyright 2014 Pivotal. All rights reserved.
42
Understanding Transaction Propagation
 Consider the sample below. What should happen if
ClientServiceImpl calls AccountServiceImpl?
 Should everything run into a single transaction?
 Should each service have its own transaction?
public class ClientServiceImpl
implements ClientService {
@Autowired
private AccountService accountService;
@Transactional
public void updateClient(Client c)
{ // 
this.accountService.update(c.getAccounts());
}
}
 Copyright 2014 Pivotal. All rights reserved.
public class AccountServiceImpl
implements AccountService
{
@Transactional
public void update(List <Account> l)
{ //  }
}
43
Understanding Transaction Propagation
A
B
Single Transaction
Transaction 1
Transaction 2
Caller
Transaction created,
committed or rolled
back as needed
Transactional method 1
Transactional method 2
Is there an existing transaction? Should
method 2 execute in that transaction (A)
or should a new transaction be created (B),
with outer transaction suspended?
Behavior driven by metadata for the method
 Copyright 2014 Pivotal. All rights reserved.
44
Transaction Propagation with Spring
 7 levels of propagation
 The following examples show REQUIRED and
REQUIRES_NEW
 Check the documentation for other levels
 Can be used as follows:
@Transactional( propagation=Propagation.REQUIRES_NEW )
 Copyright 2014 Pivotal. All rights reserved.
45
REQUIRED
 REQUIRED
 Default value
 Execute within a current transaction, create a new one if
none exists
tx1
no tx
tx1
tx1
@Transactional(propagation=Propagation.REQUIRED)
 Copyright 2014 Pivotal. All rights reserved.
46
REQUIRES_NEW
 REQUIRES_NEW
 Create a new transaction, suspending the current
transaction if one exists
no tx
tx1
tx1
tx2
@Transactional(propagation=Propagation.REQUIRES_NEW)
 Copyright 2014 Pivotal. All rights reserved.
47
Topics in this session
Why use Transactions?
Java Transaction Management
Spring Transaction Management
Annotations or XML
Isolation Levels
Transaction Propagation
Rollback rules
Testing
Advanced topics
 Copyright 2014 Pivotal. All rights reserved.
48
Default behavior
 By default, a transaction is rolled back if a
RuntimeException has been thrown
 Could be any kind of RuntimeException:
DataAccessException, HibernateException etc.
public class RewardNetworkImpl implements RewardNetwork {
@Transactional
public RewardConfirmation rewardAccountFor(Dining d) {
// ...
throw new RuntimeException();
}
Triggers a rollback
 Copyright 2014 Pivotal. All rights reserved.
49
rollbackFor and noRollbackFor
 Default settings can be overridden with rollbackFor and
noRollbackFor attributes
public class RewardNetworkImpl implements RewardNetwork {
@Transactional(rollbackFor=MyCheckedException.class)
public void updateConfirmation(Confirmation c) throws MyCheckedException {
// ...
}
@Transactional(noRollbackFor={JmxException.class, MailException.class})
public RewardConfirmation rewardAccountFor(Dining d) {
// ...
}
}
 Copyright 2014 Pivotal. All rights reserved.
50
Topics in this session
Why use Transactions?
Java Transaction Management
Spring Transaction Management
Annotations or XML
Isolation Levels
Transaction Propagation
Rollback rules
Testing
Advanced topics
 Copyright 2014 Pivotal. All rights reserved.
51
@Transactional within Integration Test
 Annotate test method (or class) with @Transactional
 Runs test methods in a transaction
 Transaction will be rolled back afterwards
 No need to clean up your database after testing!
@ContextConfiguration(classes=RewardsConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class RewardNetworkTest {
Test now
@Test @Transactional
public void testRewardAccountFor() {
...
}
transactional
 Copyright 2014 Pivotal. All rights reserved.
52
Advanced use of @Transactional within
Integration Test
@ContextConfiguration(locations={"/rewards-config.xml"})
@RunWith(SpringJUnit4ClassRunner.class)
@TransactionConfiguration(defaultRollback=false, transactionManager="txMgr")
@Transactional
Transactions do a commit at the
end by default
public class RewardNetworkTest {
Overrides default rollback settings
@Test
@Rollback(true)
public void testRewardAccountFor() {
...
}
}
Inside @TransactionConfiguration, no need to specify the
transactionManager attribute if the bean id is transactionManager
 Copyright 2014 Pivotal. All rights reserved.
53
@Before vs @BeforeTransaction
@ContextConfiguration(locations={"/rewards-config.xml"})
 @Before runs in the transaction
@RunWith(SpringJUnit4ClassRunner.class)
public
class RewardNetworkTestruns
{
 @BeforeTransaction
before the transaction starts
Run before transaction is started
@BeforeTransaction
public void verifyInitialDatabaseState() {}
Within the transaction
@Before
public void setUpTestDataInTransaction() {}
@Test @Transactional
public void testRewardAccountFor() {
...
}
@After and @AfterTransaction work in the same way as
@Before and @BeforeTransaction
 Copyright 2014 Pivotal. All rights reserved.
54
Lab
Managing Transactions Declaratively
using Spring Annotations
 Copyright 2014 Pivotal. All rights reserved.
55
Topics in this session
 Advanced topics
Programmatic transactions
Read-only transactions
Multiple transaction managers
Global transactions
Available Propagation Options
 Copyright 2014 Pivotal. All rights reserved.
56
Programmatic Transactions with Spring
 Declarative transaction management is highly
recommended
 Clean code
 Flexible configuration
 Spring does enable programmatic transaction
 Works with local or JTA transaction manager
 TransactionTemplate plus callback
Can be useful inside a technical framework that would not rely on
external configuration
 Copyright 2014 Pivotal. All rights reserved.
57
Programmatic Transactions: example
Method not
@Transactional
public RewardConfirmation rewardAccountFor(Dining dining) {
...
return new TransactionTemplate(txManager).execute( (status) -> {
try {
...
Lambda syntax
accountRepository.updateBeneficiaries(account);
confirmation = rewardRepository.confirmReward(contribution, dining);
}
Method no longer throws
catch (RewardException e) {
exception
status.setRollbackOnly();
 manual rollback
confirmation = new RewardFailure();
}
return confirmation;
}
public interface TransactionCallback<T> {
);
public T doInTransaction(TransactionStatus status)
}
}
 Copyright 2014 Pivotal. All rights reserved.
throws Exception;
58
Read-only transactions (1)
 Why use transactions if you're only planning to read
data?
 Performance: allows Spring to optimize the transactional
resource for read-only data access
public void rewardAccount1() {
jdbcTemplate.queryForList();
jdbcTemplate.queryForInt();
}
@Transactional(readOnly=true)
public void rewardAccount2() {
jdbcTemplate.queryForList();
jdbcTemplate.queryForInt();
}
 Copyright 2014 Pivotal. All rights reserved.
2 connections
1 single connection
59
Read-only transactions (2)
 Why use transactions if you're only planning to read
data?
 Isolation: with a high isolation level, a readOnly transaction
prevents data from being modified until the transaction
commits
@Transactional(readOnly=true,
isolation=Isolation.READ_COMMITTED)
public void rewardAccount2() {
jdbcTemplate.queryForList();
jdbcTemplate.queryForInt();
}
 Copyright 2014 Pivotal. All rights reserved.
60
Multiple Transaction Managers
 @Transactional can declare the id of the transaction
manager that should be used
@Transactional("myOtherTransactionManager")
public void rewardAccount1() {
Uses the bean with id
jdbcTemplate.queryForList();
"myOtherTransactionManager
jdbcTemplate.queryForInt();
"
}
Uses "transactionManager"
@Transactional
bean by default
public void rewardAccount2() {
jdbcTemplate.queryForList();
jdbcTemplate.queryForInt();
}
Important: Separate transaction managers = separate transactions!
 Copyright 2014 Pivotal. All rights reserved.
61
Global Transactions
 Also called distributed transactions
 Involve multiple dissimilar resources:
Your
Application
Transaction
Manager
Oracle
DB
Message
Queue
SQL
Server
 Global transactions typically require JTA and specific
drivers (XA drivers)
 Copyright 2014 Pivotal. All rights reserved.
62
Global transactions  Spring Integration
 Many possible strategies
 Spring allows you to switch easily from a non-JTA to a JTA
transaction policy
 Just change the type of the transaction manager
 Reference:
 Distributed transactions with Spring, with and without XA
by Dr. Dave Syer
 http://www.javaworld.com/javaworld/jw-01-2009/jw-01spring-transactions.html
 Copyright 2014 Pivotal. All rights reserved.
63
Propagation Levels and their Behaviors
Propagation Type
If NO current
transaction
If there is a current transaction
MANDATORY
throw exception
use current transaction
NEVER
don't create a transaction, throw exception
run method outside any
transaction
NOT_SUPPORTED
don't create a transaction, suspend current transaction, run
run method outside any
method outside any transaction
transaction
SUPPORTS
don't create a transaction, use current transaction
run method outside any
transaction
REQUIRED(default)
create a new transaction
use current transaction
REQUIRES_NEW
create a new transaction
suspend current transaction,
create a new independent
transaction
NESTED
create a new transaction
create a new nested transaction
 Copyright 2014 Pivotal. All rights reserved.
64
JPA with Spring
and Spring Data
Object Relational Mapping with
Spring & Java Persistence API
Using JPA with Spring, Spring Data Repositories
 Copyright 2014 Pivotal. All rights reserved.
Topics in this session
 Introduction to JPA
 General Concepts
 Mapping
 Querying
Configuring JPA in Spring
Implementing JPA DAOs
Spring Data  JPA
Lab
Optional Topics
 Copyright 2014 Pivotal. All rights reserved.
Introduction to JPA
 The Java Persistence API is designed for operating on
domain objects
 Defined as POJO entities
 No special interface required
 Replaces previous persistence mechanisms
 EJB Entity Beans
 Java Data Objects (JDO)
 A common API for object-relational mapping
 Derived from the experience of existing products such as
JBoss Hibernate and Oracle TopLink
 Copyright 2014 Pivotal. All rights reserved.
About JPA
 Java Persistence API
 Released May 2006
 Version 2 since Dec 2009
 Removes many of the limitations of JPA 1
 Less need for ORM specific annotations and extensions
 JPA 2.1 May 2013
 Convertors, bulk updates, stored procedures, listeners
 DDL generation, partial entity loading, extra query syntax
 Key Concepts
 Entity Manager
 Entity Manager Factory
 Persistence Context
 Copyright 2014 Pivotal. All rights reserved.
JPA General Concepts (1)
 EntityManager
 Manages a unit of work and persistent objects therein: the
PersistenceContext
 Lifecycle often bound to a Transaction (usually containermanaged)
 EntityManagerFactory
 thread-safe, shareable object that represents a single data
source / persistence unit
 Provides access to new application-managed
EntityManagers
 Copyright 2014 Pivotal. All rights reserved.
JPA General Concepts (2)
 Persistence Unit
Describes a group of persistent classes (entities)
Defines provider(s)
Defines transactional types (local vs JTA)
Multiple Units per application are allowed
 In a Spring JPA application
 The configuration can be in the
Persistence Unit
 Or in the Spring bean-file
 Or a combination of the two
 Copyright 2014 Pivotal. All rights reserved.
Persistence Context and EntityManager
Entity
Manager
creates
Factory
 Copyright 2014 Pivotal. All rights reserved.
The EntityManager API
persist(Object o)
Adds the entity to the Persistence
Context:
SQL: insert into table 
remove(Object o)
Removes the entity from the Persistence
Context:
SQL: delete from table 
find(Class entity, Object primaryKey)
Find by primary key:
SQL: select * from table where id = ?
Query createQuery(String jpqlString)
Create a JPQL query
flush()
Force changed entity state to be written
to database immediately
Plus other methods ...
 Copyright 2014 Pivotal. All rights reserved.
JPA Providers
 Several major implementations of JPA spec
 Hibernate EntityManager
 Used inside Jboss
 EclipseLink (RI)
 Used inside Glassfish
 Apache OpenJPA
 Used by Oracle WebLogic and IBM Websphere
 Data Nucleus
 Used by Google App Engine
 Can all be used without application server as well
 Independent part of EJB 3 spec
 Copyright 2014 Pivotal. All rights reserved.
Hibernate JPA
 Hibernate adds JPA support through an additional library
 The Hibernate EntityManager
 Hibernate sessions used behind JPA interfaces
 Custom annotations for Hibernate specific extensions not
covered by JPA
 less important since JPA
version 2
JPA
API
Hibernate
Implementation
 Copyright 2014 Pivotal. All rights reserved.
10
JPA Mapping
 JPA requires metadata for mapping classes/fields to
database tables/columns
 Usually provided as annotations
 XML mappings also supported (orm.xml)
 Intended for overrides only  not shown here
 JPA metadata relies on defaults
 No need to provide metadata for the obvious
 Copyright 2014 Pivotal. All rights reserved.
11
What can you Annotate?
 Classes
 Applies to the entire class (such as table properties)
 Fields
 Typically mapped to a column
 By default, all treated as persistent
 Mappings will be defaulted
 Unless annotated with @Transient (non-persistent)
 Accessed directly via Reflection
Properties (getters)
 Also mapped to a column
 Annotate getters instead of fields
 Copyright 2014 Pivotal. All rights reserved.
12
Mapping using fields (Data-Members)
@Entity
@Entity
@Table(name=
@Table(name= T_CUSTOMER)
T_CUSTOMER)
public
public class
class Customer
Customer {{
@Id
@Id
@Column(name=cust_id)
@Column(name=cust_id)
private
private Long
Long id;
id;
@Column(name=first_name)
@Column(name=first_name)
private
private String
String firstName;
firstName;
@Transient
@Transient
private
private User
User currentUser;
currentUser;
...
...
Only @Entity and @Id are mandatory
 Copyright 2014 Pivotal. All rights reserved.
Mark as an entity
Optionally override
table name
Mark id-field
(primary key)
Optionally override
column names
Not stored in database
Data members set directly
- using reflection
- field access
- no setters needed
13
Mapping using accessors (Properties)
Must place @Id on the
getter method
@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 Long
Long getId()
getId()
{{ return
return this.id;
this.id; }}
Other annotations now also
placed on getter methods
@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; }}
}}
 Copyright 2014 Pivotal. All rights reserved.
14
Relationships
 Common relationship mappings supported
 Single entities and entity collections both supported
 Associations can be uni- or bi-directional
@Entity
@Table(name= T_CUSTOMER)
public class Customer {
@Id
@Column (name=cust_id)
private Long id;
@OneToMany
@JoinColumn (name=cid)
private Set<Address> addresses;
 Copyright 2014 Pivotal. All rights reserved.
@Entity
@Table(name= T_ADDRESS)
public class Address {
@Id private Long id;
private String street;
private String suburb;
private String city;
private String postcode;
private String country;
}
Foreign key in
Address table
15
Embeddables
 Map a table row to multiple classes
 Address fields also columns in T_CUSTOMER
 @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;
 Copyright 2014 Pivotal. All rights reserved.
Maps to ZIP
column in
T_CUSTOMER
16
JPA Querying
 JPA provides several options for accessing data
 Retrieve an object by primary key
 Query for objects using JPA Query Language (JPQL)
 Similar to SQL and HQL
 Query for objects using Criteria Queries (appendix)
 API for creating ad hoc queries
 Only in JPA 2
 Execute SQL directly to underlying database (appendix)
 Native queries, allow DBMS-specific SQL to be used
 Consider JdbcTemplate instead when not using managed
objects  more options/control, more efficient
 Copyright 2014 Pivotal. All rights reserved.
17
JPA Querying: By Primary Key
 To retrieve an object by its database identifier simply call
find() on the EntityManager
Long customerId = 123L;
Customer customer = entityManager.find(Customer.class, customerId);
returns null if no object exists for the
identifier
No cast required  JPA uses
generics
 Copyright 2014 Pivotal. All rights reserved.
18
JPA Querying: JPQL
- SELECT clause required
- can't use *
 Query for objects based on properties or associations ...
// Query with named parameters
TypedQuery<Customer> query = entityManager.createQuery(
select c from Customer c where c.address.city = :city, Customer.class);
query.setParameter(city, Chicago);
List<Customer> customers = query.getResultList();
Specify Class to
Populate / return
//  or using a single statement
List<Customer> customers2 = entityManager.
createQuery(select c from Customer c ..., Customer.class).
setParameter(city, Chicago).getResultList();
//  or if expecting a single result
Customer customer = query.getSingleResult(); Can also use bind ? Variables
 indexed from 1 like JDBC
 Copyright 2014 Pivotal. All rights reserved.
19
Topics in this session
 Introduction to JPA
 General Concepts
 Mapping
 Querying
Configuring JPA in Spring
Implementing JPA DAOs
Spring Data  JPA
Lab
Optional Topics
 Copyright 2014 Pivotal. All rights reserved.
20
Quick Start  Spring JPA Configuration
Steps to using JPA with Spring
1.
2.
3.
4.
5.
Define an EntityManagerFactory bean.
Define a DataSource bean
Define a Transaction Manager bean
Define Mapping Metadata (already covered)
Define DAOs
Note: There are many configuration options for EntityManagerFactory,
persistence.xml, and DataSource. See the optional section for details.
 Copyright 2014 Pivotal. All rights reserved.
21
Define the EntityManagerFactory
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
adapter.setShowSql(true);
adapter.setGenerateDdl(true);
adapter.setDatabase(Database.HSQL);
Properties props = new Properties();
props.setProperty("hibernate.format_sql", "true");
LocalContainerEntityManagerFactoryBean emfb =
new LocalContainerEntityManagerFactoryBean();
emfb.setDataSource(dataSource);
emfb.setPackagesToScan("rewards.internal");
emfb.setJpaProperties(props);
NOTE: no persistence.xml
emfb.setJpaVendorAdapter(adapter);
return emfb;
needed when using
packagesToScan property
 Copyright 2014 Pivotal. All rights reserved.
22
Configuration  XML Equivalent
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="rewards.internal"/>
<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>
</property>
<property name="jpaProperties">
<props> <prop key="hibernate.format_sql">true</prop> </props>
</property>
</bean>
 Copyright 2014 Pivotal. All rights reserved.
23
Define DataSource & Transaction Manager
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean emfb =
new LocalContainerEntityManagerFactoryBean();
emfb.setDataSource(dataSource());
...
Method returns a FactoryBean...
return emfb;
}
...Spring calls getObject() on the FactoryBean
to obtain the EntityManagerFactory:
@Bean
public PlatformTransactionManager
transactionManager(EntityManagerFactory emf) {
return new JpaTransactionManager(emf);
}
@Bean
public DataSource dataSource() { // Lookup via JNDI or create locally. }
 Copyright 2014 Pivotal. All rights reserved.
24
EntityManagerFactoryBean Configuration
OrderServiceImpl
DataSource
LocalContainer
EntityManager
FactoryBean
creates
Entity
Manager
Factory
creates
JPA
OrderRepository
EntityManager
Spring Proxy
Proxy automatically finds entitymanager for current transaction
 Copyright 2014 Pivotal. All rights reserved.
25
Topics in this session
 Introduction to JPA
 General Concepts
 Mapping
 Querying
Configuring JPA in Spring
Implementing JPA DAOs
Spring Data  JPA
Lab
Optional Topics
 Copyright 2014 Pivotal. All rights reserved.
26
Implementing JPA DAOs
 JPA provides configuration options so Spring can
manage transactions and the EntityManager
 There are no Spring dependencies in your DAO
implementations
 Optional: Use AOP for transparent exception translation
 Rethrows JPA PersistenceExceptions as Spring's
DataAccessExceptions
 See Advanced Topics at end of section
 Copyright 2014 Pivotal. All rights reserved.
27
Spring-Managed Transactions &
EntityManager (1)
 To transparently participate in Spring-driven transactions
 Use a Spring FactoryBean for building the
EntityManagerFactory
 Inject an EntityManager reference with
@PersistenceContext
 Define a transaction manager
 JpaTransactionManager
 JtaTransactionManager
 Copyright 2014 Pivotal. All rights reserved.
28
Spring-Managed Transactions &
EntityManager (2)
 The code  no Spring dependencies
public class JpaOrderRepository implements OrderRepository {
private EntityManager entityManager;
Automatic injection of EM Proxy
@PersistenceContext
public void setEntityManager (EntityManager entityManager) {
this. entityManager = entityManager;
}
public Order findById(long orderId) {
return entityManager.find(Order.class, orderId);
}
Proxy resolves to EM when used
 Copyright 2014 Pivotal. All rights reserved.
29
Spring-managed Transactions and
EntityManager (3)
 The Configuration
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
...
}
@Bean
public OrderRepository jpaOrderRepository() {
return new JpaOrderRepository();
}
Automatic injection of
entity-manager proxy
@Bean
public PlatformTransactionManager
transactionManager(EntityManagerFactory emf) throws Exception {
return new JpaTransactionManager(emf);
}
 Copyright 2014 Pivotal. All rights reserved.
30
How it Works (JPA)
Spring AOP Proxy
invoke(input)
Service
proxy handles
transaction
create entity
manager
EntityManager
Factory
 Copyright 2014 Pivotal. All rights reserved.
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
Entity Manager Proxy
get EM
31
How it Works (JTA)
invoke(input)
Spring
Hibernate
TransactionInterceptor
OrderRepository
Service
proxy handles
transaction begin
OrderServiceImpl
Spring AOP Proxy
commit
get order
data
JtaTransaction
Manager
begin
txn
JTA
 Copyright 2014 Pivotal. All rights reserved.
commit
txn
join
txn
Proxy gets EM
for current txn
OrderRepository
Entity Manager Proxy
find
order
get EM
Entity
Manager
(EM)
create
EntityManager
Factory
32
Topics in this session
 Introduction to JPA
 General Concepts
 Mapping
 Querying
Configuring JPA in Spring
Implementing JPA DAOs
Spring Data  JPA
Lab
Optional Topics
 Copyright 2014 Pivotal. All rights reserved.
33
What is Spring Data?
 Reduces boiler plate code for data access
 Works in many environments
Spring Data
JPA
 Copyright 2014 Pivotal. All rights reserved.
Pivotal
Gemfire
Core project
MongoDB
Apache
Hadoop
Solr
JDBC
extensions
Neo4j
Redis
And more ...
Sub-projects
34
Instant Repositories
 How?
 Annotate domain class
 define keys & enable persistence
 Define your repository as an interface
 Spring will implement it at run-time
 Scans for interfaces extending Spring's
Repository<T, K>
 CRUD methods auto-generated
 Paging, custom queries and sorting supported
 Variations exist for most Spring Data sub-projects
 Copyright 2014 Pivotal. All rights reserved.
35
Domain Objects: Using JPA
 Annotate JPA Domain object as normal
 Nothing to see here!
@Entity
@Table(...)
public class Customer {
Domain Class
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
Key is a Long
private Date firstOrderDate;
private String email;
// Other data-members and getters and setters omitted
}
 Copyright 2014 Pivotal. All rights reserved.
36
Domain Objects: Other Data Stores
 Spring Data provides similar annotations to JPA
 @Document, @Region, @NodeEntity ...
 Templates (like JdbcTemplate) for basic CRUD access
 MongoTemplate, GemfireTemplate, RedisTemplate ...
MongoDB  map to
a JSON document
@Document
public class Account {
...
 Copyright 2014 Pivotal. All rights reserved.
@NodeEntity
public class Account {
@GraphId
Long id;
...
Neo4J  map
to a graph
Gemfire  map
to a region
@Region
public class Account {
...
37
Extend Predefined Repository Interfaces
public interface Repository<Customer, Long> { }
public interface CrudRepository<T, ID
extends Serializable> extends Repository<T, ID> {
Marker interface  add
any methods from
CrudRepository or add
custom finders
public <S extends T> save(S entity);
public <S extends T> Iterable<S> save(Iterable<S> entities);
public T findOne(ID id);
public Iterable<T> findAll();
public void delete(ID id);
public void delete(T entity);
public void deleteAll();
}
 Copyright 2014 Pivotal. All rights reserved.
You get all these
methods automatically
PagingAndSortingRepository<T, K>
- adds Iterable<T> findAll(Sort)
- adds Page<T> findAll(Pageable)
38
Generating Repositories
 Spring scans for Repository interfaces
 Implements them and creates as a Spring bean
 XML
<jpa:repositories base-package="com.acme.**.repository" />
<mongo:repositories base-package="com.acme.**.repository" />
<gfe:repositories base-package="com.acme.**.repository" />
 Java Configuration
@Configuration
@EnableJpaRespositories(basePackages=com.acme.**.repository")
@EnableMongoRepositories(...)
public class MyConfig { ... }
 Copyright 2014 Pivotal. All rights reserved.
39
Defining a JPA Repository
 Auto-generated finders obey naming convention
 findBy<DataMember><Op>
 <Op> can be Gt, Lt, Ne, Between, Like  etc
public interface CustomerRepository
extends CrudRepository<Customer, Long> {
id
public Customer findByEmail(String someEmail); // No <Op> for Equals
public Customer findByFirstOrderDateGt(Date someDate);
public Customer findByFirstOrderDateBetween(Date d1, Date d2);
@Query(SELECT c FROM Customer c WHERE c.email NOT LIKE '%@%')
public List<Customer> findInvalidEmails();
}
 Copyright 2014 Pivotal. All rights reserved.
Custom query uses query-language of
underlying product (here JPQL)
40
Convention over Configuration
Extend Repository
and build your own
interface using
conventions.
 Note: Repository is an interface (not a class!)
import org.springframework.data.repository.Repository;
import org.springframework.data.jpa.repository.Query;
public interface CustomerRepository extends Repository<Customer, Long> {
<S extends Customer> save(S entity); // Definition as per CrudRepository
Customer findById(long i);
// Query determined from method name
Customer findByEmailIgnoreCase(String email);
// Case insensitive search
@Query("select u from Customer u where u.emailAddress = ?1")
Customer findByEmail(String email);
// ?1 replaced by method param
}
 Copyright 2014 Pivotal. All rights reserved.
41
Internal behavior
 Before startup
Interface
UserRepository
 After startup
Interface
UserRepository
implements
$Proxy1
<jpa:repositories base-package="com.acme.repository"/>
You can conveniently use Spring to inject a dependency of type
UserRepository. Implementation will be generated at startup time.
 Copyright 2014 Pivotal. All rights reserved.
42
Adding Custom Behavior (1)
 Not all use cases satisfied by automated methods
 Enrich with custom repositories
 Step 1: Create normal interface and implementation
 Instantiate as a normal Spring bean:
public interface AccountRepositoryCustom {
Account findOverdrawnAccounts();
}
@Repository // This is a normal Spring bean, id = accountRepositoryImpl
public class AccountRepositoryImpl implements AccountRepositoryCustom {
Account findOverdrawnAccounts() {
// Your custom implementation
}
}
 Copyright 2014 Pivotal. All rights reserved.
43
Adding Custom Behavior (2)
 Step 2: Combine with automatic repository:
public interface AccountRepository
extends CrudRepository<Account, Long>, AccountRepositoryCustom {
}
 Spring Data looks for implementation beans
 ID = repository interface + Impl (configurable)
 In this example: AccountRepositoryImpl
 Result: AccountRepository bean contains automatic and
custom methods!
 Copyright 2014 Pivotal. All rights reserved.
44
Lab
Reimplementing Repositories using
Spring and JPA
 Copyright 2014 Pivotal. All rights reserved.
45
Topics in this session
Introduction to JPA
Configuring JPA in Spring
Implementing JPA DAOs
Spring Data  JPA
Lab
Optional Topics
 JPA Typed Queries / Native Queries
 EntityManagerFactoryBean alternatives / persistence.xml
 Exception Translation
 Copyright 2014 Pivotal. All rights reserved.
46
JPA Querying: Typed Queries
 Criteria Query API (JPA 2)
 Build type safe queries: fewer run-time errors
 Much more verbose
public List<Customer> findByLastName(String lastName) {
CriteriaBuilder builder = entityManager.getCriteriaBuilder();
CriteriaQuery<Customer> cq = builder.createQuery(Customer.class);
Predicate condition =
builder.equal( cq.from(Customer.class).get(Customer_.name), lastName);
cq.where(condition);
return entityManager.createQuery(cq).getResultList();
Meta-data class
created by JPA
(note underscore)
 Copyright 2014 Pivotal. All rights reserved.
47
JPA Querying: SQL
 Use a native query to execute raw SQL
No named parameter support
// Query for multiple rows
Query query = entityManager.createNativeQuery(
SELECT cust_num FROM T_CUSTOMER c WHERE cust_name LIKE ?);
query.setParameter(1, %ACME%);
Indexed from 1
List<String> customerNumbers = query.getResultList();
 like JDBC
//  or if expecting a single result
String customerNumber = (String) query.getSingleResult();
Specify Class to
Populate / return
// Query for multiple columns
Query query = entityManager.createNativeQuery(
SELECT ... FROM T_CUSTOMER c WHERE ..., Customer.class);
List<Customer> customers = query.getResultList();
 Copyright 2014 Pivotal. All rights reserved.
48
Topics in this session
Introduction to JPA
Configuring JPA in Spring
Implementing JPA DAOs
Spring Data  JPA
Lab
Optional Topics
 JPA Typed Queries / Native Queries
 EntityManagerFactoryBean alternatives / persistence.xml
 Exception Translation
 Copyright 2014 Pivotal. All rights reserved.
49
Setting up an EntityManagerFactory
 Three ways to set up an EntityManagerFactory:
 LocalEntityManagerFactoryBean
 LocalContainerEntityManagerFactoryBean
 Use a JNDI lookup
 persistence.xml required for configuration
 From version 3.1, Spring allows no persistence.xml with
LocalContainerEntityManagerFactoryBean
 Copyright 2014 Pivotal. All rights reserved.
50
persistence.xml
 Always stored in META-INF
 Specifies persistence unit:
 optional vendor-dependent information
 DB Connection properties often specified here.
<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>
File is required in JPA, but optional when using Spring with JPA!
 Copyright 2014 Pivotal. All rights reserved.
51
LocalEntityManagerFactoryBean
 Useful for standalone apps, integration tests
 Cannot specify a DataSource
 Useful when only data access is via JPA
 Uses standard JPA service location (SPI) mechanism
/META-INF/services/javax.persistence.spi.PersistenceProvider
@Bean
public LocalEntityManagerFactoryBean entityManagerFactory() {
LocalEntityManagerFactoryBean em =
new LocalEntityManagerFactoryBean();
em.setPersistenceUnitName(rewardNetwork);
return em;
}
 Copyright 2014 Pivotal. All rights reserved.
52
LocalContainer
EntityManagerFactoryBean
 Provides full JPA capabilities
 Integrates with existing DataSources
 Useful when fine-grained customization needed
 Can specify vendor-specific configuration
We saw this earlier with
100% Spring configuration
 Copyright 2014 Pivotal. All rights reserved.
53
Configuration  Spring and Persistence Unit
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean emfb =
new LocalContainerEntityManagerFactoryBean();
emfb.setDataSource(dataSource);
emfb.setPersistenceUnitName("rewardNetwork");
return emfb;
}
<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
 Copyright 2014 Pivotal. All rights reserved.
54
JNDI Lookups
 A jee:jndi-lookup can be used to retrieve
EntityManagerFactory from application server
 Useful when deploying to JEE Application Servers
(WebSphere, WebLogic, etc.)
OR
 Copyright 2014 Pivotal. All rights reserved.
55
Topics in this session
Introduction to JPA
Configuring JPA in Spring
Implementing JPA DAOs
Spring Data  JPA
Lab
Optional Topics
 JPA Typed Queries / Native Queries
 EntityManagerFactoryBean alternatives / persistence.xml
 Exception Translation
 Copyright 2014 Pivotal. All rights reserved.
56
Transparent Exception Translation (1)
 Used as-is, the DAO implementations described earlier
will throw unchecked PersistenceExceptions
 Not desirable to let these propagate up to the service layer
or other users of the DAOs
 Introduces dependency on the specific persistence
solution that should not exist
 AOP allows translation to Springs rich, vendor-neutral
DataAccessException hierarchy
 Hides access technology used
 Copyright 2014 Pivotal. All rights reserved.
57
Transparent Exception Translation (2)
 Spring provides this capability out of the box
 Annotate with @Repository
 Define a Spring-provided BeanPostProcessor
@Repository
public class JpaOrderRepository implements OrderRepository {
...
}
<bean class=org.springframework.dao.annotation.
PersistenceExceptionTranslationPostProcessor/>
 Copyright 2014 Pivotal. All rights reserved.
58
Transparent Exception Translation (3)
 Or use XML configuration:
public class JpaOrderRepository implements OrderRepository {
...
No annotations
}
<bean id=persistenceExceptionInterceptor
class=org.springframework.dao.support.
PersistenceExceptionTranslationInterceptor/>
<aop:config>
<aop:advisor pointcut=execution(* *..OrderRepository+.*(..))
advice-ref=persistenceExceptionInterceptor />
</aop:config>
 Copyright 2014 Pivotal. All rights reserved.
59
Summary
 Use 100% JPA to define entities and access data
 Repositories have no Spring dependency
 Spring Data Repositories need no code!
 Use Spring to configure JPA entity-manager factory
 Smart proxy works with Spring-driven transactions
 Optional translation to DataAccessExceptions
Spring-JPA  3 day in-depth JPA course with
emphasis on Hibernate as JPA provider
 Copyright 2014 Pivotal. All rights reserved.
60
Overview of Spring
Web
Developing Modern Web Applications
Servlet Configuration, Product Overview
 Copyright 2014 Pivotal. All rights reserved.
Topics in this Session
Introduction
Using Spring in Web Applications
Overview of Spring Web
Spring and other Web frameworks
 Copyright 2014 Pivotal. All rights reserved.
Web layer integration
 Spring provides support in the Web layer
 Spring MVC, Spring WebFlow...
 However, you are free to use Spring with any Java web
framework
 Integration might be provided by Spring or by the other
framework itself
 Copyright 2014 Pivotal. All rights reserved.
Effective Web Application Architecture
Clients
Remote HTTP Interfaces
Web Layer
Local Java Business Interfaces
Application Layer
(Spring)
Java EE Servlet Container
 Copyright 2014 Pivotal. All rights reserved.
JVM
Topics in this Session
Introduction
Using Spring in Web Applications
Overview of Spring Web
Spring and other Web frameworks
 Copyright 2014 Pivotal. All rights reserved.
Spring Application Context Lifecycle
in Web Applications
 Spring can be initialized within a webapp
 start up business services, repositories, etc.
 Uses a standard servlet listener
 initialization occurs before any servlets execute
 application ready for user requests
 ApplicationContext.close() is called when the application is
stopped
 Copyright 2014 Pivotal. All rights reserved.
Configuration via WebApplicationInitializer
public class MyWebAppInitializer
extends AbstractContextLoaderInitializer {
Implements
WebApplicationInitializer
Automatically detected
by servlet container.
@Override
protected WebApplicationContext createRootApplicationContext() {
// Create the 'root' Spring application context
AnnotationConfigWebApplicationContext rootContext =
new AnnotationConfigWebApplicationContext();
rootContext.getEnvironment().setActiveProfiles("jpa"); // optional
rootContext.register(RootConfig.class);
return rootContext;
}
...
Available in Servlet 3.0+ Environments, no more web.xml!
 Copyright 2014 Pivotal. All rights reserved.
Configuration in web.xml
 Only option prior to servlet 3.0
 Just add a Spring-provided servlet listener
<context-param>
web.xml
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/merchant-reporting-webapp-config.xml
</param-value>
</context-param> The application contexts configuration file(s)
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
Loads the ApplicationContext into the ServletContext
</listener>
before any Servlets are initialized
 Copyright 2014 Pivotal. All rights reserved.
Configuration Options
 Default resource location is document-root
 Can use classpath: designator
 Defaults to WEB-INF/applicationContext.xml
 Can optionally select profile to use
<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>
 Copyright 2014 Pivotal. All rights reserved.
web.xml
Servlet Container After Starting Up
Servlet
Context
Application Layer
(Spring)
Root ApplicationContext
Bound in ServletContext
under a well-known name
Now accessible to
any Servlet or other
web-layer artifact
Java EE Servlet Container
JVM
 Copyright 2014 Pivotal. All rights reserved.
10
Instantiating Servlets
Override onStartup() method to define servlets
 Warning: Can't inject the beans, not available yet
public class MyWebAppInitializer extends AbstractContextLoaderInitializer {
protected WebApplicationContext createRootApplicationContext() {
// ...Same configuration as previous slide...
No beans
}
are loaded
calls
yet at this
public void onStartup(ServletContext container) {
point in the
super.onStartup(container);
lifecycle...
// Register and map a servlet
ServletRegistration.Dynamic svlt =
container.addServlet("myServlet", new TopSpendersReportGenerator());
svlt.setLoadOnStartup(1);
svlt.addMapping("/");
}
 Copyright 2014 Pivotal. All rights reserved.
11
Dependency Injection of Servlets
 Suitable for web.xml or AbstractContextLoaderInitializer
 Neither provides access to Spring Beans
 Use WebApplicationContextUtils
 provides Spring ApplicationContext via ServletContext
public class TopSpendersReportGenerator extends HttpServlet {
private ClientService clientService;
public void init() {
ApplicationContext context = WebApplicationContextUtils.
getRequiredWebApplicationContext(getServletContext());
clientService = (ClientService) context.getBean(clientService);
}
}
 Copyright 2014 Pivotal. All rights reserved.
12
Dependency injection
 Example using Spring MVC
@Controller
public class TopSpendersReportController {
private ClientService clientService;
@Autowired
public TopSpendersReportController(ClientService service) {
this.clientService = service;
}
Dependency is automatically injected by type
No need for WebApplicationContextUtils anymore
 Copyright 2014 Pivotal. All rights reserved.
13
Topics in this Session
Introduction
Using Spring in Web Applications
Overview of Spring Web
Spring and other Web frameworks
 Copyright 2014 Pivotal. All rights reserved.
14
Spring Web
 Spring MVC
 Web framework bundled with Spring
 Spring WebFlow
 Plugs into Spring MVC
 Implements navigation flows
 Spring Mobile
 Routing between mobile / non-mobile versions of site
 Spring Social
 Easy integration with Facebook, Twitter, etc.
 Copyright 2014 Pivotal. All rights reserved.
15
Spring Web MVC
 Springs web framework
 Uses Spring for its own configuration
 Controllers are Spring beans
 testable artifacts
 Annotation-based model since Spring 2.5
 Builds on the Java Servlet API
 The core platform for developing web applications with
Spring
 All higher-level modules such as WebFlow build on it
 Copyright 2014 Pivotal. All rights reserved.
16
Spring Web Flow
 Plugs into Spring Web MVC as a Controller technology
for implementing stateful "flows"
 Checks that users follow the right navigation path
 Manages back button and multiple windows issues
 Provides scopes beyond request and session
 such as the flow and flash scope
 Addresses the double-submit problem elegantly
 Copyright 2014 Pivotal. All rights reserved.
17
Example Flow Definition
Online Check-in
 Flows are declared in Xml
<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>
 Copyright 2014 Pivotal. All rights reserved.
18
More about WebFlow
 Online sample application is available here:
http://richweb.springframework.org/swf-booking-faces/spring/intro
 Sample applications can be downloaded here:
http://www.springsource.org/webflow-samples
 Copyright 2014 Pivotal. All rights reserved.
19
Topics in this Session
Introduction
Using Spring in Web Applications
Overview of Spring Web
Spring and other Web frameworks
 Copyright 2014 Pivotal. All rights reserved.
20
Spring  Struts 1 integration
 Integration provided by the Spring framework
 Inherit from ActionSupport instead of Action
public class UserAction extends ActionSupport {
Provided by the
Spring framework
public ActionForward execute(ActionMapping mapping,
ActionForm form,...) throws Exception {
WebApplicationContext ctx = getWebApplicationContext();
UserManager mgr = (UserManager) ctx.getBean("userManager");
return mapping.findForward("success");
}
}
This is one of the 2 ways to integrate Spring and Struts 1 together.
More information in the reference documentation
 Copyright 2014 Pivotal. All rights reserved.
21
Spring  JSF integration
 Two options
 Spring-centric integration
 Provided by Spring Faces
 JSF-centric integration
 Spring plugs in as as a JSF managed bean provider
<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>
JSF-centric integration
</managed-property>
</managed-bean>
 Copyright 2014 Pivotal. All rights reserved.
22
Integration provided by other frameworks
 Struts 2
 provides a Spring plugin
http://struts.apache.org/2.0.8/docs/spring-plugin.html
 Wicket
 Comes with an integration to Spring
http://cwiki.apache.org/WICKET/spring.html
 Tapestry 5
 Comes with an integration to Spring
http://tapestry.apache.org/tapestry5/tapestry-spring/
 Copyright 2014 Pivotal. All rights reserved.
23
Summary
 Spring can be used with any web framework
 Spring provides the ContextLoaderListener that can be
declared in web.xml
 Spring MVC is a lightweight web framework where
controllers are Spring beans
 More about Spring MVC in the next module
 WebFlow plugs into Spring MVC as a Controller
technology for implementing stateful "flows"
 Copyright 2014 Pivotal. All rights reserved.
24
Spring Web MVC
Essentials
Getting Started With Spring MVC
Implementing a Simple Controller
 Copyright 2014 Pivotal. All rights reserved.
What is Spring MVC?
 Web framework based on the Model/View/Controller
pattern
 Alternative to Struts 1, Struts 2 (WebWork), Tapestry, Wicket,
JSF, etc.
 Based on Spring principles
 POJO programming
 Testable components
 Uses Spring for configuration
 Supports a wide range of view technologies
 JSP, XSLT, PDF, Excel, Velocity, Freemarker, Thymeleaf, etc.
 Copyright 2014 Pivotal. All rights reserved.
Topics in this Session
 Request Processing Lifecycle
 Key Artifacts
 DispatcherServlet
 Controllers
 Views
 Quick Start
 Copyright 2014 Pivotal. All rights reserved.
Web Request Handling Overview
 Web request handling is rather simple
Based on an incoming URL...
...we need to call a method...
...after which the return value (if any)...
...needs to be rendered using a view
 Copyright 2014 Pivotal. All rights reserved.
Request Processing Lifecycle
request (URL)
dispatch request
Dispatcher
Servlet
response
ts
ul
ns
Co
Model
Handler
Controller
(Logical view
name)
w)
ie
(v
render
Model
View
Resolver
Resolver(s)
View
 Copyright 2014 Pivotal. All rights reserved.
Topics in this Session
 Request Processing Lifecycle
 Key Artifacts
 DispatcherServlet
 Controllers
 Views
 Quick Start
 Copyright 2014 Pivotal. All rights reserved.
DispatcherServlet:
The Heart of Spring Web MVC
 A front controller
 coordinates all request handling activities
 analogous to Struts ActionServlet / JSF FacesServlet
 Delegates to Web infrastructure beans
 Invokes user Web components
 Fully customizable
 interfaces for all infrastructure beans
 many extension points
 Copyright 2014 Pivotal. All rights reserved.
DispatcherServlet Configuration
 Defined in web.xml or WebApplicationInitializer
 Uses Spring for its configuration
 programming to interfaces + dependency injection
 easy to swap parts in and out
 Creates separate servlet application context
 configuration is private to DispatcherServlet
 Full access to the parent root context
 instantiated via ContextLoaderListener
 shared across servlets
 Copyright 2014 Pivotal. All rights reserved.
Dispatcher Servlet Configuration Example
public class WebInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer {
// Tell Spring what to use for the Root context:
@Override protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{ RootConfig.class };
Root configuration
}
// Tell Spring what to use for the DispatcherServlet context:
@Override protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{ MvcConfig.class };
MVC configuration
}
// DispatcherServlet mapping:
@Override protected String[] getServletMappings() {
return new String[]{"/main/*"};
}
Servlet 3.0+
 Copyright 2014 Pivotal. All rights reserved.
Beans defined in
dispatcherContext
have access to
beans defined in
rootContext.
9
Dispatcher Servlet Configuration Example
<servlet>
<servlet-name>main</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/web-config.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>main</servlet-name>
<url-pattern>/main/*</url-pattern>
</servlet-mapping>
Pre-Servlet 3.0
web.xml
Beans defined in web layer have access
to beans defined in RootApplicationContext.
 Copyright 2014 Pivotal. All rights reserved.
10
Servlet Container After Starting Up
DispatcherServlet Application
Context
Web Layer Context:
Controllers, Views,
Resolvers, etc.
child
parent
Application Layer
Context:
Business Services,
Repositories, etc.
Root Application Context
 Copyright 2014 Pivotal. All rights reserved.
11
Topics in this Session
 Request Processing Lifecycle
 Key Artifacts
 DispatcherServlet
 Controllers
 Views
 Quick Start
 Copyright 2014 Pivotal. All rights reserved.
12
Controller Implementation
 Annotate controllers with @Controller
 @RequestMapping tells Spring what method to execute
when processing a particular request
@Controller
public class AccountController {
@RequestMapping("/listAccounts")
public String list(Model model) {...}
}
Example of calling URL:
http://localhost:8080 / mvc-1 / rewardsadmin / listAccounts
application server
 Copyright 2014 Pivotal. All rights reserved.
webapp
servlet mapping request mapping
13
URL-Based Mapping Rules
 Mapping rules typically URL-based, optionally using wild
cards:
/login
/editAccount
/listAccounts.htm
/reward/*/**
 Copyright 2014 Pivotal. All rights reserved.
14
Controller Method Parameters
 Extremely flexible!
 You pick the parameters you need, Spring provides them
 HttpServletRequest, HttpSession, Principal 
 Model for sending data to the view.
 See Spring Reference, Handler Methods
@Controller
public class AccountController {
@RequestMapping("/listAccounts")
public String list(Model model) {
...
}
}
 Copyright 2014 Pivotal. All rights reserved.
View name
Model holds data for view
15
Extracting Request Parameters
 Use @RequestParam annotation
 Extracts parameter from the request
 Performs type conversion
@Controller
public class AccountController {
@RequestMapping("/showAccount")
public String show(@RequestParam("entityId") long id,
Model model) {
...
}
...
Example of calling URL:
http://localhost:8080/mvc-1/rewardsadmin/showAccount.htm?entityId=123
 Copyright 2014 Pivotal. All rights reserved.
16
URI Templates
 Values can be extracted from request URLs
 Based on URI Templates
 not Spring-specific concept, used in many frameworks
 Use {} placeholders and @PathVariable
 Allows clean URLs without request parameters
@Controller
public class AccountController {
@RequestMapping("/accounts/{accountId}")
public String show(@PathVariable("accountId") long id,
Model model) {
...
}
Example of calling URL:
...
http://localhost:8080/mvc-1/rewardsadmin/accounts/123
 Copyright 2014 Pivotal. All rights reserved.
17
Method Signature Examples
@RequestMapping("/accounts")
public String show(HttpServletRequest request,
Model model)
@RequestMapping("/orders/{id}/items/{itemId}")
public String show(@PathVariable(id) Long id,
@PathVariable int itemId,
Model model, Locale locale,
@RequestHeader(user-agent)) String agent )
@RequestMapping("/orders")
public String show(@RequestParam Long id,
@RequestParam(itemId) int itemId,
Principal user, Map<String,Object> model,
Session session )
 Copyright 2014 Pivotal. All rights reserved.
18
Topics in this Session
 Request Processing Lifecycle
 Key Artifacts
 DispatcherServlet
 Controllers
 Views
 Quick Start
 Copyright 2014 Pivotal. All rights reserved.
19
Views
 A View renders web output.
 Many built-in views available for JSPs, XSLT, templating
approaches (Velocity, FreeMarker), etc.
 View support classes for creating PDFs, Excel spreadsheets,
etc.
 Controllers typically return a 'logical view name' String.
 ViewResolvers select View based on view name.
 Copyright 2014 Pivotal. All rights reserved.
20
View Resolvers
 The DispatcherServlet delegates to a ViewResolver to
obtain View implementation based on view name.
 The default ViewResolver treats the view name as a
Web Application-relative file path
 i.e. a JSP: /WEB-INF/reward/list.jsp
 Override this default by registering a ViewResolver bean
with the DispatcherServlet
 We will use InternalResourceViewResolver
 Several other options available.
 Copyright 2014 Pivotal. All rights reserved.
21
Internal Resource View Resolver Example
request (URL)
response
handle GET /reward/list
Dispatcher
Servlet
JstlView
ts
ul
ns
Co
Model
Logical view name
w)
ie
(v
render
Controller
Model
rewardList
View
Resolver
Resolved
Physical Path
/WEB-INF/views/rewardList.jsp
@Bean
public ViewResolver simpleViewResolver() {
InternalResourceViewResolver vr =
new InternalResourceViewResolver();
vr.setPrefix ( "/WEB-INF/views/" );
vr.setSuffix ( ".jsp" );
return vr;
}
 Copyright 2014 Pivotal. All rights reserved.
22
Topics in this Session
 Request Processing Lifecycle
 Key Artifacts
 DispatcherServlet
 Controllers
 Views
 Quick Start
 Copyright 2014 Pivotal. All rights reserved.
23
Quick Start
Steps to developing a Spring MVC application
1.
2.
3.
4.
5.
6.
Deploy a Dispatcher Servlet (one-time only)
Implement a controller
Register the Controller with the DispatcherServlet
Implement the View(s)
Register a ViewResolver (optional, one-time only)
Deploy and test
Repeat steps 2-6 to develop new functionality
 Copyright 2014 Pivotal. All rights reserved.
24
1a. Deploy DispatcherServlet
public class WebInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer {
// Root context:
@Override protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{ RootConfig.class };
}
// DispatcherServlet context:
@Override protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{ MvcConfig.class };
}
Contains Spring MVC configuration
// DispatcherServlet mapping:
@Override protected String[] getServletMappings() {
return new String[]{"/rewardsadmin/*"};
}
 Copyright 2014 Pivotal. All rights reserved.
25
1b. Deploy DispatcherServlet
 Can handle URLs like 
http://localhost:8080/mvc-1/rewardsadmin/reward/list
http://localhost:8080/mvc-1/rewardsadmin/reward/new
http://localhost:8080/mvc-1/rewardsadmin/reward/show?id=1
 We will implement show
 Copyright 2014 Pivotal. All rights reserved.
26
Initial Spring MVC Configuration
@Configuration
public class MvcConfig {
// No beans required for basic Spring MVC usage.
DispatcherServlet automatically defines several beans.
Provide overrides to default values as desired (view resolvers).
 Copyright 2014 Pivotal. All rights reserved.
27
2. Implement the Controller
@Controller
public class RewardController {
private RewardLookupService lookupService;
@Autowired
public RewardController(RewardLookupService svc) {
this.lookupService = svc;
Depends on
}
application service
@RequestMapping("/reward/show")
public String show(@RequestParam("id") long id,
Automatically filled
Model model) {
Reward reward = lookupService.lookupReward(id); in by Spring
model.addAttribute(reward, reward);
return rewardView;
Selects the rewardView to
}
to render the reward
}
 Copyright 2014 Pivotal. All rights reserved.
28
3. Register the Controller
@Configuration
@ComponentScan(accounts.web)
public class MvcConfig() {
Component-scanning very effective for MVC controllers!
Be specific when indicating base package, avoid loading non-web
layer beans
Feel free to use <bean /> or @Configuration approaches as desired
 Copyright 2014 Pivotal. All rights reserved.
29
4. Implement the View
<html>
<head><title>Your Reward</title></head>
<body>
Amount=${reward.amount} <br/>
Date=${reward.date} <br/>
Account Number=${reward.account} <br/>
Merchant Number=${reward.merchant}
</body>
References result model object by name
</html>
/WEB-INF/views/rewardView.jsp
Note: no references to Spring object / tags required in JSP.
 Copyright 2014 Pivotal. All rights reserved.
30
5. Register ViewResolver
@Configuration
@ComponentScan("accounts.web")
public class MvcConfig() {
@Bean
public ViewResolver simpleViewResolver() {
InternalResourceViewResolver vr =
new InternalResourceViewResolver();
vr.setPrefix ( "/WEB-INF/views/" );
vr.setSuffix ( ".jsp" );
return vr;
}
}
Controller returns rewardList
ViewResolver converts to /WEB-INF/views/rewardList.jsp
 Copyright 2014 Pivotal. All rights reserved.
31
6. Deploy and Test
http://localhost:8080/rewardsadmin/reward/show?id=1
Your Reward
Amount = $100.00
Date = 2006/12/29
Account Number = 123456789
Merchant Number = 1234567890
 Copyright 2014 Pivotal. All rights reserved.
32
Lab
Adding a Web Interface
 Copyright 2014 Pivotal. All rights reserved.
33
MVC Additions from Spring 3.0
 @MVC and legacy Controllers enabled by default
 Appropriate Controller Mapping and Adapters registered
out-of-the-box
 New features not enabled by default
 Stateless converter framework for binding & formatting
 Support for JSR-303 declarative validation for forms
 HttpMessageConverters (for RESTful web services)
 How do you use these features?
 Copyright 2014 Pivotal. All rights reserved.
34
@EnableWebMvc
 Registers Controller Mapping/Adapter for @MVC only
 You lose legacy default mappings and adapters!
 Enables custom conversion service and validators
 Beyond scope of this course
@Configuration
@EnableWebMvc
public class RewardConfig {
@Bean
public rewardController(RewardLookupService service) {
return new RewardController(service);
}
...
 Copyright 2014 Pivotal. All rights reserved.
35
WebMvcConfigurerAdapter
 Optionally extend WebMvcConfigurerAdapter
 Override methods to define/customize web-beans
@Configuration
@EnableWebMvc
public class RewardConfig extends WebMvcConfigurerAdapter {
@Bean public rewardController(RewardLookupService service) {  }
@Override
public void addFormatters(FormatterRegistry registry) {
// Register your own type converters and formatters...
}
...
 Copyright 2014 Pivotal. All rights reserved.
Example: add
custom formatters
36
MVC Namespace
 XML Equivalent to @EnableWebMvc
<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/>
Learn More:
Spring-Web  4 day course on Spring Web Modules
 Copyright 2014 Pivotal. All rights reserved.
37
Older Versions of Spring MVC
 Spring MVC is highly backwards compatible
 Most default settings have remained unchanged since
spring 2.5 (versions 3.0, 3.1, 3.2, 4.0, 4.1!)
 However, old default settings are no longer
recommended
 Newer styles of controllers, adapters, message convertors,
validators ...
 Use <mvc:annotation-config/> or @EnableWebMvc to
enable the more modern set of defaults
 Copyright 2014 Pivotal. All rights reserved.
38
Spring Boot
A new way to create Spring Applications
 Copyright 2014 Pivotal. All rights reserved.
Topics in this session
 What is Spring Boot?
 Spring Boot Explained
Dependency Management
Auto Configuration
Containerless Applications
Packaging
 Spring Boot inside of a Servlet Container
 Ease of Use Features
 Customizing Spring Boot
 Copyright 2014 Pivotal. All rights reserved.
What is Spring Boot?
 Spring Applications typically require a lot of setup
 Consider working with JPA. You need:
 Datasource, TransactionManager,
EntityManagerFactory, etc.
 Consider a web MVC app. You need:
 WebApplicationInitializer / web.xml,
ContextLoaderListener, DispatcherServlet, etc.
 An MVC app using JPA would need all of this
Much of this is predictable
 Copyright 2014 Pivotal. All rights reserved.
What is Spring Boot?
 An opinionated runtime for Spring Projects
 Supports different project types, like Web and Batch
 Handles most low-level, predictable setup for you
 It is not:
 A code generator
 An IDE plugin
See: Spring Boot Reference
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle
 Copyright 2014 Pivotal. All rights reserved.
Opinionated Runtime?
 Spring Boot uses sensible defaults, mostly based on the
classpath contents.
 E.g.:
 Sets up a JPA Entity Manager Factory if a JPA
implementation is on the classpath.
 Creates a default Spring MVC setup, if Spring MVC is on
the classpath.
 Everything can be overridden easily
 But most of the time not needed
 Copyright 2014 Pivotal. All rights reserved.
Spring Boot Demo
 Copyright 2014 Pivotal. All rights reserved.
Topics in this session
 What is Spring Boot?
 Spring Boot Explained
Dependency Management
Auto Configuration
Containerless Applications
Packaging
 Spring Boot inside of a Servlet Container
 Ease of Use Features
 Customizing Spring Boot
 Copyright 2014 Pivotal. All rights reserved.
Spring Boot Dependencies
 You've been using Spring Boot already in this class!
 Spring Boot defines parent POM and starter POMs
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>...</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
 See next...
 Copyright 2014 Pivotal. All rights reserved.
Spring Boot Parent POM
 Parent POM defines key versions of dependencies and
Maven plugin
 Ultimately optional  you can have your own parent POM
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>...</version>
</parent>
 Note: Spring Boot works with Maven, Gradle, Ant/Ivy
 But our content here will show Maven.
 Copyright 2014 Pivotal. All rights reserved.
Spring Starter POMs
 Allow an easy way to bring in multiple coordinated
dependencies
 Transitive Dependencies
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
</dependencies>
Resolves ~ 16 JARs!
Version not needed!
Defined by parent.
 Copyright 2014 Pivotal. All rights reserved.
spring-boot-*.jar
spring-core-*.jar
spring-context-*.jar
spring-aop-*.jar
spring-beans-*.jar
aopalliance-*.jar
etc.
10
Available Starter POMs
 Many Starter POMs available
 Web Starter (includes the basic starter):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
 Test Starter (adds Spring Test Framework and JUnit)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
See: Spring Boot Reference, Starter POMs
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-starter-poms
 Copyright 2014 Pivotal. All rights reserved.
11
Topics in this session
 What is Spring Boot?
 Spring Boot Explained
Dependency Management
Auto Configuration
Containerless Applications
Packaging
 Spring Boot inside of a Servlet Container
 Ease of Use Features
 Customizing Spring Boot
 Copyright 2014 Pivotal. All rights reserved.
12
Spring Boot @EnableAutoConfiguration
 @EnableAutoConfiguration annotation on a Spring Java
configuration class.
 Causes Spring Boot to automatically create beans it
thinks are needed
 Usually based on classpath contents
 But you can easily override
@Configuration
@EnableAutoConfiguration
public class MyAppConfig {
//...
}
 Copyright 2014 Pivotal. All rights reserved.
13
Shortcut @SpringBootApplication
 Very common to use @EnableAutoConfiguration,
@Configuration, and @ComponentScan together.
 Boot 1.2 combines these with @SpringBootApplication
@SpringBootApplication
public class MyAppConfig {
//...
}
 Copyright 2014 Pivotal. All rights reserved.
14
Topics in this session
 What is Spring Boot?
 Spring Boot Explained
Dependency Management
Auto Configuration
Containerless Applications
Packaging
 Spring Boot inside of a Servlet Container
 Ease of Use Features
 Customizing Spring Boot
 Copyright 2014 Pivotal. All rights reserved.
15
Spring Boot as a runtime
 Spring Boot can startup an embedded web server
 You can run a web application from a JAR file!
 Tomcat included in Web Starter
 Jetty instead of Tomcat:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
 Copyright 2014 Pivotal. All rights reserved.
16
Why Run a Web Application
Outside of a Container?
 No separation of container config and app config
 They depend on each other anyway (like JNDI DS names,
security config)
 Apps mostly target to a specific container
 Why not include that already?
Easier debugging and profiling
Easier hot code replacement
No special IDE support needed
Familiar model for non-Java developers
 Copyright 2014 Pivotal. All rights reserved.
17
Topics in this session
 What is Spring Boot?
 Spring Boot Explained
Dependency Management
Auto Configuration
Containerless Applications
Packaging
 Spring Boot inside of a Servlet Container
 Ease of Use Features
 Customizing Spring Boot
 Copyright 2014 Pivotal. All rights reserved.
18
Packaging
 Spring Boot creates an Ueber-Jar
 Contains your classes as well as all 3rd party libs in one
JAR (a JarJar).
 Can be executed with java -jar yourapp.jar
 Gradle and Maven plugins available
 Original JAR is still created
 Copyright 2014 Pivotal. All rights reserved.
19
Maven Packaging
 Add Boot Maven plugin to pom.xml
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
 Copyright 2014 Pivotal. All rights reserved.
20
Packaging Result
 mvn package execution produces:
22M yourapp-0.0.1-SNAPSHOT.jar
5,1K yourapp-0.0.1-SNAPSHOT.jar.original
 .jar.original contains only your code (traditional JAR file)
 .jar contains your code and all libs
 Copyright 2014 Pivotal. All rights reserved.
21
Topics in this session
 What is Spring Boot?
 Spring Boot Explained
Dependency Management
Auto Configuration
Containerless Applications
Packaging
 Spring Boot inside of a Servlet Container
 Ease of Use Features
 Customizing Spring Boot
 Copyright 2014 Pivotal. All rights reserved.
22
Spring Boot in a Servlet Container
 Spring Boot can run in any Servlet 3.x container
 Only small changes required
 Change artifact type to WAR (instead of JAR)
 Extend SpringBootServletInitializer
 Override configure method
 Still no web.xml required
 Produces hybrid WAR file
 Can still be executed with embedded Tomcat using java
-jar yourapp.war
 Traditional WAR file (without embedded Tomcat) is
produced as well
 Copyright 2014 Pivotal. All rights reserved.
23
Spring Boot in a Servlet Container
@ComponentScan
@EnableAutoConfiguration
public class Application extends SpringBootServletInitializer {
protected SpringApplicationBuilder configure(
SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
 Copyright 2014 Pivotal. All rights reserved.
24
WAR packaging result
 mvn package execution produces:
22M
20M
yourapp-0.0.1-SNAPSHOT.war
yourapp-0.0.1-SNAPSHOT.war.original
 .war.original is a traditional WAR file
 .war is a hybrid WAR file, additionally containing the
embedded Tomcat
 Can be executed with
java -jar yourapp-0.0.1-SNAPSHOT.war
 Copyright 2014 Pivotal. All rights reserved.
25
It's Your Choice
 There is no force to go containerless
 Embedded container is just one feature of Spring Boot
 Traditional WAR also benefits a lot from Spring Boot:
 Automatic Spring MVC setup, including DispatcherServlet
 Sensible defaults based on the classpath content
 Embedded container can be used during development
 Copyright 2014 Pivotal. All rights reserved.
26
Topics in this session
 What is Spring Boot?
 Spring Boot Explained
Dependency Management
Auto Configuration
Containerless Applications
Packaging
 Spring Boot inside of a Servlet Container
 Ease of Use Features
 Customizing Spring Boot
 Copyright 2014 Pivotal. All rights reserved.
27
Externalized Properties:
application.properties
 Developers commonly externalize properties to files
 Easily consumable via Spring PropertySource
 ...But developers name / locate their files different ways.
 Spring Boot will automatically look for
application.properties in the classpath root.
 Or use application.yml if you prefer YAML
database.host: localhost
database.user: admin
database.poolsize: 2-20
application.properties
 Copyright 2014 Pivotal. All rights reserved.
database
host: localhost
user: admin
poolsize: 2-20
application.yml
28
Relaxed property binding
 No need for an exact match between desired properties
and names
 Intuitive mapping between system properties and
environment variables
 test.property equivalent to TEST_PROPERTY
 Access via SpEL
@Configuration
class AppConfig {
@Value("${test.property}")
String testProperty;
Or without Spring Boot:
@Value("${TEST_PROPERTY}")
}
 Copyright 2014 Pivotal. All rights reserved.
@Bean SomeObject myBean() { ... }
29
@ConfigurationProperties
 Easily set multiple properties on a bean with one
annotation
 Enable with @EnableConfigurationProperties in
configuration class
@Component
@ConfigurationProperties(prefix="my.car")
public class Car {
private String color;
private String engine;
// getters / setters
my.car.color=red
my.car.engine=5.0
application.properties
 Copyright 2014 Pivotal. All rights reserved.
30
@ConfigurationProperties with @Bean
 Set properties on @Bean method automatically
 Replace this:
@Bean
public DataSource dataSource(
@Value("${db.credentials.driver}") dbDriver,
@Value("${db.credentials.url}") dbUrl,
@Value("${db.credentials.user}") dbUser,
@Value("${db.credentials.password}") dbPassword) {
DataSource ds = new BasicDataSource();
ds.setDriverClassName( dbDriver);
ds.setUrl( dbUrl);
ds.setUser( dbUser);
ds.setPassword( dbPassword ));
return ds;
}
 Copyright 2014 Pivotal. All rights reserved.
31
@ConfigurationProperties with @Bean
 Set properties on @Bean method automatically
 Replace this:
 With this:
@Bean
@ConfigurationProperties(prefix="db.credentials")
public DataSource dataSource() {
return new BasicDataSource();;
}
 Copyright 2014 Pivotal. All rights reserved.
32
Even Easier...
 Use either spring-boot-starter-jdbc or spring-boot-starterdata-jpa and include a JDBC driver on classpath
 Declare properties
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
 That's It!
 Spring Boot will create a DataSource with properties set.
 Will even use a connection pool if one is found on the
classpath!
 Copyright 2014 Pivotal. All rights reserved.
33
Controlling Logging Level
 Boot can control the logging level
 Just set the logging level in application.properties
 Works with most logging frameworks
 Java Util Logging, Logback, Log4J, Log4J2
logging.level.org.springframework: DEBUG
logging.level.com.acme.your.code: INFO
 Copyright 2014 Pivotal. All rights reserved.
34
Web Application Convenience
 Boot automatically configures Spring MVC
DispatcherServlet and @EnableWebMvc defaults
 When spring-webmvc*.jar on classpath
 Static resources served from classpath
 /static, /public, /resources or /META-INF/resources
 Templates served from /templates
 When Velocity, Freemarker, Thymeleaf, or Groovy on
classpath
 Provides default /error mapping
 Easily overridden
 Copyright 2014 Pivotal. All rights reserved.
35
Topics in this session
 What is Spring Boot?
 Spring Boot Explained
Dependency Management
Auto Configuration
Containerless Applications
Packaging
 Spring Boot inside of a Servlet Container
 Ease of Use Features
 Customizing Spring Boot
 Copyright 2014 Pivotal. All rights reserved.
36
Customizing Spring Boot
 Many ways to customize Spring Boot
 application.properties
 Replacing generated beans
 Selectively disabling auto configuration
 Copyright 2014 Pivotal. All rights reserved.
37
Application properties
 Spring Boot looks for application.properties in these
locations (in this order):
/config subdir of the working directory
The working directory
config package in the classpath
classpath root
 Creates a PropertySource based on these files.
 Check AutoConfigure classes for available properties
 e.g. spring.datasource.name in
EmbeddedDataSourceConfiguration.class
See: Spring Boot Reference, Appendix A. Common Application Properties
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#common-application-properties
 Copyright 2014 Pivotal. All rights reserved.
38
Replacing generated beans (1)
 Self declared beans typically disable automatically
created ones.
 E.g. Own DataSource stops creating Spring Boot
DataSource
 Bean name often not important
 XML, Component Scan and Java Config supported
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder().
setName("RewardsDb").build();
}
 Copyright 2014 Pivotal. All rights reserved.
39
Replacing generated beans (2)
 Check AutoConfigure classes for details:
@Configuration
public class DataSourceAutoConfiguration
implements EnvironmentAware {
@Conditional()
@ConditionalOnMissingBean(DataSource.class)
@Import()
protected static class EmbeddedConfiguration {  }
 Copyright 2014 Pivotal. All rights reserved.
40
Selectively disabling auto configuration
 Check /autoconfig to see active configuration classes
 exclude completely disables them:
@EnableAutoConfiguration(exclude=EmbeddedDatabaseConfigurer.class)
public class Application extends SpringBootServletInitializer {
 Copyright 2014 Pivotal. All rights reserved.
41
Additional Integrations
Spring Data (see lab)
Spring Security
MongoDB
Testing
Cloud Foundry
...
 Copyright 2014 Pivotal. All rights reserved.
42
Summary
Spring Boot speeds up Spring application development
You always have full control and insight
Nothing is generated
No special runtime requirements
No servlet container needed (if you want)
 E.g. ideal for microservices
 Stay tuned for much more features soon
 Copyright 2014 Pivotal. All rights reserved.
43
Spring Boot Lab
 Copyright 2014 Pivotal. All rights reserved.
44
Spring Security
Web Application Security
Addressing Common Security Requirements
 Copyright 2014 Pivotal. All rights reserved.
Topics in this Session
High-Level Security Overview
Motivations of Spring Security
Spring Security in a Web Environment
Configuring Web Authentication
Using Spring Security's Tag Libraries
Method security
Advanced security: working with filters
 Copyright 2014 Pivotal. All rights reserved.
Security Concepts
 Principal
 User, device or system that performs an action
 Authentication
 Establishing that a principals credentials are valid
 Authorization
 Deciding if a principal is allowed to perform an action
 Secured item
 Resource that is being secured
 Copyright 2014 Pivotal. All rights reserved.
Authentication
 There are many authentication mechanisms
 e.g. basic, digest, form, X.509
 There are many storage options for credential and
authority information
 e.g. Database, LDAP, in-memory (development)
 Copyright 2014 Pivotal. All rights reserved.
Authorization
 Authorization depends on authentication
 Before deciding if a user can perform an action, user
identity must be established
 The decision process is often based on roles
 ADMIN can cancel orders
 MEMBER can place orders
 GUEST can browse the catalog
 Copyright 2014 Pivotal. All rights reserved.
Topics in this Session
High-Level Security Overview
Motivations of Spring Security
Spring Security in a Web Environment
Configuring Web Authentication
Using Spring Security's Tag Libraries
Method security
Advanced security: working with filters
See: Spring Security Reference
http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/
 Copyright 2014 Pivotal. All rights reserved.
Motivations - I
 Spring Security is portable across containers
 Secured archive (WAR, EAR) can be deployed as-is
 Also runs in standalone environments
 Uses Spring for configuration
 Separation of Concerns
 Business logic is decoupled from security concerns
 Authentication and Authorization are decoupled
 Changes to the authentication process have no impact
on authorization
 Copyright 2014 Pivotal. All rights reserved.
Motivations: II
 Flexibility
 Supports all common authentication mechanisms
 Basic, Form, X.509, Cookies, Single-Sign-On, etc.
 Configurable storage options for user details (credentials
and authorities)
 RDBMS, LDAP, custom DAOs, properties file, etc.
 Extensible
 All the following can be customized
 How a principal is defined
 How authorization decisions are made
 Where security constraints are stored
 Copyright 2014 Pivotal. All rights reserved.
Consistency of Approach
 The goal of authentication is always the same
regardless of the mechanism
 Establish a security context with the authenticated
principals information
 Out-of-the-box this works for web applications
 The process of authorization is always the same
regardless of resource type
 Consult the attributes of the secured resource
 Obtain principal information from security context
 Grant or deny access
 Copyright 2014 Pivotal. All rights reserved.
Spring Security 
the Big Picture
Authentication
Manager
populates
AccessDecision
Manager
polls
delegates
Security Interceptor
protects consults
obtains
Voters
Config
Attributes
describes
Security Context
thread of
execution
 Copyright 2014 Pivotal. All rights reserved.
Authentication
(Principal + Authorities)
Secured
Resource
10
Topics in this Session
High-Level Security Overview
Motivations of Spring Security
Spring Security in a Web Environment
Configuring Web Authentication
Using Spring Security's Tag Libraries
Method security
Advanced security: working with filters
 Copyright 2014 Pivotal. All rights reserved.
11
Configuration in the Application Context
 Java Configuration (XML also available)
 Extend WebSecurityConfigurerAdapter for easiest use
@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
}
Web-specific security settings
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
}
}
 Copyright 2014 Pivotal. All rights reserved.
general security settings
(authentication manager, etc.
12
Configuration in web.xml
 Define the single proxy filter
 springSecurityFilterChain is a mandatory name
 Refers to an existing Spring bean with same name
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
web.xml
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
 Copyright 2014 Pivotal. All rights reserved.
13
authorizeRequests()
 Adds specific authorization requirements to URLs
 Evaluated in the order listed
 first match is used, put specific matches first
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/css/**","/images/**","/javascript/**").permitAll()
.antMatchers("/accounts/edit*").hasRole("ADMIN")
.antMatchers("/accounts/account*").hasAnyRole("USER",ADMIN)
.antMatchers("/accounts/**").authenticated()
.antMatchers("/customers/checkout*").authenticatedFully()
.antMatchers("/customers/**").anonymous()
 Copyright 2014 Pivotal. All rights reserved.
14
Specifying login and logout
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/aaa*").hasRole("ADMIN")
.and()
// method chaining!
.formLogin()
.loginPage("/login.jsp")
.permitAll()
.and()
//
//
//
//
setup form-based authentication
URL to use when login is needed
any user can access
method chaining!
.logout()
.permitAll();
// configure logout
// any user can access
 Copyright 2014 Pivotal. All rights reserved.
15
An Example Login Page
URL that indicates an authentication request.
Default: POST against URL used to display the page.
<c:url var=loginUrlvalue=/login.jsp />
<form:form action=${loginUrl} method=POST>
<input type=text name=username/>
<br/>
<input type=password name=password/>
<br/>
<input type=submit name=submit value=LOGIN/>
</form:form>
 Copyright 2014 Pivotal. All rights reserved.
The expected keys
for generation of
an authentication
request token
login-example.jsp
16
Topics in this Session
High-Level Security Overview
Motivations of Spring Security
Spring Security in a Web Environment
Configuring Web Authentication
Using Spring Security's Tag Libraries
Method security
Advanced security: working with filters
 Copyright 2014 Pivotal. All rights reserved.
17
Configure Authentication
 DAO Authentication provider is default
 Expects a UserDetailsService implementation to provide
credentials and authorities
 Built-in: In-memory (properties), JDBC (database), LDAP
 Custom
 Or define your own Authentication provider
 Example: to get pre-authenticated user details
when using single sign-on
 CAS, TAM, SiteMinder ...
 See online examples
 Copyright 2014 Pivotal. All rights reserved.
18
Authentication Provider
 Use a UserDetailsManagerConfigurer
 Three built in options:
 LDAP
 JDBC
 In-memory (for quick testing)
 Or use your own UserDetailsService implementation
Not web-specific
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
Adds a UserDetailsManagerConfigurer
.inMemoryAuthentication()
.withUser("hughie").password("hughie").roles("GENERAL").and().
.withUser("dewey").password("dewey").roles("ADMIN").and().
.withUser("louie").password("louie").roles("SUPPORT");
}
password
login
Supported roles
 Copyright 2014 Pivotal. All rights reserved.
19
Sourcing Users from a Database
 Configuration:
@Autowired DataSource dataSource;
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource);
}
Can customize queries using methods:
usersByUsernameQuery()
authoritiesByUsernameQuery()
groupAuthoritiesByUsername()
 Copyright 2014 Pivotal. All rights reserved.
20
Sourcing Users from a Database
Queries RDBMS for users and their authorities
 Provides default queries
 SELECT username, password, enabled FROM users
WHERE username = ?
 SELECT username, authority FROM authorities WHERE
username = ?
 Groups also supported
 groups, group_members, group_authorities tables
 See online documentation for details
 Advantage
 Can modify user info while system is running
 Copyright 2014 Pivotal. All rights reserved.
21
Password Encoding
 Can encode passwords using a hash
 sha, md5, bcrypt, ...
auth.jdbcAuthentication()
.dataSource(dataSource)
SHA-256 encoding
.passwordEncoder(new StandardPasswordEncoder());
 Secure passwords using a well-known string
 Known as a 'salt', makes brute force attacks harder
auth.jdbcAuthentication()
encoding with salt
.dataSource(dataSource)
.passwordEncoder(new StandardPasswordEncoder(sodium-chloride));
 Copyright 2014 Pivotal. All rights reserved.
22
Other Authentication Options
 Implement a custom UserDetailsService
 Delegate to an existing User repository or DAO
LDAP
X.509 Certificates
JAAS Login Module
Single-Sign-On
OAuth
SAML
SiteMinder
Kerberos
JA-SIG Central Authentication Service
Authorization is not affected by changes to Authentication!
 Copyright 2014 Pivotal. All rights reserved.
23
@Profile with Security Configuration
 Use @Profile to separate development vs. production
public class SecurityBaseConfig extends WebSecurityConfigurerAdapter {
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/resources/**").permitAll();
}
}
@Configuration
@EnableWebMvcSecurity
@Profile(production)
@Profile(development)
public class SecurityDevConfig
SecurityProdConfigextends
extendsSecurityBaseConfig
SecurityBaseConfig{{
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth
auth.jdbcAuthentication().dataSource(dataSource);
} .inMemoryAuthentication()
}
.withUser("hughie").password("hughie").roles("GENERAL");
}
}
 Copyright 2014 Pivotal. All rights reserved.
24
Topics in this Session
High-Level Security Overview
Motivations of Spring Security
Spring Security in a Web Environment
Configuring Web Authentication
Using Spring Security's Tag Libraries
Method security
Advanced security: working with filters
 Copyright 2014 Pivotal. All rights reserved.
25
Tag library declaration
 The Spring Security tag library is declared as follows
available since Spring Security 2.0
<%@ taglib prefix="security"
uri="http://www.springframework.org/security/tags" %>
jsp
Facelet tags for JSF are also available
 You need to define and install them manually
 See Using the Spring Security Facelets Tag Library in the
Spring Webflow documentation
 Principle is available in SpEL: #{principle.username}
 Copyright 2014 Pivotal. All rights reserved.
26
Spring Securitys Tag Library
 Display properties of the Authentication object
You are logged in as:
<security:authentication property=principal.username/>
jsp
 Hide sections of output based on role
<security:authorize access=hasRole('ROLE_MANAGER')>
TOP-SECRET INFORMATION
Click <a href=/admin/deleteAll>HERE</a> to delete all records.
</security:authorize>
jsp
 Copyright 2014 Pivotal. All rights reserved.
27
Authorization in JSP based on intercept-url
 Role declaration can be centralized in Spring config files
URL to protect
<security:authorize url=/admin/deleteAll>
TOP-SECRET INFORMATION
Click <a href=/admin/deleteAll>HERE</a>
</security:authorize>
jsp
Pattern that
matches the URL
to be protected
.antMatchers("/admin/*").hasAnyRole("MANAGER",ADMIN)
Matching roles
 Copyright 2014 Pivotal. All rights reserved.
28
Topics in this Session
High-Level Security Overview
Motivations of Spring Security
Spring Security in a Web Environment
Configuring Web Authentication
Using Spring Security's Tag Libraries
Method security
Advanced security: working with filters
 Copyright 2014 Pivotal. All rights reserved.
29
Method Security
 Spring Security uses AOP for security at the method
level
 annotations based on Spring annotations or JSR-250
annotations
 XML configuration with the Spring Security namespace
 Typically secure your services
 Do not access repositories directly, bypasses security (and
transactions)
 Copyright 2014 Pivotal. All rights reserved.
30
Method Security - JSR-250
 JSR-250 annotations should be enabled
@EnableGlobalMethodSecurity(jsr250Enabled=true)
import javax.annotation.security.RolesAllowed;
public class ItemManager {
@RolesAllowed({"ROLE_MEMBER", "ROLE_USER"})
public Item findItem(long itemNumber) {
...
}
}
Only supports role-based security  hence the name
 Copyright 2014 Pivotal. All rights reserved.
31
Method Security - @Secured
 Secured annotation should be enabled
@EnableGlobalMethodSecurity(securedEnabled=true)
import org.springframework.security.annotation.Secured;
public class ItemManager {
@Secured("IS_AUTHENTICATED_FULLY")
public Item findItem(long itemNumber) {
...
}
@Secured("ROLE_MEMBER")
}
@Secured({"ROLE_MEMBER", "ROLE_USER"})
Spring 2.0 syntax, so not limited to roles. SpEL not supported.
 Copyright 2014 Pivotal. All rights reserved.
32
Method Security with SpEL
 Use Pre/Post annotations for SpEL
@EnableGlobalMethodSecurity(prePostEnabled=true)
import org.springframework.security.annotation.PreAuthorize;
public class ItemManager {
@PreAuthorize("hasRole('ROLE_MEMBER')")
public Item findItem(long itemNumber) {
...
}
}
 Copyright 2014 Pivotal. All rights reserved.
33
Topics in this Session
High-Level Security Overview
Motivations of Spring Security
Spring Security in a Web Environment
Configuring Web Authentication
Using Spring Security's Tag Libraries
Method security
Advanced security: working with filters
 Copyright 2014 Pivotal. All rights reserved.
34
Spring Security in a Web Environment
 springSecurityFilterChain is declared in web.xml
 This single proxy filter delegates to a chain of Springmanaged filters
Drive authentication
Enforce authorization
Manage logout
Maintain SecurityContext in HttpSession
and more
 Copyright 2014 Pivotal. All rights reserved.
35
Web Security Filter Configuration
Servlet Container
Web
User
DelegatingFilterProxy
Servlet
springSecurityFilterChain
Filter
1
Filter
2
Filter
N
Spring ApplicationContext
 Copyright 2014 Pivotal. All rights reserved.
36
The Filter chain
 With ACEGI Security 1.x
 Filters were manually configured as individual <bean>
elements
 Led to verbose and error-prone XML
 Spring Security 2.x and 3.x
 Filters are initialized with correct values by default
 Manual configuration is not required unless you want to
customize Spring Security's behavior
 It is still important to understand how they work underneath
 Copyright 2014 Pivotal. All rights reserved.
37
Access Unsecured Resource Prior to Login
Web Browser
Context did not
change so no need to
store in session
Clears context
No context in session
Establishes empty
security context
SecurityContextPersistenceFilter
Not a logout request
does nothing
LogoutFilter
Does nothing on
response side
Not an authentication
request does nothing
UsernamePasswordAuthenticationFilter
Does nothing on
response side
Does nothing on
request side
ExceptionTranslationFilter
Resource has no
security attributes
does nothing
FilterSecurityInterceptor
UnsecuredResource
 Copyright 2014 Pivotal. All rights reserved.
No exceptions thrown
does nothing
Resource has no
security attributes
does nothing
38
Access Secured Resource Prior to Login
Web Browser
No context in session
Establishes empty
security context
Login Form
SecurityContextPersistenceFilter
LogoutFilter
Does nothing
Does nothing
UsernamePasswordAuthenticationFilter
Does nothing
ExceptionTranslationFilter
Resource is secured
THROWS NOT
AUTHENTICATED
EXCEPTION
 Copyright 2014 Pivotal. All rights reserved.
FilterSecurityInterceptor
Authentication
exception!
 Saves current
request in session
Clears context
Redirects to
authentication entry
point
SecuredResource
39
Submit Login Request
Web Browser
No context in session
Establishes empty
security context
Does nothing
Creates request and
delegates to the
Authentication
Manager
SUCCESS
populates context
redirects to target url
FAILURE
redirects to failure url
 Copyright 2014 Pivotal. All rights reserved.
SecurityContextPersistenceFilter
LogoutFilter
UsernamePasswordAuthenticationFilter
ExceptionTranslationFilter
FilterSecurityInterceptor
SecuredResource
40
Access Resource With Required Role
Web Browser
Finds context in
session and sets
for current thread
SecurityContextPersistenceFilter
Stores context back
into session
Does nothing
LogoutFilter
Does nothing
Does nothing
UsernamePasswordAuthenticationFilter
Does nothing
Does nothing
ExceptionTranslationFilter
Does nothing
FilterSecurityInterceptor
Does nothing
Consults attributes,
obtains context, and
delegates to access
decision manager
 Copyright 2014 Pivotal. All rights reserved.
SecuredResource
41
Access Resource Without Required Role
Web Browser
Finds context in
session and sets
for current thread
Error Page
SecurityContextPersistenceFilter
LogoutFilter
Does nothing
Does nothing
UsernamePasswordAuthenticationFilter
Does nothing
ExceptionTranslationFilter
Consults attributes,
obtains context, and
delegates to access
decision manager
Access Denied
Exception!
 Puts exception in
request scope
 Forwards to the
error page
FilterSecurityInterceptor
SecuredResource
Throws ACCESS DENIED EXCEPTION
 Copyright 2014 Pivotal. All rights reserved.
42
Submit Logout Request
Logout Success
Finds context in
session and sets
for current thread
 Clears context
 Redirects to
logout success url
Web Browser
SecurityContextPersistenceFilter
LogoutFilter
UsernamePasswordAuthenticationFilter
ExceptionTranslationFilter
FilterSecurityInterceptor
SecuredResource
 Copyright 2014 Pivotal. All rights reserved.
43
The Filter Chain: Summary
#
Filter Name
SecurityContext
IntegrationFilter
LogoutFilter
UsernamePassword
AuthenticationFilter
Main Purpose
Establishes SecurityContext and maintains
between HTTP requests
formerly: HttpSessionContextIntegrationFilter
Clears SecurityContextHolder when logout
requested
Puts Authentication into the
SecurityContext on login request
formerly: AuthenticationProcessingFilter
Exception
TranslationFilter
Converts SpringSecurity exceptions into
HTTP response or redirect
FilterSecurity
Interceptor
Authorizes web requests based on on
config attributes and authorities
 Copyright 2014 Pivotal. All rights reserved.
44
Custom Filter Chain
 Filter can be added to the chain
 Before or after existing filter
http.addFilterAfter ( myFilter, UsernamePasswordAuthenticationFilter.class );
@Bean
public Filter myFilter() {
return new MySpecialFilter();
}
 Filter on the stack may be replaced by a custom filter
 Replacement must extend the filter being replaced.
http.addFilter ( myFilter );
public class MySpecialFilter
@Bean
extends UsernamePasswordAuthenticationFilter {}
public Filter myFilter() {
return new MySpecialFilter();
}
 Copyright 2014 Pivotal. All rights reserved.
45
Lab
Applying Spring Security to a Web
Application
 Copyright 2014 Pivotal. All rights reserved.
46
Practical REST Web
Services
Using Spring MVC to build RESTful Web
Services
Extending Spring MVC to handle REST
 Copyright 2014 Pivotal. All rights reserved.
Topics in this Session
 REST introduction
 REST and Java
 Spring MVC support for RESTful applications
 Request/Response Processing
 Using MessageConverters
 Content Negotiation
 Putting it all together
 RESTful clients with the RestTemplate
 Conclusion
 Copyright 2014 Pivotal. All rights reserved.
REST Introduction
 Web apps not just usable by browser clients
 Programmatic clients can also connect via HTTP
 Such as: mobile applications, AJAX enabled web-pages
 REST is an architectural style that describes best
practices to expose web services over HTTP
REpresentational State Transfer, term by Roy Fielding
HTTP as application protocol, not just transport
Emphasizes scalability
Not a framework or specification
 Copyright 2014 Pivotal. All rights reserved.
REST Principles (1)
 Expose resources through URIs
 Model nouns, not verbs
 http://mybank.com/banking/accounts/123456789
 Resources support limited set of operations
 GET, PUT, POST, DELETE in case of HTTP
 All have well-defined semantics
 Example: update an order
 PUT to /orders/123
 don't POST to /order/edit?id=123
 Copyright 2014 Pivotal. All rights reserved.
REST Principles (2)
 Clients can request particular representation
 Resources can support multiple representations
 HTML, XML, JSON, 
 Representations can link to other resources
 Allows for extensions and discovery, like with web sites
 Hypermedia As The Engine of Application State
 HATEOAS: Probably the world's worst acronym!
 RESTful responses contain the links you need  just
like HTML pages do
 Copyright 2014 Pivotal. All rights reserved.
REST Principles (3)
 Stateless architecture
No HttpSession usage
GETs can be cached on URL
Requires clients to keep track of state
Part of what makes it scalable
Looser coupling between client and server
 HTTP headers and status codes communicate result
to clients
 All well-defined in HTTP Specification
 Copyright 2014 Pivotal. All rights reserved.
Why REST?
 Benefits of REST
 Every platform/language supports HTTP
 Unlike for example SOAP + WS-* specs
 Easy to support many different clients
 Scripts, Browsers, Applications
 Scalability
 Support for redirect, caching, different representations,
resource identification, 
 Support for XML, but also other formats
 JSON and Atom are popular choices
 Copyright 2014 Pivotal. All rights reserved.
Topics in this Session
REST introduction
REST and Java
Spring MVC support for RESTful applications
RESTful clients with the RestTemplate
Conclusion
 Copyright 2014 Pivotal. All rights reserved.
REST and Java: JAX-RS
 JAX-RS is a Java EE 6 standard for building RESTful
applications
 Focuses on programmatic clients, not browsers
 Various implementations
 Jersey (RI), RESTEasy, Restlet, CXF
 All implementations provide Spring support
 Good option for full REST support using a standard
 No support for building clients in standard
 Although some implementations do offer it
 Copyright 2014 Pivotal. All rights reserved.
REST and Java: Spring-MVC
 Spring-MVC provides REST support as well
 Since version 3.0
 Using familiar and consistent programming model
 Spring MVC does not implement JAX-RS
 Single web-application for everything
 Traditional web-site: HTML, browsers
 Programmatic client support (RESTful web applications,
HTTP-based web services)
 RestTemplate for building programmatic clients in Java
 Copyright 2014 Pivotal. All rights reserved.
10
Topics in this Session
 REST introduction
 REST and Java
 Spring MVC support for RESTful applications
 Request/Response Processing
 Using MessageConverters
 Putting it all together
 RESTful clients with the RestTemplate
 Conclusion
 Copyright 2014 Pivotal. All rights reserved.
11
Spring-MVC and REST
 Some features have been covered already
 URI templates for 'RESTful' URLs
 Will now extend Spring MVC to support REST
 Map requests based on HTTP method
 More annotations
 Message Converters
 Support for RESTful web applications targeting browserbased clients is also offered
 See HttpMethodFilter in online documentation
 Copyright 2014 Pivotal. All rights reserved.
12
Topics in this Session
 REST introduction
 REST and Java
 Spring MVC support for RESTful applications
 Request/Response Processing
 Using MessageConverters
 Putting it all together
 RESTful clients with the RestTemplate
 Conclusion
 Copyright 2014 Pivotal. All rights reserved.
13
Request Mapping Based on HTTP Method
 Can map HTTP requests based on method
 Allows same URL to be mapped to multiple methods
 Often used for form-based controllers (GET & POST)
 Essential to support RESTful resource URLs
 incl. PUT and DELETE
@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
}
 Copyright 2014 Pivotal. All rights reserved.
14
HTTP Status Code Support
 Web apps just use a handful of status codes
Success: 200 OK
Redirect: 302/303 for Redirects
Client Error: 404 Not Found
Server Error: 500 (such as unhandled Exceptions)
 RESTful applications use many additional codes to
communicate with their clients
 Add @ResponseStatus to controller method
 don't have to set status on HttpServletResponse
manually
 Copyright 2014 Pivotal. All rights reserved.
15
Common Response Codes
200
After a successful GET returning content
201
New resource was created on POST or PUT
Location header contains its URI
204
The response is empty  such as after
successful PUT or DELETE
404
405
Requested resource was not found
409
415
Conflict while making changes  such as
POSTing unique data that already exists
 Copyright 2014 Pivotal. All rights reserved.
HTTP method is not supported by resource
Request body type not supported
16
@ResponseStatus
@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()));
}
 IMPORTANT: When using @ResponseStatus
 void methods no longer imply a default view name!
 There will be no View at all
 This example gives a response with an empty body
 Copyright 2014 Pivotal. All rights reserved.
17
Determining Location Header
 Location header value must be full URL
 Determine based on request URL
 Controller shouldn't know host name or servlet path
 URL of created child resource usually a sub-path
 POST to http://www.myshop.com/store/orders
gives http://www.myshop.com/store/orders/123
 Can use Spring's UriTemplate for encoding where needed
private String getLocationForChildResource(HttpServletRequest request,
Object childIdentifier) {
StringBuffer url = request.getRequestURL();
UriTemplate template = new UriTemplate(url.append("/{childId}").toString());
return template.expand(childIdentifier).toASCIIString();
}
 Copyright 2014 Pivotal. All rights reserved.
18
@ResponseStatus & Exceptions
 Can also annotate exception classes with this
 Given status code used when exception is thrown from
controller method
@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";
}
 Copyright 2014 Pivotal. All rights reserved.
19
@ExceptionHandler
 For existing exceptions you cannot annotate, use
@ExceptionHandler method on controller
 Method signature similar to request handling method
 Also supports @ResponseStatus
@ResponseStatus(HttpStatus.CONFLICT) // 409
@ExceptionHandler({DataIntegrityViolationException.class})
public void conflict() {
// could add the exception, response, etc. as method params
}
 Copyright 2014 Pivotal. All rights reserved.
20
Topics in this Session
 REST introduction
 REST and Java
 Spring MVC support for RESTful applications
 Request/Response Processing
 Using MessageConverters
 Putting it all together
 RESTful clients with the RestTemplate
 Conclusion
 Copyright 2014 Pivotal. All rights reserved.
21
HttpMessageConverter
 Converts between HTTP request/response and object
 Various implementations registered by default when using
@EnableWebMvc or <mvc:annotation-driven/>
 XML (using JAXP Source or JAXB2 mapped object*)
 Feed data*, i.e. Atom/RSS
 Form-based data
 JSON*
* Requires 3rd party
libraries on classpath
 Byte[], String, BufferedImage
 Define HandlerAdapter explicitly to register other
HttpMessageConverters
You must use @EnableWebMvc/<mvc:annotation-driven> or register
custom converters to have any HttpMessageConverters defined at all!
 Copyright 2014 Pivotal. All rights reserved.
22
@RequestBody
 Annotate method parameter with @RequestBody
 Enables converters for request data
 Right converter chosen automatically
 Based on content type of request
 Order could be mapped from XML with JAXB2 or from JSON
with Jackson, for example
@RequestMapping(value="/orders/{id}", method=RequestMethod.PUT)
@ResponseStatus(HttpStatus.NO_CONTENT) // 204
public void updateOrder(@RequestBody Order updatedOrder,
@PathVariable("id") long id) {
// process updated order data and return empty response
orderManager.updateOrder(id, updatedOrder);
}
 Copyright 2014 Pivotal. All rights reserved.
23
@ResponseBody
 Use converters for response data by annotating method
with @ResponseBody
 Converter handles rendering to response
 No ViewResolver and View involved anymore!
@RequestMapping(value="/orders/{id}", method=RequestMethod.GET)
@ResponseStatus(HttpStatus.OK) // 200
public @ResponseBody Order getOrder(@PathVariable("id") long id) {
// Order class is annotated with JAXB2's @XmlRootElement
Order order= orderRepository.findOrderById(id);
// results in XML response containing marshalled order:
return order;
}
 Copyright 2014 Pivotal. All rights reserved.
24
Automatic Content Negotiation
 HttpMessageConverter selected automatically
 For @Request/ResponseBody annotated parameters
 Each converter has list of supported media types
 Allows multiple representations for a single controller
method
 Without affecting controller implementation
 Alternative to using Views
 Flexible media-selection
 Based on Accept header in HTTP request, or URL suffix,
or URL format parameter
See: http://spring.io/blog/2013/05/11/content-negotiation-using-spring-mvc
 Copyright 2014 Pivotal. All rights reserved.
25
Content Negotiation Sample
@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:
Host:www.myshop.com
www.myshop.com
Accept:
Accept:application/json,
application/json,......
 Copyright 2014 Pivotal. All rights reserved.
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
Using Views and Annotations - 1
 REST methods cannot return HTML, PDF, ...
 No message converter
 Views better for presentation-rich representations
 Need two methods on controller for same URL
 One uses a converter, the other a view
 Identify using produces attribute
 Similarly use consumes to differentiate methods
 Such as RESTful POST from an HTML form submission
@RequestMapping(value="/orders/{id}", method=RequestMethod.GET,
produces = {"application/json"})
@RequestMapping(value="/orders/{id}", method=RequestMethod.POST,
consumes = {"application/json"})
 Copyright 2014 Pivotal. All rights reserved.
27
Using Views and Annotations - 2
 Identify RESTful method with produces
 Call RESTful method from View method
 Implement all logic once in RESTful method
@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)); // Call RESTful method
return "orderDetails";
}
 Copyright 2014 Pivotal. All rights reserved.
28
Topics in this Session
 REST introduction
 REST and Java
 Spring MVC support for RESTful applications
 Request/Response Processing
 Using MessageConverters
 Putting it all together
 RESTful clients with the RestTemplate
 Conclusion
 Copyright 2014 Pivotal. All rights reserved.
29
Retrieving a Representation: GET
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);
}
 Copyright 2014 Pivotal. All rights reserved.
30
Creating a new Resource: POST - 1
POST
POST/store/orders/123/items
/store/orders/123/items
Host:
Host:www.myshop.com
www.myshop.com
Content-Type:
Content-Type:application/xml
application/xml
<item>
<item>
HTTP/1.1
HTTP/1.1201
201Created
Created
Date:
Date: 
Content-Length:
Content-Length:00
Location:
Location:http://myshop.com/store/order/123/items/abc
http://myshop.com/store/order/123/items/abc
</item>
</item>
@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()));
}
getLocationForChildResource was shown earlier
 Copyright 2014 Pivotal. All rights reserved.
31
Creating a new Resource: POST - 2
 Simplify POST
 Use @Value for request properties
 Use HttpEntity instead of HttpServletResponse
@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);
}
Controller is a POJO again  no HttpServlet* parameters
 Copyright 2014 Pivotal. All rights reserved.
32
Updating existing Resource: PUT
PUT
PUT/store/orders/123/items/abc
/store/orders/123/items/abc
Host:
Host:www.myshop.com
www.myshop.com
Content-Type:
Content-Type:application/xml
application/xml
<item>
<item>
HTTP/1.1
HTTP/1.1204
204No
NoContent
Content
Date:
Date: 
Content-Length:
Content-Length:00
</item>
</item>
@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);
}
 Copyright 2014 Pivotal. All rights reserved.
33
Deleting a Resource: DELETE
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);
}
 Copyright 2014 Pivotal. All rights reserved.
34
Spring 4.x
@RestController Simplification
@Controller
public class OrderController {
@RequestMapping(value="/orders/{id}", method=RequestMethod.GET)
public @ResponseBody Order getOrder(@PathVariable("id") long id) {
return orderRepository.findOrderById(id);
}
@RestController
public class OrderController {
@RequestMapping(value="/orders/{id}", method=RequestMethod.GET)
public Order getOrder(@PathVariable("id") long id) {
return orderRepository.findOrderById(id);
}
 Copyright 2014 Pivotal. All rights reserved.
No need for @ResponseBody on GET methods
35
Topics in this Session
REST introduction
REST and Java
Spring MVC support for RESTful applications
RESTful clients with the RestTemplate
Conclusion
 Copyright 2014 Pivotal. All rights reserved.
36
RestTemplate
 Provides access to RESTful services
 Supports URI templates, HttpMessageConverters and
custom execute() with callbacks
 Map or String... for vars, java.net.URI or String for URL
HTTP Method
DELETE
GET
RestTemplate Method
delete(String url, String urlVariables)
getForObject(String url, Class<T> responseType, String urlVariables)
HEAD
headForHeaders(String url, String urlVariables)
OPTIONS
optionsForAllow(String url, String urlVariables)
POST
postForLocation(String url, Object request, String urlVariables)
postForObject(String url, Object request, Class<T> responseType,
String uriVariables)
PUT
 Copyright 2014 Pivotal. All rights reserved.
put(String url, Object request, StringurlVariables)
37
Defining a RestTemplate
 Just call constructor in your code
RestTemplate template = new RestTemplate();
 Has default HttpMessageConverters
 Same as on the server, depending on classpath
 Or use external configuration
 To use Apache Commons HTTP Client, for example
<bean id="restTemplate" class="org.sfw.web.client.RestTemplate">
<property name="requestFactory">
<bean class="org.sfw.http.client.CommonsClientHttpRequestFactory"/>
</property>
</bean>
 Copyright 2014 Pivotal. All rights reserved.
38
RestTemplate Usage Examples
RestTemplate template = new RestTemplate();
String uri = "http://example.com/store/orders/{id}/items";
{id} = 1
// GET all order items for an existing order with ID 1:
OrderItem[] items = template.getForObject(uri, OrderItem[].class, "1");
// POST to create a new item
OrderItem item = // create item object
URI itemLocation = template.postForLocation(uri, item, "1");
// PUT to update the item
item.setAmount(2);
template.put(itemLocation, item);
// DELETE to remove that item again
template.delete(itemLocation);
Also supports HttpEntity, which makes adding headers to the HTTP
request very easy as well
 Copyright 2014 Pivotal. All rights reserved.
39
Topics in this Session
 REST introduction
 REST and Java
 Spring MVC support for RESTful applications
 Request/Response Processing
 Using MessageConverters
 Putting it all together
 RESTful clients with the RestTemplate
 Conclusion
 Copyright 2014 Pivotal. All rights reserved.
40
Conclusion
 REST is an architectural style that can be applied to
HTTP-based applications
 Useful for supporting diverse clients and building highly
scalable systems
 Java provides JAX-RS as standard specification
 Spring-MVC adds REST support using a familiar
programming model
 Extended by @Request-/@ResponseBody
 Use RestTemplate for accessing RESTful apps
 Copyright 2014 Pivotal. All rights reserved.
41
Lab
Restful applications with Spring MVC
 Copyright 2014 Pivotal. All rights reserved.
42
Spring JMS
Simplifying Messaging Applications
Introducing JmsTemplate and Spring's Listener
Container
 Copyright 2014 Pivotal. All rights reserved.
Topics in this Session
Introduction to JMS
Apache ActiveMQ
Configuring JMS Resources with Spring
Springs JmsTemplate
Sending Messages
Receiving Messages
Advanced Features
 Copyright 2014 Pivotal. All rights reserved.
Java Message Service (JMS)
 The JMS API provides an abstraction for accessing
Message Oriented Middleware
 Avoid vendor lock-in
 Increase portability
 JMS does not enable different MOM vendors to
communicate
 Need a bridge (expensive)
 Or use AMQP (standard msg protocol, like SMTP)
 See RabbitMQ
 Copyright 2014 Pivotal. All rights reserved.
JMS Core Components
Message
Destination
Connection
Session
MessageProducer
MessageConsumer
 Copyright 2014 Pivotal. All rights reserved.
JMS Message Types
 Implementations of the Message interface
TextMessage
ObjectMessage
MapMessage
BytesMessage
StreamMessage
 Copyright 2014 Pivotal. All rights reserved.
JMS Destination Types
 Implementations of the Destination interface
 Queue
 Point-to-point messaging
 Topic
 Publish/subscribe messaging
 Both support multiple producers and consumers
 Messages are different
 Let's take a closer look ...
 Copyright 2014 Pivotal. All rights reserved.
JMS Queues: Point-to-point
1. Message sent to queue
2. Message queued
3. Message consumed by single consumer
1
Producer
Consumer
1
2
2
Producer
 Copyright 2014 Pivotal. All rights reserved.
Queue
Consumer
JMS Topics: Publish-subscribe
1. Message sent to topic
2. Message optionally stored
3. Message distributed to all subscribers
1
Producer
Consumer
1
1
Producer
 Copyright 2014 Pivotal. All rights reserved.
Topic
Consumer
The JMS Connection
 A JMS Connection is obtained from a factory
Connection conn = connectionFactory.createConnection();
 Typical enterprise application:
 ConnectionFactory is a managed resource bound to JNDI
Properties env = new Properties();
// provide JNDI environment properties
Context ctx = new InitialContext(env);
ConnectionFactory connectionFactory =
(ConnectionFactory) ctx.lookup("connFactory");
 Copyright 2014 Pivotal. All rights reserved.
The JMS Session
 A Session is created from the Connection
 Represents a unit-of-work
 Provides transactional capability
Session session = conn.createSession(
boolean transacted, int acknowledgeMode);
// use session
if (everythingOkay) {
session.commit();
} else {
session.rollback();
}
 Copyright 2014 Pivotal. All rights reserved.
10
Creating Messages
 The Session is responsible for the creation of various
JMS Message types
session.createTextMessage("Some Message Content");
session.createObjectMessage(someSerializableObject);
MapMessage message = session.createMapMessage();
message.setInt("someKey", 123);
BytesMessage message = session.createBytesMessage();
message.writeBytes(someByteArray);
 Copyright 2014 Pivotal. All rights reserved.
11
Producers and Consumers
 The Session is also responsible for creating instances of
MessageProducer and MessageConsumer
producer = session.createProducer(someDestination);
consumer = session.createConsumer(someDestination);
 Copyright 2014 Pivotal. All rights reserved.
12
Topics in this Session
Introduction to JMS
Apache ActiveMQ
Configuring JMS Resources with Spring
Springs JmsTemplate
Sending Messages
Receiving Messages
Advanced Features
 Copyright 2014 Pivotal. All rights reserved.
13
JMS Providers
 Most providers of Message Oriented Middleware (MoM)
support JMS
 WebSphere MQ, Tibco EMS, Oracle EMS, JBoss AP,
SwiftMQ, etc.
 Some are Open Source, some commercial
 Some are implemented in Java themselves
 The lab for this module uses Apache ActiveMQ
 Copyright 2014 Pivotal. All rights reserved.
14
Apache ActiveMQ
 Open source message broker written in Java
 Supports JMS and many other APIs
 Including non-Java clients!
 Can be used stand-alone in production environment
 'activemq' script in download starts with default config
 Can also be used embedded in an application
 Configured through ActiveMQ or Spring configuration
 What we use in the labs
 Copyright 2014 Pivotal. All rights reserved.
15
Apache ActiveMQ Features
Support for:
 Many cross language clients & transport protocols
 Incl. excellent Spring integration
 Flexible & powerful deployment configuration
 Clustering incl. load-balancing & failover, ...
 Advanced messaging features
 Message groups, virtual & composite destinations, wildcards,
etc.
 Enterprise Integration Patterns when combined with Spring
Integration or Apache Camel
 from the book by Gregor Hohpe & Bobby Woolf
 Copyright 2014 Pivotal. All rights reserved.
16
Topics in this Session
Introduction to JMS
Apache ActiveMQ
Configuring JMS Resources with Spring
Springs JmsTemplate
Sending Messages
Receiving Messages
Advanced Features
 Copyright 2014 Pivotal. All rights reserved.
17
Configuring JMS Resources with Spring
 Spring enables decoupling of your application code
from the underlying infrastructure
 Container provides the resources
 Application is simply coded against the API
 Provides deployment flexibility
 use a standalone JMS provider
 use an application server to manage JMS resources
See: Spring Framework Reference  Using Spring JMS
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#jms
 Copyright 2014 Pivotal. All rights reserved.
18
Configuring a ConnectionFactory
 ConnectionFactory may be standalone
@Bean
public ConnectionFactory connectionFactory() {
ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory();
cf.setBrokerURL("tcp://localhost:60606");
return cf;
}
 Or retrieved from JNDI
@Bean
public ConnectionFactory connectionFactory() throws Exception {
Context ctx = new InitialContext();
return (ConnectionFactory) ctx.lookup("jms/ConnectionFactory");
}
<jee:jndi-lookup id="connectionFactory" jndi-name="jms/ConnectionFactory"/>
 Copyright 2014 Pivotal. All rights reserved.
19
Configuring Destinations
 Destinations may be standalone
@Bean
public Destination orderQueue() {
return new ActiveMQQueue( "order.queue" );
}
 Or retrieved from JNDI
@Bean
public Destination connectionFactory() throws Exception {
Context ctx = new InitialContext();
return (Destination) ctx.lookup("jms/OrderQueue");
}
<jee:jndi-lookup id=orderQueue jndi-name=jms/OrderQueue/>
 Copyright 2014 Pivotal. All rights reserved.
20
Topics in this Session
Introduction to JMS
Apache ActiveMQ
Configuring JMS Resources with Spring
Springs JmsTemplate
Sending Messages
Receiving Messages
Advanced Features
 Copyright 2014 Pivotal. All rights reserved.
21
Springs JmsTemplate
 The template simplifies usage of the API
Reduces boilerplate code
Manages resources transparently
Converts checked exceptions to runtime equivalents
Provides convenience methods and callbacks
NOTE: The AmqpTemplate (used with RabbitMQ) has an
almost identical API to the JmsTemplate  they offer
similar abstractions over very different products
 Copyright 2014 Pivotal. All rights reserved.
22
Exception Handling
 Exceptions in JMS are checked by default
 JmsTemplate converts checked exceptions to runtime
equivalents
Exception
javax.jms.
JMSException
 Copyright 2014 Pivotal. All rights reserved.
RuntimeException
converted into
org.springframework.jms.
JmsException
23
JmsTemplate Strategies
 The JmsTemplate delegates to two collaborators to
handle some of the work
 MessageConverter
 DestinationResolver
 Copyright 2014 Pivotal. All rights reserved.
24
MessageConverter
 The JmsTemplate uses a MessageConverter to convert
between objects and messages
 You only send and receive objects
 The default SimpleMessageConverter
handles basic types
String to TextMessage
Map to MapMessage
byte[] to BytesMessage
Serializable to ObjectMessage
Object
Message
Convertor
Message
NOTE: It is possible to implement custom converters by
implementing the MessageConverter interface
 Copyright 2014 Pivotal. All rights reserved.
25
XML MessageConverter
 XML is a common message payload
 ...but there is no XmlMessage in JMS
 Use TextMessage instead.
 MarshallingMessageConverter
 Plugs into Spring's OXM abstraction.
 You choose strategy
Spring OXM
jibx
JAXB
XStream
XML
Castor
Beans
DOM
SAX
 Copyright 2014 Pivotal. All rights reserved.
Object
Message
Convertor
XML
Message
26
MarshallingMessageConverter Example
@Bean public JmsTemplate jmsTemplate () {
JmsTemplate template = new JmsTemplate( connectionFactory );
template.setMessageConverter ( msgConverter() );
return template;
}
@Bean public MessageConverter msgConverter() {
MessageConverter converter = new MarshallingMessageConverter();
converter.setMarshaller ( marshaller() );
return converter;
JAXB2 Illustrated here,
}
other strategies
@Bean public Marshaller marshaller() {
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setContextPath ( example.app.schema );
return marshaller;
}
 Copyright 2014 Pivotal. All rights reserved.
available.
27
DestinationResolver
 Convenient to use destination names at
runtime
 DynamicDestinationResolver used by
default
 Resolves topic and queue names
 Not their Spring bean names
 JndiDestinationResolver also available
Name
Destination
Resolver
Destination
Destination resolveDestinationName(Session session,
String destinationName,
publish-subscribe?
boolean pubSubDomain)
true  Topic
throws JMSException;
false  Queue
 Copyright 2014 Pivotal. All rights reserved.
28
JmsTemplate configuration
 Must provide reference to ConnectionFactory
 via either constructor or setter injection
 Optionally provide other facilities
 setMessageConverter
 setDestinationResolver
 setDefaultDestination or setDefaultDestinationName
@Bean
public JmsTemplate jmsTemplate () {
JmsTemplate template = new JmsTemplate( connectionFactory );
template.setMessageConverter (  );
template.setDestinationResolver (  );
return template;
}
 Copyright 2014 Pivotal. All rights reserved.
29
Topics in this Session
Introduction to JMS
Apache ActiveMQ
Configuring JMS Resources with Spring
Springs JmsTemplate
Sending Messages
Receiving Messages
Advanced Features
 Copyright 2014 Pivotal. All rights reserved.
30
Sending Messages
 The template provides options
 Simple methods to send a JMS message
 One line methods that leverage the templates
MessageConverter
 Callback-accepting methods that reveal more of the
JMS API
 Use the simplest option for the task at hand
 Copyright 2014 Pivotal. All rights reserved.
31
Sending POJO
 A message can be sent in one single line
public class JmsOrderManager implements OrderManager {
@Autowired JmsTemplate jmsTemplate;
@Autowired Destination orderQueue;
No @Qualifier so Destination
is wired by name
public void placeOrder(Order order) {
String stringMessage = "New order " + order.getNumber();
jmsTemplate.convertAndSend("message.queue", stringMessage );
// use destination resolver and message converter
jmsTemplate.convertAndSend(orderQueue, order); // use message converter
jmsTemplate.convertAndSend(order); // use converter and default destination
}
}
 Copyright 2014 Pivotal. All rights reserved.
32
Sending JMS Messages
 Useful when you need to access JMS API
 eg. set expiration, redelivery mode, reply-to ...
public void sendMessage(final String msg) {
Lambda syntax
this.jmsTemplate.send( (session) -> {
TextMessage message = session.createTextMessage(msg);
message.setJMSExpiration(2000); // 2 seconds
return message;
});
}
 Copyright 2014 Pivotal. All rights reserved.
public interface MessageCreator {
public Message createMessage(Session session)
throws JMSException;
}
33
Topics in this Session
Introduction to JMS
Apache ActiveMQ
Configuring JMS Resources with Spring
Springs JmsTemplate
Sending Messages
Receiving Messages
Advanced Features
 Copyright 2014 Pivotal. All rights reserved.
34
Synchronous Message Reception
 JmsTemplate can also receive messages
 but methods are blocking (synchronous)
 optional timeout: setReceiveTimeout()
public void receiveMessages() {
// use message converter and destination resolver
String s = (String) jmsTemplate.receiveAndConvert("message.queue");
// use message converter
Order order1 = (Order) jmsTemplate.receiveAndConvert(orderQueue);
// handle JMS native message from default destination
ObjectMessage orderMessage = (ObjectMessage) jmsTemplate.receive();
Order order2 = (Order) orderMessage.getObject();
}
 Copyright 2014 Pivotal. All rights reserved.
35
Synchronous Message Exchange
 JmsTemplate also implements a request/reply pattern
 Sending a message and blocking until a reply has been
received (also uses receiveTimeout)
 Manage a temporary reply queue automatically by default
public void processMessage(String msg) {
Message reply = jmsTemplate.sendAndReceive("message.queue",
(session) -> {
return session.createTextMessage(msg);
});
// handle reply
}
 Copyright 2014 Pivotal. All rights reserved.
36
Springs MessageListener Containers
 Spring provides containers for asynchronous JMS
reception
 SimpleMessageListenerContainer
 Uses plain JMS client API
 Creates a fixed number of Sessions
 DefaultMessageListenerContainer
 Adds transactional capability
 Many configuration options available for each container
type
 Copyright 2014 Pivotal. All rights reserved.
37
Quick Start
Steps for Asynchronous Message Handling
1) Define POJO / Bean to process Message
2) Define JmsListenerContainerFactory / Enable Annotations
 Copyright 2014 Pivotal. All rights reserved.
38
Step 1  Define POJO / Bean to
Process Message
Spring 4.1
 Define a POJO to process message
 Note: No references to JMS
public class OrderServiceImpl {
@JmsListener(destination=queue.order)
@SendTo(queue.confirmation)
public OrderConfirmation order(Order o) {  }
}
 Define as a Spring bean using XML, JavaConfig, or
annotations as preferred
 @JmsListener enables a JMS message consumer for the
method
 @SendTo defines response destination (optional)
 Copyright 2014 Pivotal. All rights reserved.
39
Step 2  Define
JmsListenerContainerFactory to use
Spring 4.1
 JmsListenerContainerFactory: separates JMS API from
your POJO:
@Configuration @EnableJms
public class MyConfiguration {
Enable annotations
Default container name
@Bean
public DefaultJmsListenerContainerFactory
Set
jmsListenerContainerFactory () {
ConnectionFactory
DefaultJmsListenerContainerFactory cf =
new DefaultJmsListenerContainerFactory( );
cf.setConnectionFactory(connectionFactory());
...
return cf;
}
Many settings available:
}
TransactionManager, TaskExecutor, ContainerType ...
 Copyright 2014 Pivotal. All rights reserved.
40
Spring 4.1
@JmsListener features
 By default, the container with name
jmsListenerContainerFactory is used
public class OrderServiceImpl {
@JmsListener(containerFactory=myFactory,
destination=orderConfirmation)
public void process(OrderConfirmation o) {  }
}
 Can also set a custom concurrency or a selector
public class OrderServiceImpl {
@JmsListener(selector=type = 'Order',
concurrency=2-10, destination = order)
public OrderConfirmation order(Order o) {  }
}
 Copyright 2014 Pivotal. All rights reserved.
41
Step 2: JMS XML Namespace support
 Equivalent Capabilities
 The containerId attribute exposes the configuration of the
container with that name
 Same configuration options available
 task execution strategy, concurrency, container type,
transaction manager and more
<jms:annotation-driven/>
<jms:listener-container
containerId="jmsMessageContainerFactory"
connection-factory="myConnectionFactory"/>
<bean id=orderService class=org.acme.OrderService/>
 Copyright 2014 Pivotal. All rights reserved.
42
100% XML Equivalent
 Use jms:listener-container with embedded jms:listeners
 Allows multiple listeners per container
 Same configuration options available
<jms:listener-container connection-factory="myConnectionFactory">
<jms:listener destination="order.queue"
ref="orderService"
method="order"
response-destination="confirmation.queue" />
<jms:listener destination="confirmation.queue"
ref="orderService"
method="confirm" />
</jms:listener-container>
<bean id=orderService class=org.acme.OrderService/>
 Copyright 2014 Pivotal. All rights reserved.
43
Messaging: Pros and Cons
 Advantages
Resilience, guaranteed delivery
Asynchronous support
Application freed from messaging concerns
Interoperable  languages, environments
 Disadvantages
 Requires additional third-party software
 Can be expensive to install and maintain
 More complex to use  but not with JmsTemplate!
Spring Enterprise  4 day course on application integration
 Copyright 2014 Pivotal. All rights reserved.
44
Lab
Sending and Receiving Messages in
a Spring Application
 Copyright 2014 Pivotal. All rights reserved.
45
Topics in this Session
Introduction to JMS
Apache ActiveMQ
Configuring JMS Resources with Spring
Springs JmsTemplate
Sending Messages
Receiving Messages
Advanced Features
 Copyright 2014 Pivotal. All rights reserved.
46
Advanced Option: CachingConnectionFactory
 JmsTemplate aggressively closes and reopens
resources like Sessions and Connections
 Normally these are cached by connection factory
 Without caching can cause lots of overhead
 Resulting in poor performance
 Use our CachingConnectionFactory to add caching
within the application if needed
<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>
 Copyright 2014 Pivotal. All rights reserved.
47
Finishing Up
Course Completed
What's Next?
 Copyright 2014 Pivotal. All rights reserved.
What's Next
 Congratulations, we've finished the course
 What to do next?
Certification
Other courses
Resources
Evaluation
 Check-out optional sections on Remoting and SOAP
web-services
 Copyright 2014 Pivotal. All rights reserved.
Certification
 Computer-based exam
 50 multiple-choice questions
 90 minutes
 Passing score: 76% (38 questions answered successfully)
 Preparation
 Review all the slides
 Redo the labs
 Study Guide:
http://www.pivotal.io/files/pdfs/pivotal_studyguide_corespring.docx
 Copyright 2014 Pivotal. All rights reserved.
Certification: Questions
Sample question
 Statements
a. An application context holds Spring beans
b. An application context manages bean scope
c. Spring provides many types of application context
 Pick the correct response:
1. Only a. is correct
2. Both a. and c. are correct
3. All are correct
4. None are correct
 Copyright 2014 Pivotal. All rights reserved.
Certification: Logistics
 Where?
 At any Pearson VUE Test Center
 Most large or medium-sized cities
 See http://www.pearsonvue.com/vtclocator
 How?
 At the end of the class, you will receive a certification
voucher by email
 Make an appointment
 Give them the voucher when you take the test
 For any further inquiry, you can write to
 education@pivotal.io
 Copyright 2014 Pivotal. All rights reserved.
Other courses
 Many courses available
Web Applications with Spring
Enterprise Spring
JPA with Spring
What's New in Spring
Groovy and Grails
Cloud Foundry
Hadoop, Gemfire, Rabbit MQ 
 See http://www.pivotal.io/training
 Copyright 2014 Pivotal. All rights reserved.
Spring Web
 Four-day workshop
 Making the most of Spring in the web layer
Spring MVC
Spring Web Flow
REST using MVC and AJAX
Security of Web applications
Mock MVC testing framework
 Spring Web Application Developer certification
 Copyright 2014 Pivotal. All rights reserved.
Spring Enterprise
 Building loosely coupled,event-driven architectures
 Separate processing, communications & integration
 Formerly Enterprise Integration & Web Services
 Four day course covering
Concurrency
Advanced transaction management
SOAP Web Services with Spring WS
REST Web Services with Spring MVC
Spring Batch
Spring Integration
 Copyright 2014 Pivotal. All rights reserved.
JPA with Spring
 Three day course covering
Using JPA with Spring and Spring Transactions
Implement inheritance and relationships with JPA
Discover how JPA manages objects
Go more in depth on locking with JPA
Advanced features such as interceptors, caching and
batch updates
 Copyright 2014 Pivotal. All rights reserved.
Developing Applications with Cloud Foundry
 Three day course covering
Application deployment to Cloud Foundry
Cloud Foundry Concepts
Deployment using cf tool or an IDE
Accessing and defining Services
Using and customizing Buildpacks
Design considerations: 12 Factor
JVM Application specifics, using Spring Cloud
 Copyright 2014 Pivotal. All rights reserved.
10
Pivotal Support Offerings
 Global organization provides 24x7 support
 How to Register: http://tinyurl.com/piv-support
 Premium and Developer support offerings:
 http://www.pivotal.io/support/offerings
 http://www.pivotal.io/support/oss
 Both Pivotal App Suite and Open Source products
 Support Portal: https://support.pivotal.io
 Community forums, Knowledge Base, Product documents
 Copyright 2014 Pivotal. All rights reserved.
11
Pivotal Consulting
 Custom consulting engagement?
 Contact us to arrange it
 http://www.pivotal.io/contact/spring-support
 Even if you don't have a support contract!
 Pivotal Labs
 Agile development experts
 Assist with design, development and product management
 http://www.pivotal.io/agile
 http://pivotallabs.com
 Copyright 2014 Pivotal. All rights reserved.
12
Resources
 The Spring reference documentation
 http://spring.io/docs
 Already 800+ pages!
 The official technical blog
 http://spring.io/blog
 Stack Overflow  Active Spring Forums
 http://stackoverflow.com
 Copyright 2014 Pivotal. All rights reserved.
13
Resources (2)
 You can register issues on our Jira repository
 https://jira.spring.io
 The source code is available here
 https://github.com/spring-projects/spring-framework
 Copyright 2014 Pivotal. All rights reserved.
14
Thank You!
We hope you enjoyed the course
Please fill out the evaluation form
http://tinyurl.com/mylearneval
 Copyright 2014 Pivotal. All rights reserved.
15
Object Relational
Mapping
Using OR Mapping in the Enterprise
Fundamental Concepts and Concerns
 Copyright 2014 Pivotal. All rights reserved.
Topics in this session
 The Object/Relational mismatch
 ORM in context
 Benefits of O/R Mapping
 Copyright 2014 Pivotal. All rights reserved.
The Object/Relational Mismatch (1)
 A domain object model is designed to serve the needs
of the application
 Organize data into abstract concepts that prove useful to
solving the domain problem
 Encapsulate behavior specific to the application
 Under the control of the application developer
 Copyright 2014 Pivotal. All rights reserved.
The Object/Relational Mismatch (2)
 Relational models relate business data and are typically
driven by other factors:
 Performance
 Space
 Furthermore, a relational database schema often:
 Predates the application
 Is shared with other applications
 Is managed by a separate DBA group
 Copyright 2014 Pivotal. All rights reserved.
Object/Relational Mapping
 Object/Relational Mapping (ORM) engines exist to
mitigate the mismatch
 Spring supports all of the major ones:
 Hibernate
 EclipseLink
 Other JPA (Java Persistence API) implementations, such
as OpenJPA
 This session will focus on Hibernate
 Copyright 2014 Pivotal. All rights reserved.
Topics in this session
 The Object/Relational Mismatch
 ORM in context
 Benefits of modern-day ORM engines
 Copyright 2014 Pivotal. All rights reserved.
ORM in context
 For the Reward Dining domain
 The database schema already exists
 Several applications share the data
Reward
Network
Legacy
Apps?
 Copyright 2014 Pivotal. All rights reserved.
Account Management
Portal
Database
SQL
Merchant
Reporting
Mapping to a legacy
schema is much harder
than starting fresh.
O/R Mismatch: Granularity (1)
 In an object-oriented language, cohesive fine-grained
classes provide encapsulation and express the domain
naturally
 In a database schema, granularity is typically driven by
normalization and performance considerations
 Copyright 2014 Pivotal. All rights reserved.
O/R Mismatch: Granularity (2)
just one example
Domain Model in Java
Customer
- customerId
- firstName
- lastName
Address
- streetNumber
- streetName
- city
- state
- zipCode
 Copyright 2014 Pivotal. All rights reserved.
Table in Database
CUSTOMER
EmailAddress
PhoneNumber
CUST_ID <<PK>>
FIRST_NAME
LAST_NAME
EMAIL
PHONE
STREET_NUMBER
STREET_NAME
CITY
STATE
ZIP_CODE
O/R Mismatch: Identity (1)
 In Java, there is a difference between Object identity and
Object equivalence:
 x == y
 x.equals(y)
identity (same memory address)
equivalence
 In a database, identity is based solely on primary keys:
 x.getEntityId().equals(y.getEntityId())
 Copyright 2014 Pivotal. All rights reserved.
10
O/R Mismatch: Identity (2)
 When working with persistent Objects, the identity
problem leads to difficult challenges
 Two different Java objects may correspond to the same
relational row
 But Java says they are not equal
 Some of the challenges:
 Implement equals() to accommodate this scenario
 Determine when to update and when to insert
 Avoid duplication when adding to a Collection
 Copyright 2014 Pivotal. All rights reserved.
11
O/R Mismatch:
Inheritance and Associations (1)
 In an object-oriented language:
 IS-A relations are modeled with inheritance
 HAS-A relations are modeled with composition
 In a database schema, relations are limited to what can
be expressed by foreign keys
 Copyright 2014 Pivotal. All rights reserved.
12
O/R Mismatch:
Inheritance and Associations (2)
 Bi-directional associations are common in a domain
model (e.g. Parent-Child)
 This can be modeled naturally in each Object
 In a database:
 One side (parent) provides a primary-key
 Other side (child) provides a foreign-key reference
 For many-to-many associations, the database schema
requires a join table
 Copyright 2014 Pivotal. All rights reserved.
13
Topics in this session
 The Object/Relational Mismatch
 ORM in Context
 Benefits of O/R Mapping
 Copyright 2014 Pivotal. All rights reserved.
14
Benefits of ORM
Object Query Language
Automatic Change Detection
Persistence by Reachability
Caching
 Per-Transaction (1st Level)
 Per-DataSource (2nd Level)
 Copyright 2014 Pivotal. All rights reserved.
15
Object Query Language
 When working with domain objects, it is more natural to
query based on objects.
 Query with SQL:
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
 Query with object properties and associations:
SELECT c FROM Customer c WHERE c.address.zipCode = 12345
 Copyright 2014 Pivotal. All rights reserved.
16
Automatic Change Detection
 When a unit-of-work completes, all modified state will be
synchronized with the database.
Service
Repository1
invoke(input)
Repository2
UnitOfWork
begin
find
find
modify
commit
output
 Copyright 2014 Pivotal. All rights reserved.
flush
Database
17
Persistence by Reachability
 When a persistent object is being managed, other
associated objects may become managed transparently:
Order order = orderRepository.findByConfirmationId(cid);
// order is now a managed object  retrieved via ORM
LineItem item = new LineItem(..);
order.addLineItem(item);
// item is now a managed object  reachable from order
 Copyright 2014 Pivotal. All rights reserved.
18
(Un)Persistence by Reachability
= Make Transient
 The same concept applies for deletion:
Order order = orderRepository.findByConfirmationId(cid);
// order is now a managed object  retrieved via ORM
List<LineItem> items = order.getLineItems();
Item becomes transient
for (LineItem item : items) {
if (item.isCancelled()) { order.removeItem(item); }
// the database row for this item will be deleted
Order and all its
}
items now transient
if (order.isCancelled()) {
orderRepository.remove(order);
// all item rows for the order will be deleted
}
 Copyright 2014 Pivotal. All rights reserved.
19
Caching
 The first-level cache (1LC) is scoped at the level of a
unit-of-work
 When an object is first loaded from the database within a
unit-of-work it is stored in this cache
 Subsequent requests to load that same entity from the
database will hit this cache first
 The second-level cache (2LC) is scoped at the level of
the SessionFactory
 Reduce trips to database for read-heavy data
 Especially useful when a single application has exclusive
access to the database
 Copyright 2014 Pivotal. All rights reserved.
20
Summary
 Managing persistent objects is hard
 Especially if caching is involved
 Especially on a shared, legacy schema with existing
applications
 The ORM overcomes some of these problems
 Automatic change detection, queries, caching
 Ideal if your application owns its database
 It is not a magic-bullet
 JDBC may still be better for some tables/queries
 True distributed cache coherency is very hard
 Design for it and test performance
 Copyright 2014 Pivotal. All rights reserved.
21
ORM With Spring
and Hibernate
Configuring Hibernate to work with Spring
Equivalent to JPA section but using Hibernate
Session API
 Copyright 2014 Pivotal. All rights reserved.
Topics in this session
 Introduction to Hibernate
 Mapping
 Querying
 Configuring a Hibernate SessionFactory
 Implementing Native Hibernate DAOs
 Exception Mapping
 Copyright 2014 Pivotal. All rights reserved.
Introduction to Hibernate
 A SessionFactory is a thread-safe, shareable object
that represents a single data source
 Provides access to a transactional Session
 Ideal candidate for a singleton Spring bean
 Hibernates Session is a stateful object representing a
Session
unit-of-work
 Often corresponds at a higher-level to a JDBC Connection
 Manages persistent objects within the unit-of-work
 Acts as a transaction-scoped cache (1LC)
 Copyright 2014 Pivotal. All rights reserved.
Hibernate Mapping
 Hibernate requires metadata
 for mapping classes to database tables
 and their properties to columns
 Metadata can be annotations or XML
 This session will present JPA annotations
 XML shown in the appendix
Customer
firstName: String
dob: Date
...
???
Customer
PK
FIRST_NAME
DATE_OF_BIRTH
 Copyright 2014 Pivotal. All rights reserved.
Annotations support in Hibernate
 Hibernate supports all JPA 2 annotations
 Since Hibernate 3.5
 javax.persistence.*
 Suitable for most needs
 Hibernate Specific Extensions
 In addition to JPA annotations
 For behavior not supported by JPA
 Performance enhancements specific to Hibernate
 Less important since JPA 2
 Copyright 2014 Pivotal. All rights reserved.
What can you Annotate?
 Classes
 Applies to the entire class (such as table properties)
 Data-members
 Typically mapped to a column
 By default, all data-members treated as persistent
 Mappings will be defaulted
 Unless annotated with @Transient (non-persistent)
 All data-members accessed directly
 No accessors (getters/setters) needed
 Any accessors will not be used
 This is called field access
 Copyright 2014 Pivotal. All rights reserved.
Mapping simple data-members: Field Access
@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;
@Column
@Column (name=first_name)
(name=first_name)
private
private String
String firstName;
firstName;
Mark as an entity
Optionally override
table name
Mark id-field (primary
key)
Optionally override
column names
@Transient
@Transient
private
private User
User currentUser;
currentUser;
Not stored in database
public
public void
void setFirstName(String
setFirstName(String firstName)
firstName) {{
this.firstName
this.firstName == firstName;
firstName;
}} Only @Entity and @Id are mandatory
...
...
Setters and not used by
Hibernate
 Copyright 2014 Pivotal. All rights reserved.
Mapping simple Properties
- Traditional Approach
Must place @Id on the
getter method
@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; }}
Other annotations now also
placed on getter methods
@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
 Copyright 2014 Pivotal. All rights reserved.
public
public void
void setFirstName(String
setFirstName(String name)
name)
{{ this.firstName
this.firstName == name;
name; }}
}}
Mapping collections with annotations
@Entity
@Entity
@Table(name
@Table(name== T_CUSTOMER
T_CUSTOMER))
public
public class
class Customer
Customer {{
@Id
@Id
@Column
@Column (name
(name=cust_id
=cust_id))
Propagate all operations
to the underlying objects
private
private Long
Long id;
id;
@OneToMany(
@OneToMany(cascade=CascadeType.ALL)
cascade=CascadeType.ALL)
@JoinColumn
@JoinColumn (name
(name=cid
=cid))
private
private Set<Address>
Set<Address> addresses;
addresses;
Foreign key in
Address table
JoinTable also supported, more
commonly used in
@ManyToMany associations
 Copyright 2014 Pivotal. All rights reserved.
Accessing Persistent Data
 Hibernate's key class is the Session
 Provides methods to manipulate entities
 persist, delete, get 
 Create queries using Hibernate Query Language
 Manages transactions
 JPA defines a similar class: EntityManager
 Sessions more popular than EntityManagers
 Already widely used before JPA
 Common to write hybrid applications
Session
 JPA annotations, Hibernate API and HQL
 But remember: it is not a JPA application
 Copyright 2014 Pivotal. All rights reserved.
10
Hibernate Querying
 Hibernate provides several options for accessing data
 Retrieve an object by primary key
 Query for objects with the Hibernate Query Language
(HQL)
 Query for objects using Criteria Queries
 Execute standard SQL
 Copyright 2014 Pivotal. All rights reserved.
11
Hibernate Querying: by Primary Key
 To retrieve an object by its database identifier simply call
get(..) on the Session
Long custId = new Long(123);
Customer customer = (Customer) session.get(Customer.class, custId);
returns null if no object exists for the identifier
 Copyright 2014 Pivotal. All rights reserved.
12
Hibernate Querying: HQL
 To query for objects based on properties or associations
use HQL
 Pre Java 5 API, not type aware
Query query = session.createQuery(
from Customer c where c.address.city = :city);
query.setString(city, Chicago);
List customers = query.list();
No generics
// Or if expecting a single result
Customer customer = (Customer) query.uniqueResult();
Must cast
 Copyright 2014 Pivotal. All rights reserved.
13
Topics in this session
Introduction to Hibernate
Configuring a Hibernate SessionFactory
Implementing Native Hibernate DAOs
Exception Mapping
 Copyright 2014 Pivotal. All rights reserved.
14
Configuring a SessionFactory (1)
 Hibernate implementations of data access code require
access to the SessionFactory
 The SessionFactory requires
 DataSource (local or container-managed)
 Mapping metadata
 Spring provides a FactoryBean for configuring a
shareable SessionFactory
 Supports Hibernate V4 from Spring 3
 There are different versions in hibernate2, hibernate3,
hibernate4 packages
 Copyright 2014 Pivotal. All rights reserved.
15
Configuring a SessionFactory (2)
OrderServiceImpl
Hibernate
OrderRepository
Annotation
Session
FactoryBean
creates
SessionFactory
DataSource
Mapping
Metadata
 Copyright 2014 Pivotal. All rights reserved.
16
SessionFactory and Annotated Classes
<bean id=orderRepository class=example.HibernateOrderRepository>
<property name=sessionFactory ref=sessionFactory/>
Spring 3.1
</bean>
<bean id=sessionFactory class=org.springframework.orm.
hibernate4.annotation.LocalSessionFactoryBean>
<property name=dataSource ref=dataSource/>
<property name=annotatedClasses>
<list>
<value>example.Customer</value>
<value>example.Address</value>
</list>
</property>
</bean>
Entities listed one by one
- wildcards not supported
<jee:jndi-lookup id=dataSource jndi-name=java:comp/env/jdbc/orders/>
Prior to Spring 3.1 use the AnnotationSessionFactoryBean
 Copyright 2014 Pivotal. All rights reserved.
17
SessionFactory and Scanned Packages
 Or use packagesToScan attribute
Spring 3.1
 Wildcards are supported
 Also scans all sub-packages
<bean id=sessionFactory class=org.springframework.orm.hibernate4.
annotation.LocalSessionFactoryBean>
<property name=dataSource ref=dataSource/>
<property name=packagesToScan>
<list>
<value>com/springsource/*/entity</value>
</list>
</property>
</bean>
<jee:jndi-lookup id=dataSource jndi-name=java:comp/env/jdbc/orders/>
 Copyright 2014 Pivotal. All rights reserved.
18
Topics in this session
Introduction to Hibernate
Configuring a Hibernate SessionFactory
Implementing Native Hibernate DAOs
Exception Mapping
 Copyright 2014 Pivotal. All rights reserved.
19
Implementing Native Hibernate DAOs (1)
 Since Hibernate 3.1+
 Hibernate provides hooks so Spring can manage
transactions and Sessions in a transparent fashion
 Use AOP for transparent exception translation to Springs
DataAccessException hierarchy
 No dependency on Spring in your DAO implementations
 No longer require HibernateTemplate (obsolete)
 Copyright 2014 Pivotal. All rights reserved.
20
Spring-Managed Transactions
and Sessions (1)
 Transparently participate in Spring-driven transactions
 use one of Springs Factory Beans to build the
SessionFactory
 Provide it to the data access code
 dependency injection
 Define a transaction manager
 HibernateTransactionManager
 JtaTransactionManager
 Copyright 2014 Pivotal. All rights reserved.
21
Spring-managed Transactions
and Sessions (2)
 The code  with no Spring dependencies
public class HibernateOrderRepository implements OrderRepository {
private SessionFactory sessionFactory;
public HibernateOrderRepository(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
dependency injection
...
public Order findById(long orderId) {
// use the Spring-managed Session
Session session = this.sessionFactory.getCurrentSession();
return (Order) session.get(Order.class, orderId);
}
use existing session
}
 Copyright 2014 Pivotal. All rights reserved.
22
Spring-managed Transactions
and Sessions (3)
 The configuration
<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>
or use JtaTransactionManager if needed
 Copyright 2014 Pivotal. All rights reserved.
23
How it Works (Hibernate)
Spring AOP Proxy
invoke(input)
Spring
Hibernate
TransactionInterceptor
OrderRepository
begin
commit
OrderServiceImpl
get order data
Hibernate
TransactionManager
new
session
close
session
SessionFactory
 Copyright 2014 Pivotal. All rights reserved.
getCurrentSession
OrderRepository
24
How it Works (JTA)
invoke(input)
Spring
Hibernate
TransactionInterceptor
OrderRepository
Service
proxy handles
transaction begin
Spring AOP Proxy
commit
HibernateTransaction
Manager
begin
txn
JTA
 Copyright 2014 Pivotal. All rights reserved.
commit
txn
join
txn
OrderServiceImpl
get order
data
OrderRepository
getCurrent
Session
SessionFactory
find
order
Session
25
Spring-managed Transactions
and Sessions (4)
 Best practice: use read-only transactions when you don't
write anything to the database
 Prevents Hibernate from flushing its session
 possibly dramatic performance improvement
 Also marks JDBC Connection as read-only
 provides additional safeguards with some databases
 for example: Oracle only accepts SELECT statements
@Transactional(readOnly=true)
public List<RewardConfirmation> listRewardsFrom(Date d) {
// read-only, atomic unit-of-work
}
 Copyright 2014 Pivotal. All rights reserved.
26
Topics in this session
Introduction to Hibernate
Configuring a Hibernate SessionFactory
Implementing Native Hibernate DAOs
Exception Mapping
 Copyright 2014 Pivotal. All rights reserved.
27
Transparent Exception Translation
 Used as-is, the previous DAO implementation can throw
an access specific HibernateException
 Propagate up to the caller
 service layer or other users of the DAOs
 Introduces dependency on specific persistence solution
that should not exist
 Service layer knows you are using Hibernate
 Can use AOP to convert them to Springs rich
DataAccessException hierarchy
 Hides access technology used
 Copyright 2014 Pivotal. All rights reserved.
28
Exception Translation
 Using @Repository
Spring provides this capability out of the box
 Annotate with @Repository
 Define a Spring-provided BeanPostProcessor
@Repository
public class HibernateOrderRepository implements OrderRepository {
...
}
<bean class=org.springframework.dao.annotation.
PersistenceExceptionTranslationPostProcessor/>
 Copyright 2014 Pivotal. All rights reserved.
29
Exception Translation - XML
 Can't always use annotations
 For example with a third-party repository
 Use XML to configure instead
public class HibernateOrderRepository implements OrderRepository {
...
No annotations
}
<bean id=persistenceExceptionInterceptor
class=org.springframework.dao.support.
PersistenceExceptionTranslationInterceptor/>
<aop:config>
<aop:advisor pointcut=execution(* *..OrderRepository+.*(..))
advice-ref=persistenceExceptionInterceptor />
</aop:config>
 Copyright 2014 Pivotal. All rights reserved.
30
Summary
 Use Hibernate and/or JPA to define entities
 Repositories have no Spring dependency
 Use Spring to configure Hibernate session factory
 Works with Spring-driven transactions
 Optional translation to DataAccessExceptions
Spring-Hibernate  3 day in-depth Hibernate course
 Copyright 2014 Pivotal. All rights reserved.
31
Lab
Using Hibernate with Spring
 Copyright 2014 Pivotal. All rights reserved.
32
Introduction to
Spring Remoting
Simplifying Distrubuted Applications
Painless RMI and HTTP Tunnelling
 Copyright 2014 Pivotal. All rights reserved.
Topics in this Session
Introduction to Remoting
Spring Remoting Overview
Spring Remoting and RMI
HttpInvoker
 Copyright 2014 Pivotal. All rights reserved.
Local access
 So far, you have seen how to access objects locally
ClientService
findAccount(...)
Account
AccountService
 Copyright 2014 Pivotal. All rights reserved.
Remote access
 What if those 2 objects run in some separate JVMs?
ClientService
jvm 1
findAccount(...)
Account
AccountService
jvm 2
In this module, only Java-to-Java communication is addressed
(as opposed to remote access using Web Services or JMS)
 Copyright 2014 Pivotal. All rights reserved.
The RMI Protocol
 Standard Java remoting protocol
 Remote Method Invocation
 Java's version of RPC
 Server-side exposes a skeleton
 Client-side invokes methods on a stub (proxy)
 Java serialization is used for marshalling
 Copyright 2014 Pivotal. All rights reserved.
Working with plain RMI
 RMI violates separation of concerns
 Couples business logic to remoting infrastructure
 For example, with RMI:
 Service interface extends Remote
 Client must catch RemoteExceptions
 Technical Java code needed for binding and retrieving
objects on the RMI server
 Copyright 2014 Pivotal. All rights reserved.
Traditional RMI
 The RMI model is invasive
 server and client code is coupled to the framework
Client must catch
RemoteExceptions
Must extend RMI Remote
'marker' interface
Server Process
Client Process
Remote
<<interface>>
TransferService
<<interface>>
Teller
Desktop
UI
 Copyright 2014 Pivotal. All rights reserved.
TransferServic
e
Stub
transfer(..)
Skeleton
TransferServiceImp
l
RMI and Serialization
 RMI relies on Object Serialization
 Objects transferred using RMI should implement 'marker'
interface Serializable
 Marker interface, no method to be implemented
import java.io.Serializable;
ClientService
public class Account implements Serializable {
private static final long
Account
serialVersionUID = 9123849272938193534L;
AccountService
 Copyright 2014 Pivotal. All rights reserved.
...
}
Topics in this Session
Introduction to Remoting
Spring Remoting Overview
Spring Remoting and RMI
HttpInvoker
 Copyright 2014 Pivotal. All rights reserved.
Goals of Spring Remoting
 Hide plumbing code
 Configure and expose services declaratively
 Support multiple protocols in a consistent way
 Copyright 2014 Pivotal. All rights reserved.
10
Hide the Plumbing
 Spring provides exporters to handle server-side
requirements
 Binding to registry or exposing an endpoint
 Conforming to a programming model if necessary
 Spring provides FactoryBeans that generate proxies to
handle client-side requirements
 Communicate with the server-side endpoint
 Convert remote exceptions to a runtime hierarchy
 Copyright 2014 Pivotal. All rights reserved.
11
Service Exporters
 Spring provides service exporters to enable declarative
exposing of existing services
Accessible from remote clients
<<interface>>
Spring
ServiceExporter
Teller
Controller
 Copyright 2014 Pivotal. All rights reserved.
TransferServic
e
transfer(..)
transfer(..)
TransferServiceImp
l
12
Client Proxies
 Dynamic proxies generated by Spring communicate with
the service exporter
Client Process
Server Process
Teller
Controller
<<interface>>
TransferServic
e
Teller
Desktop
UI
Spring
Proxy
transfer(..)
Spring
ServiceExporter
<<interface>>
TransferServic
e
TransferServiceImp
l
Generated by a Spring FactoryBean
 Copyright 2014 Pivotal. All rights reserved.
13
A Declarative Approach
 Uses a configuration-based approach
 No code to write
 On the server side
 Expose existing services with NO code changes
 On the client side
 Invoke remote methods from existing code
 Take advantage of polymorphism by using dependency
injection
 Migrate between remote vs. local deployments
 Copyright 2014 Pivotal. All rights reserved.
14
Consistency across Protocols
 Springs exporters and proxy FactoryBeans bring the
same approach to multiple protocols
 Provides flexibility
 Promotes ease of adoption
 On the server side
 Expose a single service over multiple protocols
 On the client side
 Switch easily between protocols
 Copyright 2014 Pivotal. All rights reserved.
15
Topics in this Session
Introduction to Remoting
Spring Remoting Overview
Spring Remoting and RMI
HttpInvoker
 Copyright 2014 Pivotal. All rights reserved.
16
Springs RMI Service Exporter
 Transparently expose an existing POJO service to the
RMI registry
 No need to write the binding code
 Avoid traditional RMI requirements
 Service interface does not extend Remote
 Service class is a POJO
Transferred objects still need to implement the
java.io.Serializable interface
 Copyright 2014 Pivotal. All rights reserved.
17
Configuring the RMI Service Exporter
 Start with an existing POJO service
Server
<bean id=transferService class=app.impl.TransferServiceImpl>
<property name=accountRepository ref=accountRepository/>
</bean>
 Define a bean to export it
<bean class=org.springframework.remoting.rmi.RmiServiceExporter>
<property name=serviceName value=transferService/>
<property name=serviceInterface value=app.TransferService/>
<property name=service ref=transferService/>
<property name=registryPort value=1096/>
Binds to rmiRegistry
</bean>
as transferService
registryPort defaults to 1099
 Copyright 2014 Pivotal. All rights reserved.
18
Springs RMI Proxy Generator
 Spring provides FactoryBean implementation that
generates RMI client-side proxy
 Simpler to use than traditional RMI stub
 Converts checked RemoteExceptions into Springs runtime
hierarchy of RemoteAccessExceptions
 Dynamically implements the business interface
Exception
java.io.
RemoteException
 Copyright 2014 Pivotal. All rights reserved.
RuntimeException
converted into
org.springframework.remoting.
RemoteAccessException
19
Configuring the RMI Proxy
 Define a factory bean to generate the proxy
Client
<bean id=transferService
class=org.springframework.remoting.rmi.RmiProxyFactoryBean>
<property name=serviceInterface value=app.TransferService/>
<property name=serviceUrl value=rmi://foo:1099/transferService/>
</bean>
 Inject it into the client
<bean id=tellerDesktopUI class=app.TellerDesktopUI>
<property name=transferService ref=transferService/>
</bean>
TellerDesktopUI only depends on the TransferService
interface
 Copyright 2014 Pivotal. All rights reserved.
20
Topics in this Session
Introduction to Remoting
Spring Remoting Overview
Spring Remoting and RMI
HttpInvoker
 Copyright 2014 Pivotal. All rights reserved.
21
Springs HttpInvoker
 Lightweight HTTP-based remoting protocol
 Method invocation converted to HTTP POST
 Method result returned as an HTTP response
 Method parameters and return values marshalled with
standard Java serialization
Client Process
Server Process
HTTP POST request
HttpInvoker
Proxy
HTTP response
HttpInvoker
ServiceExporter
Java serialization
HttpInvoker is using serialization  transferred objects still need to
implement the java.io.Serializable interface
 Copyright 2014 Pivotal. All rights reserved.
22
Configuring the HttpInvoker Service
Exporter (1)
Server
 Start with an existing POJO service
<bean id=transferService class=app.impl.TransferServiceImpl>
<property name=accountRepository ref=accountRepository/>
</bean>
 Define a bean to export it
endpoint for HTTP request handling
<bean id=/transfer
class=org.springframework.remoting.httpinvoker.
HttpInvokerServiceExporter>
<property name=serviceInterface value=app.TransferService/>
<property name=service ref=transferService/>
</bean>
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.
 Copyright 2014 Pivotal. All rights reserved.
23
Configuring the HttpInvoker Service
Exporter (2a)
 Expose the HTTP service via DispatcherServlet
 Uses BeanNameUrlHandlerMapping to map requests to
service
 Can expose multiple exporters
http://foo:8080/services/transfer
<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
 Copyright 2014 Pivotal. All rights reserved.
service exporter
bean name
web.xml
24
Configuring the HttpInvoker Service
Exporter (2b)
 Alternatively define HttpRequestHandlerServlet
Doesn't require Spring-MVC
Service exporter bean is defined in root context
No handler mapping  one servlet per HttpInvoker exporter
Servlet name must match bean name
<servlet>
http://foo:8080/services/transfer
<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>
 Copyright 2014 Pivotal. All rights reserved.
service exporter bean name
web.xml
25
Configuring the HttpInvoker Proxy
Client
 Define a factory bean to generate the proxy
<bean id=transferService
class=org.springframework.remoting.httpinvoker.
HttpInvokerProxyFactoryBean>
<property name=serviceInterface value=app.TransferService/>
<property name=serviceUrl value=http://foo:8080/services/transfer/>
</bean>
 Inject it into the client
HTTP POST requests will be sent to this
URL
<bean id=tellerDesktopUI class=app.TellerDesktopUI>
<property name=transferService ref=transferService/>
</bean>
 Copyright 2014 Pivotal. All rights reserved.
26
Remoting: Pros and Cons
 Advantages
 (Too) Simple to setup and use
 Abstracts away all messaging concerns
 Disadvantages
 Client-server tightly coupled by shared interface
 Hard to maintain, especially with lots of clients
 Can't control underlying messaging (hidden)
 Difficult to scale
 Make your requests high-level
 Not interoperable, Java only
Spring Enterprise  4 day course on application integration
 Copyright 2014 Pivotal. All rights reserved.
27
Lab
Implementing Distributed Applications
with Spring Remoting
 Copyright 2014 Pivotal. All rights reserved.
28
Performance and
Operations
Management and Monitoring of Spring Java
Applications
Exporting Spring Beans to JMX
 Copyright 2014 Pivotal. All rights reserved.
Topics in this Session
JMX
Introduction
JMX
Introducing Spring JMX
Automatically exporting existing MBeans
Spring Insight
 Copyright 2014 Pivotal. All rights reserved.
Overall Goals
 Gather information about application during runtime
 Dynamically reconfigure app to align to external
occasions
 Trigger operations inside the application
 Even adapt to business changes in smaller scope
 Copyright 2014 Pivotal. All rights reserved.
Topics in this Session
Introduction
JMX
Introducing Spring JMX
Automatically exporting existing MBeans
Spring Insight
 Copyright 2014 Pivotal. All rights reserved.
What is JMX?
 The Java Management Extensions specification aims to
create a standard API for adding management and
monitoring to Java applications
 Management
 Changing configuration properties at runtime
 Monitoring
 Reporting cache hit/miss ratios at runtime
 Copyright 2014 Pivotal. All rights reserved.
How JMX Works
 To add this management and monitoring capability, JMX
instruments application components
 JMX introduces the concept of the MBean
 An object with management metadata
 Copyright 2014 Pivotal. All rights reserved.
JMX Architecture
JSR-160
Connector
JSR-160
Connector
MBeanServer
MBean
 Copyright 2014 Pivotal. All rights reserved.
MBean
MBean
JMX Architecture
 MBeanServer acts as broker for communication between
 Multiple local MBeans
 Remote clients and MBeans
 MBeanServer maintains a keyed reference to all
MBeans registered with it
 object name
 Many generic clients available
 JDK: jconsole, jvisualvm
 Copyright 2014 Pivotal. All rights reserved.
JMX Architecture
 An MBean is an object with additional management
metadata
 Attributes ( properties)
 Operations ( methods)
 The management metadata can be defined statically
with a Java interface or defined dynamically at runtime
 Simple MBean or Dynamic MBean respectively
 Copyright 2014 Pivotal. All rights reserved.
Plain JMX  Example Bean
public interface JmxCounterMBean {
int getCount();// becomes Attribute named 'Count'
void increment(); // becomes Operation named 'increment'
}
public class JmxCounter implements JmxCounterMBean {
...
public int getCount() {}
public void increment() {}
}
 Copyright 2014 Pivotal. All rights reserved.
10
Plain JMX  Exposing an MBean
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
JmxCounter bean = new JmxCounter();
try {
ObjectName name = new ObjectName("ourapp:name=counter");
server.registerMBean(bean, name);
} catch (Exception e) {
e.printStackTrace();
}
 Copyright 2014 Pivotal. All rights reserved.
11
Topics in this Session
Introduction
JMX
Introducing Spring JMX
Automatically exporting existing MBeans
Spring Insight
 Copyright 2014 Pivotal. All rights reserved.
12
Goals of Spring JMX
 Using the raw JMX API is difficult and complex
 The goal of Spring's JMX support is to simplify the use of
JMX while hiding the complexity of the API
 Copyright 2014 Pivotal. All rights reserved.
13
Goals of Spring JMX
 Configuring JMX infrastructure
 Declaratively using context namespace or FactoryBeans
 Exposing Spring beans as MBeans
 Annotation based metadata
 Declaratively using Spring bean definitions
 Consuming JMX managed beans
 Transparently using a proxy-based mechanism
 Copyright 2014 Pivotal. All rights reserved.
14
Spring JMX Steps
1. Configuring MBean Server
2. Configure Exporter
3. Control Attribute / Operation Exposure.
 Copyright 2014 Pivotal. All rights reserved.
15
Step 1: Creating an MBeanServer
 Use context namespace to locate or create an
MBeanServer
<context:mbean-server />
XML
 Or declare it explicitly
or JavaConfig
@Bean
public MBeanServerFactoryBean mbeanServer () {
MBeanServerFactoryBean server = new MBeanServerFactoryBean();
server.setLocateExistingServerIfPossible( true );
...
return server;
}
 Copyright 2014 Pivotal. All rights reserved.
16
Step 2: Exporting a Bean as an MBean
 Start with one or more existing POJO bean(s)
<bean id="messageService" class="example.MessageService"/>
 Use the MBeanExporter to export it
 By default: all public properties exposed as attributes, all
public methods exposed as operations.
JavaConfig
or XML
<context:mbean-export/>
 Copyright 2014 Pivotal. All rights reserved.
17
Step 1 & 2: JavaConfig Shortcut
 One annotation defines server and exporter:
Specific server bean
configurable if desired.
 Copyright 2014 Pivotal. All rights reserved.
18
3. Control Attribute/Operation Exposure:
 Combine Annotations with Exporter:
 Only annotated attributes/operations exposed.
@ManagedResource(objectName=statistics:name=counter,
description=A simple JMX counter)
public class JmxCounterImpl implements JmxCounter {
@ManagedAttribute(description=The counter value)
public int getCount() {}
@ManagedOperation(description=Increments the counter value)
public void increment() {}
}
 Copyright 2014 Pivotal. All rights reserved.
19
Spring in the JMX architecture
Client Process
<<interface>>
JmxCounter
Client
Generated
at startup
 Copyright 2014 Pivotal. All rights reserved.
Spring
Proxy
Server Process
<<interface>>
JmxCounter
MBean
Server
MBean
Registration
at startup
JmxCounterImpl
Spring
MBeanExporter
20
Topics in this session
Introduction
JMX
Introducing Spring JMX
Automatically exporting existing MBeans
Spring Insight
 Copyright 2014 Pivotal. All rights reserved.
21
Automatically Exporting
Pre-existing MBeans
 Some beans are MBeans themselves
 Example: Log4j's LoggerDynamicMBean
 Spring will auto-detect and export them for you
<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>
 Copyright 2014 Pivotal. All rights reserved.
22
Topics in this session
Introduction
JMX
Introducing Spring JMX
Automatically exporting existing MBeans
Spring Insight
 Copyright 2014 Pivotal. All rights reserved.
23
Spring Insight Overview
 Part of tc Server Developer Edition
 Monitors web applications deployed to tc Server
 http://localhost:8080/insight
 Focuses on what's relevant
 esp. performance related parts of the application
 Detects performance issues during development
 Commercial version for production: vFabric APM
 Copyright 2014 Pivotal. All rights reserved.
24
Spring Insight Overview
Time
Servlet Selector
 Copyright 2014 Pivotal. All rights reserved.
25
Spring Insight Overview
 A request trace from HTTP POST to SQL
 Copyright 2014 Pivotal. All rights reserved.
26
Summary
JMX
 Spring JMX
 Export Spring-managed beans to a JMX MBeanServer
 Simple value-add now that your beans are managed
 Steps
 Create MBean server
 Automatically export annotated and pre-existing Mbeans
 Use @EnableMBeanExport or <context:mbean-server> and
<context:mbean-export>
 Use Spring annotations to declare JMX metadata
 Spring Insight (tc Server Developer Edition)
 Deep view into your web-application in STS
 Copyright 2014 Pivotal. All rights reserved.
27
Optional Lab
Monitoring and Managing a Java
Application
 Copyright 2014 Pivotal. All rights reserved.
28
Spring Web
Services
Implementing Loosely-Coupled, ContractFirst Web Services
Using the Spring WS project to implement SOAP
 Copyright 2014 Pivotal. All rights reserved.
Topics in this Session
 Introduction to Web Services
 Why use or build a web service?
 Best practices for implementing a web service
 Spring Web Services
 Client access
 Copyright 2014 Pivotal. All rights reserved.
Web Services enable Interoperability
 XML is the lingua franca in the world of interoperability
 XML is understood by all major platforms
SAX, StAX or DOM in Java
System.XML or .NET XML Parser in .NET
REXML or XmlSimple in Ruby
Perl-XML or XML::Simple in Perl
 Copyright 2014 Pivotal. All rights reserved.
Best practices for implementing
web services
 Remember:
 web services != SOAP
 web services != RPC
 Design contract independently from service interface
 Results in tight coupling and awkward contracts
 Refrain from using stubs and skeletons
 Consider skipping validation for incoming requests ...
 use Xpath to only extract what you need
Postels Law:
Be conservative in what you do;
be liberal in what you accept from others.
 Copyright 2014 Pivotal. All rights reserved.
Web GUI on top of your services
The Web GUI layer
provides compatibility
between HTML-based
world of the user (the
browser) and the OObased world of your
service
 Copyright 2014 Pivotal. All rights reserved.
Web Services enable Loose Coupling
Loosely coupled systems are considered
useful when either the source
or the destination computer systems are
subject to frequent changes
Karl Weikek (attrib)
Loose coupling increases tolerance
changes should not cause incompatibility
 Copyright 2014 Pivotal. All rights reserved.
Web Service on top of your services
Web Service layer
provides compatibility
between XML-based
world of the user and
the OO-based world of
your service
 Copyright 2014 Pivotal. All rights reserved.
Topics in this Session
 Introduction to Web Services
 Why use or build a web service?
 Best practices for implementing a web service
 Spring Web Services
 Client access
 Copyright 2014 Pivotal. All rights reserved.
Define the contract
 Spring-WS uses Contract-first
 Start with XSD/WSDL
 Widely considered a Best Practice
 Solves many interoperability issues
 Also considered difficult
 But isnt
 Copyright 2014 Pivotal. All rights reserved.
Contract-first in 3 simple steps
 Create sample messages
 Infer a contract
 Trang
 Microsoft XML to Schema
 XML Spy
 Tweak resulting contract
 Copyright 2014 Pivotal. All rights reserved.
10
Sample Message
Namespace for this message
<transferRequest xmlns=http://mybank.com/schemas/tr
amount=1205.15>
<credit>S123</credit>
<debit>C456</debit>
</transferRequest>
 Copyright 2014 Pivotal. All rights reserved.
11
Define a schema for
the web service message
 Copyright 2014 Pivotal. All rights reserved.
<transferRequest
amount=1205.15>
<credit>S123</credit>
<debit>C456</debit>
</transferRequest>
12
Type constraints
<xs:element name="credit" >
<xs:simpleType>
<xs:restriction base="xs:string">
<xs:pattern value="\w\d{3}"/>
</xs:restriction>
</xs:simpleType>
</xs:element>
1 Character + 3 Digits
 Copyright 2014 Pivotal. All rights reserved.
13
SOAP Message
Envelope
Header
Security
Routing
Body
TransferRequest
 Copyright 2014 Pivotal. All rights reserved.
14
Simple SOAP 1.1 Message Example
<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>
 Copyright 2014 Pivotal. All rights reserved.
15
Spring Web Services
Client Process
XML
XML Processing
SOAP
SOAP Framework
XML
SOAP Framework
 Copyright 2014 Pivotal. All rights reserved.
XML Processing
WS
Template
Server Process
Endpoint
16
Request Processing
Message
Dispatcher
Endpoint
Mapping
Endpoint
Adapter
Endpoint
getEndpoint(
MessageContext)
invoke(MessageContext, selectedEndpoint)
 Copyright 2014 Pivotal. All rights reserved.
17
Bootstrap the Application Tier
 Inside <webapp/> within web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/transfer-app-cfg.xml
</param-value>
</context-param>The application contexts configuration file(s)
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
Loads the ApplicationContext into the ServletContext
</listener>
before any Servlets are initialized
 Copyright 2014 Pivotal. All rights reserved.
18
Wire up the Front Controller
(MessageDispatcher)
 Inside <webapp/> within web.xml
<servlet>
<servlet-name>transfer-ws</servlet-name>
<servlet-class>..ws..MessageDispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/ws-config.xml</param-value>
</init-param>
</servlet>
The application contexts configuration file(s)
containing the web service infrastructure beans
 Copyright 2014 Pivotal. All rights reserved.
19
Map the MessageDispatcherServlet
 Inside <webapp/> within web.xml
<servlet-mapping>
<servlet-name>transfer-ws</servlet-name>
<url-pattern>/services/*</url-pattern>
</servlet-mapping>
There might also be a web interface (GUI) that is
mapped to another path
 Copyright 2014 Pivotal. All rights reserved.
20
Endpoint
 Endpoints handle SOAP messages
 Similar to MVC Controllers
 Handle input message
 Call method on business service
 Create response message
 With Spring-WS you can focus on the Payload
 Switching from SOAP to POX without code change
 Copyright 2014 Pivotal. All rights reserved.
21
XML Handling techniques
 Low-level techniques
 DOM (JDOM, dom4j, XOM)
 SAX
 StAX
 Marshalling
 JAXB (1 and 2)
 Castor
 XMLBeans
 XPath argument binding
 Copyright 2014 Pivotal. All rights reserved.
22
JAXB 2
JAXB 2 is part of Java EE 5 and JDK 6
Uses annotations for mapping metadata
Generates classes from a schema and vice-versa
Supported as part of Spring-OXM
<oxm:jaxb2-marshaller id="marshaller" contextPath="rewards.ws.types"/>
 No explicit marshaller bean definition necessary to be
used in Spring-WS 2.0 endpoints
<!-- registers all infrastructure beans needed for annotation-based
endpoints, incl. JABX2 (un)marshalling: -->
<ws:annotation-driven/>
 Copyright 2014 Pivotal. All rights reserved.
23
Implement the Endpoint
Spring WS Endpoint
@Endpoint
public class TransferServiceEndpoint {
private TransferService transferService;
@Autowired
public TransferServiceEndpoint(TransferService transferService) {
this.transferService = transferService;
}
Mapping
@PayloadRoot(localPart="transferRequest",
namespace="http://mybank.com/schemas/tr")
public @ResponsePayload TransferResponse newTransfer(
@RequestPayload TransferRequest request) {
// extract necessary info from request and invoke service
}
}
Converted with JAXB2
 Copyright 2014 Pivotal. All rights reserved.
24
Configure Spring-WS and Endpoint beans
 @Endpoint classes can be component-scanned
 Saves writing lots of trivial XML bean definitions
 Just make sure not to scan classes that belong in the root
context instead
<!-- instead of defining explicit endpoints beans
we rely on component scanning: -->
<context:component-scan base-package="transfers.ws"/>
<!-- registers all infrastructure beans needed for
annotation-based endpoints, incl. JAXB2 (un)marshalling: -->
<ws:annotation-driven/>
 Copyright 2014 Pivotal. All rights reserved.
25
Architecture of our Application Exposed
using a Web Service
Clients
Web Service Interface
Web Service Layer
(application context)
Local Java Business Interfaces
Application Layer
(application context)
Java EE Servlet Container
 Copyright 2014 Pivotal. All rights reserved.
JVM
26
Further Mappings
 You can also map your Endpoints in XML by
Message Payload
SOAP Action Header
WS-Adressing
XPath
 Copyright 2014 Pivotal. All rights reserved.
27
Publishing the WSDL
 Generates WSDL based on given XSD
 Bean id becomes part of WSDL URL
 Most useful during development
 Use static WSDL in production
 Contract shouldn't change unless YOU change it
http://somehost:8080/transferService/transferDefinition.wsdl
<ws:dynamic-wsdl id="transferDefinition"
portTypeName="Transfers"
locationUri="http://somehost:8080/transferService/">
<ws:xsd location="/WEB-INF/transfer.xsd"/>
</ws:dynamic-wsdl>
 Copyright 2014 Pivotal. All rights reserved.
28
Topics in this Session
 Introduction to Web Services
 Why use or build a web service?
 Best practices for implementing a web service
 Spring Web Services
 Client access
 Copyright 2014 Pivotal. All rights reserved.
29
Spring Web Services on the Client
 WebServiceTemplate
 Simplifies web service access
 Works directly with the XML payload
 Extracts body of a SOAP message
 Also works with POX (Plain Old XML)
 Can use marshallers/unmarshallers
 Provides convenience methods for sending and receiving
web service messages
 Provides callbacks for more sophisticated usage
 Copyright 2014 Pivotal. All rights reserved.
30
Marshalling with WebServiceTemplate
<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>
<bean id=marshaller class=org.springframework.oxm.castor.CastorMarshaller>
<property name=mappingLocation value=classpath:castor-mapping.xml/>
</bean>
WebServiceTemplate ws = context.getBean(WebServiceTemplate.class);
TransferRequest request = new TransferRequest(S123, C456, 85.00);
Receipt receipt = (Receipt) ws.marshalSendAndReceive(request);
 Copyright 2014 Pivotal. All rights reserved.
31
Lab
Exposing SOAP endpoints using
Spring Web Services
 Copyright 2014 Pivotal. All rights reserved.
32