Professional Documents
Culture Documents
Version 4.3.b
© ©Copyright 2016
Copyright 2015
2013 Pivotal.
Pivotal. Allreserved.
All rights rights reserved
Copyright Notice
Copyright © 2016
2016 Pivotal Software, Inc. All rights reserved. This manual and
its accompanying materials are protected by U.S. and international copyright
and intellectual property laws.
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 2016
Copyright 2015 Pivotal.
Pivotal. Allreserved.
All rights rights reserved -2- Version 4.3.b
This Page Intentionally Left Blank
© ©Copyright 2016
Copyright 2014 Pivotal.
Pivotal. Allreserved.
All rights rights reserved -3- Version 4.3.b
Welcome to Core
Spring
A 4-day bootcamp that trains you how to use
the Spring Framework to create well-
designed, testable, business, applications
Logistics
00-cs-introduction - 1
© Copyright 2016 Pivotal. All rights reserved -4- Version 4.3.b
How You will Benefit
• Agenda
• Spring and Pivotal
00-cs-introduction - 2
© Copyright 2016 Pivotal. All rights reserved -5- Version 4.3.b
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
• Spring FactoryBeans
00-cs-introduction - 3
© Copyright 2016 Pivotal. All rights reserved -6- Version 4.3.b
Course Agenda: Day 3
00-cs-introduction - 4
© Copyright 2016 Pivotal. All rights reserved -7- Version 4.3.b
Covered in this section
• Agenda
• Spring and Pivotal
00-cs-introduction - 5
© Copyright 2016 Pivotal. All rights reserved -8- Version 4.3.b
The Pivotal World
Spring Spring
Security
Spring
Projects Integration
Spring
Social
Spring
Spring AMQP
Cloud Spring Framework
Spring Spring
Session Hateoas
Spring
Spring Web Flow Boot
00-cs-introduction - 6
© Copyright 2016 Pivotal. All rights reserved -9- Version 4.3.b
Covered in this section
• Agenda
• Spring and Pivotal
00-cs-introduction - 7
© Copyright 2016 Pivotal. All rights reserved - 10 - Version 4.3.b
Overview of the
Spring Framework
Introducing Spring in the Context of
Enterprise Application Architecture
Objectives
01-cs-spring-intro - 1
© Copyright 2016 Pivotal. All rights reserved - 11 - Version 4.3.b
Topics in this session
Open Source
Lightweight
Container
Framework
01-cs-spring-intro - 2
© Copyright 2016 Pivotal. All rights reserved - 12 - Version 4.3.b
What is the Spring Framework?
Open Source
01-cs-spring-intro - 3
© Copyright 2016 Pivotal. All rights reserved - 13 - Version 4.3.b
What is the Spring Framework?
Container
01-cs-spring-intro - 4
© Copyright 2016 Pivotal. All rights reserved - 14 - Version 4.3.b
Topics in this session
Application Configuration
Transfer Transfer
Service Repository
Account
Repository
01-cs-spring-intro - 5
© Copyright 2016 Pivotal. All rights reserved - 15 - Version 4.3.b
Example: Money Transfer System
TransferService AccountRepository
transfer(
“300.00”, loadAccount(“1”);
a1
new
“1”, “2”) Account 1
loadAccount(“2”);
a2 new
Account 2
debit(“300.00”)
credit(“300.00”)
updateAccount(a1);
updateAccount(a2);
confirmation
01-cs-spring-intro - 6
© Copyright 2016 Pivotal. All rights reserved - 16 - Version 4.3.b
Money Transfer System Assembly
Spring
Part 2
TransferServiceImpl
Assembly
JdbcAccountRepository
Part 1
01-cs-spring-intro - 7
© Copyright 2016 Pivotal. All rights reserved - 17 - Version 4.3.b
Swapping Out Part Implementations
Spring
TransferServiceImpl
JdbcAccountRepository
StubAccountRepository
JpaAccountRepository For Jdbc
For For
Unit Jpa
Testing
(1)new
(1) new StubAccountRepository();
JdbcAccountRepository(…);
JpaAccountRepository(…);
(2)new
(2) new TransferServiceImpl();
TransferServiceImpl();
(3)service.setAccountRepository(repository);
(3) service.setAccountRepository(repository);
01-cs-spring-intro - 8
© Copyright 2016 Pivotal. All rights reserved - 18 - Version 4.3.b
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.
01-cs-spring-intro - 9
© Copyright 2016 Pivotal. All rights reserved - 19 - Version 4.3.b
The Birth of Spring
• Rod Johnson publishes J2EE
Development without EJB
01-cs-spring-intro - 10
© Copyright 2016 Pivotal. All rights reserved - 20 - Version 4.3.b
Topics in this session
01-cs-spring-intro - 11
© Copyright 2016 Pivotal. All rights reserved - 21 - Version 4.3.b
The Current World
• Visit http://spring.io/projects
01-cs-spring-intro - 12
© Copyright 2016 Pivotal. All rights reserved - 22 - Version 4.3.b
Lab
Developing an Application from Plain
Java Objects
01-cs-spring-intro - 13
© Copyright 2016 Pivotal. All rights reserved - 23 - Version 4.3.b
Dependency
Injection Using
Spring
Introducing the Spring Application Context
and Spring's Java Configuration capability
02-cs-javaconfig-di - 1
© Copyright 2016 Pivotal. All rights reserved - 24 - Version 4.3.b
How Spring Works
Your Application Classes
(POJOs)
Spring
Configuration
ApplicationContext
Instructions
Creates
Fully configured
application system
Ready for use
02-cs-javaconfig-di - 2
© Copyright 2016 Pivotal. All rights reserved - 25 - Version 4.3.b
Configuration Instructions
02-cs-javaconfig-di - 3
© Copyright 2016 Pivotal. All rights reserved - 26 - Version 4.3.b
Accessing a Bean
• Multiple ways
ApplicationContext context = SpringApplication.run(...);
Application Context
transferService
TransferServiceImpl
accountRepository
JdbcAccountRepository
dataSource
BasicDataSource
02-cs-javaconfig-di - 4
© Copyright 2016 Pivotal. All rights reserved - 27 - Version 4.3.b
Bean Descriptions
@Bean
@Description("Handles all transfer related use-cases")
public TransferService transferService() { … }
@Bean
@Description("Provides access to data from the Accounts table")
public AccountRepository accountRepository() { … }
@Bean
@Description("Data-source for the underlying RDB we are using")
public DataSource dataSource() { … }
02-cs-javaconfig-di - 5
© Copyright 2016 Pivotal. All rights reserved - 28 - Version 4.3.b
Topics in this session
02-cs-javaconfig-di - 6
© Copyright 2016 Pivotal. All rights reserved - 29 - Version 4.3.b
Application Context Example
Instantiating Within a System (Integration) Test
public class TransferServiceTests {
private TransferService service;
Bootstraps the
@Before public void setUp() { system to test
// Create the application from the configuration
ApplicationContext context =
SpringApplication.run( ApplicationConfig.class )
// Look up the application service interface
service = context.getBean(TransferService.class);
}
02-cs-javaconfig-di - 7
© Copyright 2016 Pivotal. All rights reserved - 30 - Version 4.3.b
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 @Configuration
public class InfrastructureConfig { public class WebConfig {
... ...
} }
Datasource infra-structure
Datasource
02-cs-javaconfig-di - 8
© Copyright 2016 Pivotal. All rights reserved - 31 - Version 4.3.b
Mixed Configuration
application beans
Coupled to a
local Postgres
environment
infrastructure bean
Partitioning Configuration
@Configuration application beans
public class ApplicationConfig {
@Autowired DataSource dataSource;
02-cs-javaconfig-di - 9
© Copyright 2016 Pivotal. All rights reserved - 32 - Version 4.3.b
Referencing Beans Defined in Another File
02-cs-javaconfig-di - 10
© Copyright 2016 Pivotal. All rights reserved - 33 - Version 4.3.b
… But Avoid “Tramp Data”
@Configuration
Bad: dataSource is a “tramp”!
@Import( InfrastructureConfig.class )
public class ApplicationConfig {
@Bean public AccountService accountService( DataSource dataSource ) {
return new accountService( accountRepository(dataSource) ); tramp
} tramp
@Bean public AccountService accountRepository( DataSource dataSource ) {
return new accountRepository( dataSource );
}
} @Configuration
@Import( InfrastructureConfig.class ) Better: Pass actual dependency
public class ApplicationConfig {
@Bean public AccountService accountService( AccountRepository repo ) {
return new accountService( repo );
}
@Bean public AccountService accountRepository( DataSource ds ) {
return new accountRepository( ds );
}
}
02-cs-javaconfig-di - 11
© Copyright 2016 Pivotal. All rights reserved - 34 - Version 4.3.b
Topics in this session
service1 == service2
Bean Scope: default
02-cs-javaconfig-di - 12
© Copyright 2016 Pivotal. All rights reserved - 35 - Version 4.3.b
service1 != service2
Bean Scope: prototype
• Scope "prototype"
– New instance created every time bean is referenced
@Bean
@Scope(scopeName=“prototype”)
@Scope(“prototype”)
public AccountService accountService() {
return …
}
02-cs-javaconfig-di - 13
© Copyright 2016 Pivotal. All rights reserved - 36 - Version 4.3.b
Other Scopes
02-cs-javaconfig-di - 14
© Copyright 2016 Pivotal. All rights reserved - 37 - Version 4.3.b
Lab
Using Spring to Configure an
Application
02-cs-javaconfig-di - 15
© Copyright 2016 Pivotal. All rights reserved - 38 - Version 4.3.b
Dependency
Injection Using
Spring 2
Deeper Look into Spring's Java
Configuration Capability
• External Properties
• Profiles
• Spring Expression Language
• Proxying
03-cs-javaconfig-di2 - 1
© Copyright 2016 Pivotal. All rights reserved - 39 - Version 4.3.b
Setting property values
03-cs-javaconfig-di2 - 2
© Copyright 2016 Pivotal. All rights reserved - 40 - Version 4.3.b
Spring's Environment Abstraction – 2
@Configuration
public class DbConfig { Property names
private static final String DB_DRIVER = "db.driver";
private static final String DB_URL = "db.url";
private static final String DB_USER = "db.user";
private static final String DB_PWD = "db.password";
Property Sources
@Configuration
@PropertySource ( “classpath:/com/organization/config/app.properties” )
@PropertySource ( “file:config/local.properties” )
public class ApplicationConfig {
...
} Adds properties from these files in addition to
environment variables and system properties
03-cs-javaconfig-di2 - 3
© Copyright 2016 Pivotal. All rights reserved - 41 - Version 4.3.b
Accessing Properties using @Value
@Configuration Convenient
public class DbConfig { alternative to
explicitly using
@Bean Environment
public DataSource dataSource(
@Value("${db.driver}") String driver,
@Value("${db.url}") String url,
@Value("${db.user}") String user,
@Value("${db.password}") String pwd) {
DataSource ds = new BasicDataSource();
ds.setDriverClassName( driver);
ds.setUrl( url);
ds.setUser( user);
ds.setPassword( pwd ));
return ds;
}
} BUT: How are these ${...} variables resolved? Next slide ...
@Bean
public static PropertySourcesPlaceholderConfigurer pspc() {
return new PropertySourcesPlaceholderConfigurer();
}
${..} placeholders are not resolved unless this bean declared
03-cs-javaconfig-di2 - 4
© Copyright 2016 Pivotal. All rights reserved - 42 - Version 4.3.b
${...} Placeholders
db.driver=org.postgresql.Driver
db.url=jdbc:postgresql://localhost/transfer
db.user=transfer-app
db.password=secret45 db.driver=org.postgresql.Driver
db.url=jdbc:postgresql://qa/transfer
app-dev.properties app-prod.properties
db.user=transfer-app
db.password=secret88
app-qa.properties
• External Properties
• Profiles
• Spring Expression Language
• Proxying
03-cs-javaconfig-di2 - 5
© Copyright 2016 Pivotal. All rights reserved - 43 - Version 4.3.b
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
ApplicationContext
Beans with Transfer Account
no profile Service Service web
Customer Account Other
always Repository Error
Repository Other
available Handler
Other
dev
Other
data prod
Source qa data
connection data Source
Factory connection
Source
performance connection Factory
Monitor Factory
Defining Profiles – 1
@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();
}
…
03-cs-javaconfig-di2 - 6
© Copyright 2016 Pivotal. All rights reserved - 44 - Version 4.3.b
Defining Profiles - 2
03-cs-javaconfig-di2 - 7
© Copyright 2016 Pivotal. All rights reserved - 45 - Version 4.3.b
Quiz:
Which of the Following is/are Selected?
-Dspring.profiles.active=jpa
? ? ?
@Configuration @Configuration @Configuration
public class @Profile("jpa") @Profile("jdbc")
Config { ...} public class public class
JpaConfig JdbcConfig
{ ...} { ...}
db.driver=org.postgresql.Driver
db.url=jdbc:postgresql://localhost/transfer
db.user=transfer-app
db.password=secret45
dev.properties prod.properties
03-cs-javaconfig-di2 - 8
© Copyright 2016 Pivotal. All rights reserved - 46 - Version 4.3.b
Topics in this session
• External Properties
• Profiles
• Spring Expression Language
• Proxying
03-cs-javaconfig-di2 - 9
© Copyright 2016 Pivotal. All rights reserved - 47 - Version 4.3.b
SpEL examples – Using @Value
@Configuration
class TaxConfig
{
@Value("#{ systemProperties['user.region'] }") String region;
03-cs-javaconfig-di2 - 10
© Copyright 2016 Pivotal. All rights reserved - 48 - Version 4.3.b
Accessing Properties
@Value("${daily.limit}") @Value("#{environment['daily.limit']}")
int maxTransfersPerDay; int maxTransfersPerDay;
SpEL
03-cs-javaconfig-di2 - 11
© Copyright 2016 Pivotal. All rights reserved - 49 - Version 4.3.b
Topics in this session
• External Properties
• Profiles
• Spring Expression Language
• Proxying
Quiz
Which is the best
@Bean implementation?
public AccountRepository accountRepository() {
return new JdbcAccountRepository();
}
@Bean
public TransferService transferService1() {
TransferServiceImpl service = new TransferServiceImpl(); 1. Method call?
service.setAccountRepository(accountRepository());
return service;
}
2. New instance?
@Bean
public TransferService transferService2() {
return new TransferServiceImpl( new JdbcAccountRepository() );
}
Prefer call to dedicated method. Let's discuss why ...
03-cs-javaconfig-di2 - 12
© Copyright 2016 Pivotal. All rights reserved - 50 - Version 4.3.b
Working with Singletons
@Bean
• public
singleton is the default
AccountRepository scope
accountRepository() {
return new JdbcAccountRepository(); Singleton??
}
@Bean
public TransferService transferService() {
TransferServiceImpl service = new TransferServiceImpl();
service.setAccountRepository(accountRepository()); Method
return service; called twice
} more
@Bean
public AccountService accountService() {
return new AccountServiceImpl( accountRepository() );
}
HOW IS IT POSSIBLE?
03-cs-javaconfig-di2 - 13
© Copyright 2016 Pivotal. All rights reserved - 51 - Version 4.3.b
Inheritance-based Proxies
Summary
03-cs-javaconfig-di2 - 14
© Copyright 2016 Pivotal. All rights reserved - 52 - Version 4.3.b
Annotations in
Spring
Annotations for Dependency Injection and
Interception
• Fundamentals
– Annotation-based Configuration
– Best practices: when to use what?
– @PostConstruct and @PreDestroy
– Stereotypes and meta annotations
• Lab
• Advanced features
– @Resource
– Standard annotations (JSR 330
04-cs-annotations - 1
© Copyright 2016 Pivotal. All rights reserved - 53 - Version 4.3.b
Before – Explicit Bean Definition
@Configuration
@ComponentScan ( “com.bank” ) Find @Component classes
public class AnnotationConfig { within designated (sub)packages
// No bean definition needed any more
}
04-cs-annotations - 2
© Copyright 2016 Pivotal. All rights reserved - 54 - Version 4.3.b
Unique dependency of
Usage of @Autowired 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 Even when field is private!!
@Autowired – but hard to unit test, see URL
private AccountRepository accountRepository;
http://olivergierke.de/2013/11/why-field-injection-is-evil/
© Copyright 2014 Pivotal. All rights reserved. 5
@Autowired dependencies:
required or not?
• Default behavior: required Exception if no
dependency found
@Autowired
public void setAccountRepository(AccountRepository a) {
this.accountRepository = a;
}
04-cs-annotations - 3
© Copyright 2016 Pivotal. All rights reserved - 55 - Version 4.3.b
Java 8 Optional<T>
@Autowired(required=false)
AccountService accountService;
@Autowired
public void doSomething() { Optional<AccountService> accountService;
if (accountService != null) {
// do something public void doSomething() {
} accountService.ifPresent( s -> {
} // s is the AccountService instance,
// use s to do something
});
} Note the use of the lamda
04-cs-annotations - 4
© Copyright 2016 Pivotal. All rights reserved - 56 - Version 4.3.b
Autowiring and Disambiguation – 1
@Component
public class JpaAccountRepository implements AccountRepository {..}
Which one should get injected?
@Component
public class JdbcAccountRepository implements AccountRepository {..}
@Component("jpaAccountRepository")
public class JpaAccountRepository implements AccountRepository {..}
04-cs-annotations - 5
© Copyright 2016 Pivotal. All rights reserved - 57 - Version 4.3.b
Autowiring and Disambiguation – 3
@Autowired
• Autowired resolution rules public myBean(Queue ack) {
– Look for unique bean of …
required type }
• Method-injection
@Autowired
public void setDailyLimit(@Value("${daily.limit}") int max) {
this.maxTransfersPerDay = max;
}
• Field-injection
Not private so we can
@Value("#{environment['daily.limit']}") initialize in a unit-test
int maxTransfersPerDay;
04-cs-annotations - 6
© Copyright 2016 Pivotal. All rights reserved - 58 - Version 4.3.b
More on @Value
?:)
x ?: y is short for x != null ? x : y Elvis lives!
Component Names
04-cs-annotations - 7
© Copyright 2016 Pivotal. All rights reserved - 59 - Version 4.3.b
Java Config vs Annotations syntax
• Similar options are available
@Configuration
public class TransferConfiguration
@Component("transferService") @Bean(name="transferService")
@Scope("prototype") @Scope("prototype")
@Profile("dev") @Profile("dev")
@Lazy(false) @Lazy(false)
public class TransferServiceImpl public TransferService tsvc() {
implements TransferService {
return
@Autowired
new TransferServiceImpl(
public TransferServiceImpl
(AccountRepository accRep) { … }
accountRepository());
}
} }
Annotations Java Configuration
• Fundamentals
– Annotation-based Configuration
– Best practices: when to use what?
– @PostConstruct and @PreDestroy
– Stereotypes and meta annotations
• Lab
• Advanced features
– @Resource
– Standard annotations (JSR 330)
04-cs-annotations - 8
© Copyright 2016 Pivotal. All rights reserved - 60 - Version 4.3.b
About Component Scanning
Best practices
All “org” and “com”
• Really bad: packages in the classpath
will be scanned!!
@ComponentScan ( { "org", "com" } )
• Still bad:
@ComponentScan ( "com" )
• OK:
@ComponentScan ( "com.bank.app" )
• Optimized:
@ComponentScan ( { "com.bank.app.repository",
"com.bank.app.service", "com.bank.app.controller" } )
04-cs-annotations - 9
© Copyright 2016 Pivotal. All rights reserved - 61 - Version 4.3.b
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
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)
04-cs-annotations - 10
© Copyright 2016 Pivotal. All rights reserved - 62 - Version 4.3.b
Mixing Java Config and Annotations
• Common approach:
– Use annotations whenever possible
• Your classes
– But still use Java Configuration for
• Third-party beans that aren't annotated
• Legacy code that can't be changed
• Fundamentals
– Annotation-based Configuration
– Best practices: when to use what?
– @PostConstruct and @PreDestroy
– Stereotypes and meta annotations
• Lab
• Advanced features
– @Resource
– Standard annotations (JSR 330)
04-cs-annotations - 11
© Copyright 2016 Pivotal. All rights reserved - 63 - Version 4.3.b
@PostConstruct and @PreDestroy
04-cs-annotations - 12
© Copyright 2016 Pivotal. All rights reserved - 64 - Version 4.3.b
@PostConstruct
• Called after setter methods are called
public class JdbcAccountRepository {
private DataSource dataSource;
@Autowired 1
public void setDataSource(DataSource dataSource)
{ this.dataSource = dataSource; }
@PostConstruct
public void populateCache() 2
{ Connection conn = dataSource.getConnection(); //... }
}
Constructor @PostConstruct
Setter(s) called
called method(s) called
@PreDestroy
04-cs-annotations - 13
© Copyright 2016 Pivotal. All rights reserved - 65 - Version 4.3.b
Lifecycle Methods via @Bean
• Common Usage:
– @PostConstruct/@PreDestroy for your own classes
– @Bean properties for classes you didn't write and can't
annotate
• Fundamentals
– Annotation-based Configuration
– Best practices: when to use what?
– @PostConstruct and @PreDestroy
– Stereotypes and meta annotations
• Lab
• Advanced features
– @Resource
– Standard annotations (JSR 330)
04-cs-annotations - 14
© Copyright 2016 Pivotal. All rights reserved - 66 - Version 4.3.b
Stereotype Annotations
@Component
@Service @Configuration
Service classes
Java Configuration
@Repository @Controller
04-cs-annotations - 15
© Copyright 2016 Pivotal. All rights reserved - 67 - Version 4.3.b
Meta-annotations
@Retention(RetentionPolicy.RUNTIME)
recognizes @Target(ElementType.TYPE)
scans @Service
@Transactional(timeout=60)
public @interface
@MyTransactionalService MyTransactionalService {
public class TransferServiceImpl String value() default "";
implements TransferService {...} }
Summary
04-cs-annotations - 16
© Copyright 2016 Pivotal. All rights reserved - 68 - Version 4.3.b
Lab
Using Spring Annotations
To Configure and Test an application
• Fundamentals
– Annotation-based Configuration
– Best practices: when to use what?
– @PostConstruct and @PreDestroy
– Stereotypes and meta annotations
• Lab
• Advanced features
– @Resource
– Standard annotations (JSR 330)
04-cs-annotations - 17
© Copyright 2016 Pivotal. All rights reserved - 69 - Version 4.3.b
Using @Resource
@Resource(name="jdbcAccountRepository”) Field
private AccountRepository accountRepository; injection
Qualifying @Resource
@Autowired: type then name
@Resource: name then type
• 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;
}
04-cs-annotations - 18
© Copyright 2016 Pivotal. All rights reserved - 70 - Version 4.3.b
Topics in this Session
• Fundamentals
– Annotation-based Configuration
– Best practices: when to use what?
– @PostConstruct and @PreDestroy
– Stereotypes and meta annotations
• Lab
• Advanced features
– @Resource
– Standard annotations (JSR 330)
JSR 330
04-cs-annotations - 19
© Copyright 2016 Pivotal. All rights reserved - 71 - Version 4.3.b
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 {..}
04-cs-annotations - 20
© Copyright 2016 Pivotal. All rights reserved - 72 - Version 4.3.b
Dependency
Injection Using XML
Spring's XML Configuration Language
05-cs-xml-di - 1
© Copyright 2016 Pivotal. All rights reserved - 73 - Version 4.3.b
XML Configuration
@Configuration Comparison
Java
XML configuration
configuration fileclass
@Configuration profile
@Profile(“prod”) <beans profile=“prod”>
public class AppConfig {
bean id <bean id=“transferService”
@Bean class=“com.acme.TransferServiceImpl”>
public TransferService transferService() <property name=“repository”
{ ref=“accountRepository” />
TransferService service </bean>
= new TransferServiceImpl();
service.setRepository(repository());
return service;
Dependency injection
} <bean id=“accountRepository”
bean id
class=“com.acme.JdbcAccountRepository”>
@Bean(name=“accountRepository”) ...
public AccountRepository repository() </bean>
{ //... }
} </beans>
05-cs-xml-di - 2
© Copyright 2016 Pivotal. All rights reserved - 74 - Version 4.3.b
Constructor Injection Configuration
• One parameter
<bean id=“transferService” class=“com.acme.TransferServiceImpl”>
<constructor-arg ref=“accountRepository”/>
</bean>
Equivalent to:
@Bean public Repository repository() {
return new RepositoryImpl();
}
05-cs-xml-di - 3
© Copyright 2016 Pivotal. All rights reserved - 75 - Version 4.3.b
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();
}
Equivalent to:
@Bean public RequiredImpl required() { … }
@Bean public OptionalImpl optional() { … }
@Bean public Service service() {
Service svc = new ServiceImpl( required() );
svc.setOptional( optional() );
return svc;
}
05-cs-xml-di - 4
© Copyright 2016 Pivotal. All rights reserved - 76 - Version 4.3.b
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:
}
@Bean
public Service service() {
Equivalent to: Service svc = new ServiceImpl( );
svc.setStringProperty( “foo” );
return svc;
}
05-cs-xml-di - 5
© Copyright 2016 Pivotal. All rights reserved - 77 - Version 4.3.b
Topics in this session
●
Multiple files possible.
@Configuration ●
Valid prefixes are
@ImportResource( { classpath: (default), file:, http:
“classpath:com/acme/application-config.xml”,
“file:C:/Users/alex/application-config.xml” } )
@Import(DatabaseConfig.class)
public class MainConfig { … } Can combine with
@Configuration imports
05-cs-xml-di - 6
© Copyright 2016 Pivotal. All rights reserved - 78 - Version 4.3.b
Remember @Import?
@Configuration
@Import(DatabaseConfig.class)
public class MainConfig {
...
}
05-cs-xml-di - 7
© Copyright 2016 Pivotal. All rights reserved - 79 - Version 4.3.b
Creating the ApplicationContext
05-cs-xml-di - 8
© Copyright 2016 Pivotal. All rights reserved - 80 - Version 4.3.b
Remember @PostConstruct?
@PostConstruct
public void setup() {
...
}
Remember @PreDestroy?
@PreDestroy
public void teardown() {
...
}
05-cs-xml-di - 9
© Copyright 2016 Pivotal. All rights reserved - 81 - Version 4.3.b
Remember Bean Scope?
@Bean
@Scope(“prototype”) @Component
public AccountService accountService() { @Scope(“prototype”)
return ... public class AccountServiceImpl {
} ...
}
Remember @Lazy?
@Bean
@Lazy(“true”) @Component
“true”)
public AccountService accountService() { @Lazy(
return ... public class AccountServiceImpl {
} ...
}
05-cs-xml-di - 10
© Copyright 2016 Pivotal. All rights reserved - 82 - Version 4.3.b
Profile Configuration in XML
Short Break?
05-cs-xml-di - 11
© Copyright 2016 Pivotal. All rights reserved - 83 - Version 4.3.b
Advanced XML Bean Instantiation
• Conditional configuration
– @Bean methods can use any Java you need
• Do property lookups
• Use if-then-else and iterative logic
• No equivalent in XML
– We did not implement <if>, <for-each>
• Instead Spring XML relies on the Factory Pattern
– Use a factory to create the bean(s) we want
– Use any complex Java code we need in the factory's
internal logic
05-cs-xml-di - 12
© Copyright 2016 Pivotal. All rights reserved - 84 - Version 4.3.b
The FactoryBean interface
<bean id=“accountService”
class=“com.acme.AccountServiceFactoryBean”/>
@Bean
public AccountServiceFactoryBean accountService() {
return new AccountServiceFactoryBean();
}
@Bean
public CustomerService customerService(AccountService accountService) {
return new CustomerService(accountService);
}
05-cs-xml-di - 13
© Copyright 2016 Pivotal. All rights reserved - 85 - Version 4.3.b
FactoryBeans in Spring
05-cs-xml-di - 14
© Copyright 2016 Pivotal. All rights reserved - 86 - Version 4.3.b
Default Namespace
Other Namespaces
05-cs-xml-di - 15
© Copyright 2016 Pivotal. All rights reserved - 87 - Version 4.3.b
Namespace Example 1
In-Memory DataStore using Bean XML
Namespace Example 1
In-Memory DataStore using jdbc Namespace
05-cs-xml-di - 16
© Copyright 2016 Pivotal. All rights reserved - 88 - Version 4.3.b
Namespace Example 2
Property Placeholders
<bean class="org.springframework...PropertySourcesPlaceholderConfigurer">
<property name="location" value="db-config.properties"/>
</bean>
dbUrl=jdbc:oracle:...
db-config.properties
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>
05-cs-xml-di - 17
© Copyright 2016 Pivotal. All rights reserved - 89 - Version 4.3.b
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” )
05-cs-xml-di - 18
© Copyright 2016 Pivotal. All rights reserved - 90 - Version 4.3.b
Power of Namespaces
• Greatly simplifies Spring configuration
– Many advanced features of Spring need to declare a large
number of beans
<?xml version="1.0" encoding="UTF-8"?> hides 1 bean definition
<beans ...>
<context:property-placeholder location="db-config.properties" />
<tx:annotation-driven />
Transactions configuration: hides more than 15 bean definitions!
</beans>
Remember @ComponentScan?
@Configuration
@ComponentScan ( { “com.acme.app.repository”, Array of Strings
})
com.acme.app.service”, “com.acme.app.controller”
public class MainConfig {
...
}
<context:component-scan base-package=“com.acme.app.repository,
com.acme.app.service, com.acme.app.controller” />
05-cs-xml-di - 19
© Copyright 2016 Pivotal. All rights reserved - 91 - Version 4.3.b
Namespaces Declarations are Tedious!
05-cs-xml-di - 20
© Copyright 2016 Pivotal. All rights reserved - 92 - Version 4.3.b
Schema Version Numbers
spring-beans-4.2.xsd OR spring-beans.xsd ?
Summary
05-cs-xml-di - 21
© Copyright 2016 Pivotal. All rights reserved - 93 - Version 4.3.b
Spring XML Best Practices
Lab (optional)
Using XML to Configure an
Application
05-cs-xml-di - 22
© Copyright 2016 Pivotal. All rights reserved - 94 - Version 4.3.b
Understanding the
Bean Lifecycle
An In-Depth Look “Under the Hood”
• Introduction
• The initialization phase
• The use phase
• The destruction phase
06-cs-bean-lifecycle - 1
© Copyright 2016 Pivotal. All rights reserved - 95 - Version 4.3.b
Phases of the Application Lifecycle
06-cs-bean-lifecycle - 2
© Copyright 2016 Pivotal. All rights reserved - 96 - Version 4.3.b
Topics in this session
• Introduction
• The initialization phase
• The use phase
• The destruction phase
06-cs-bean-lifecycle - 3
© Copyright 2016 Pivotal. All rights reserved - 97 - Version 4.3.b
Bean Initialization Steps
for-each bean ...
Bean Post Process
Definitions Bean Instantiate
Loaded Definitions Beans
Dependency Setters
What you've seen before Injection Called
Bean
BPP Initializer BPP
Ready BPP BPP
For Use Bean Post Processors
Create and Initialize Beans
Bean
After Initializers Before
Ready
Init Called Init
For Use
06-cs-bean-lifecycle - 4
© Copyright 2016 Pivotal. All rights reserved - 98 - Version 4.3.b
Load Bean Definitions
06-cs-bean-lifecycle - 5
© Copyright 2016 Pivotal. All rights reserved - 99 - Version 4.3.b
BeanFactoryPostProcessor Extension Point
@Configuration
@PropertySource ( “classpath:/config/app.properties” )
public class ApplicationConfig {
@Value("${max.retries}")
int maxRetries;
...
}
06-cs-bean-lifecycle - 6
© Copyright 2016 Pivotal. All rights reserved - 100 - Version 4.3.b
Java Configuration uses Static beans
@Bean
public static PropertySourcesPlaceholderConfigurer
propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
Or if using XML, <context:property-placeholder/> creates a
PropertySourcesPlaceholderConfigurer for you
Setters
Called
Create Beans
Bean
After Initializers Before
Ready
Init Called Init
For Use
Bean Post-Processor(s)
06-cs-bean-lifecycle - 7
© Copyright 2016 Pivotal. All rights reserved - 101 - Version 4.3.b
Bean Creation Summary
06-cs-bean-lifecycle - 8
© Copyright 2016 Pivotal. All rights reserved - 102 - Version 4.3.b
The Initializer Extension Point - XML
06-cs-bean-lifecycle - 9
© Copyright 2016 Pivotal. All rights reserved - 103 - Version 4.3.b
Configuration Lifecycle
Bean Bean Bean instantiation and Bean
detection FactoryPP dependency injection PP
Read @Bean
Java method Call @Bean method implementations
config signatures
BeanFactoryPP → BeanFactoryPostProcessor
BeanPP → BeanPostProcessor
Dependency
Injection Setters
Called
Bean
BPP Initializer BPP
Ready BPP BPP
For Use Bean Post Processors
Create and Initialize Beans
06-cs-bean-lifecycle - 10
© Copyright 2016 Pivotal. All rights reserved - 104 - Version 4.3.b
Topics in this session
• Introduction
• The initialization phase
• The use phase
• The destruction phase
06-cs-bean-lifecycle - 11
© Copyright 2016 Pivotal. All rights reserved - 105 - Version 4.3.b
Inside The Bean Request (Use) Lifecycle
Proxy Power
begin commit
Transactional
behavior is added
TransactionManager around the target
(your bean)
06-cs-bean-lifecycle - 12
© Copyright 2016 Pivotal. All rights reserved - 106 - Version 4.3.b
Kinds of Proxies
TransferService TransferServiceImpl
06-cs-bean-lifecycle - 13
© Copyright 2016 Pivotal. All rights reserved - 107 - Version 4.3.b
Topics in this session
• Introduction
• The initialization phase
• The use phase
• The destruction phase
06-cs-bean-lifecycle - 14
© Copyright 2016 Pivotal. All rights reserved - 108 - Version 4.3.b
Application Context Destruction Lifecycle (1)
<context:component-scan … />
06-cs-bean-lifecycle - 15
© Copyright 2016 Pivotal. All rights reserved - 109 - Version 4.3.b
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
06-cs-bean-lifecycle - 16
© Copyright 2016 Pivotal. All rights reserved - 110 - Version 4.3.b
Testing Spring
Applications
Unit Testing without Spring
Integration Testing with Spring
07-cs-test - 1
© Copyright 2016 Pivotal. All rights reserved - 111 - Version 4.3.b
Pass
What is TDD? TDD
Fail, fix
Refactor
• TDD = Test Driven Development
– Is it writing tests before the code?
– Is it writing tests at the same time as the code?
– Ultimately 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
07-cs-test - 2
© Copyright 2016 Pivotal. All rights reserved - 112 - Version 4.3.b
TDD and Agility
07-cs-test - 3
© Copyright 2016 Pivotal. All rights reserved - 113 - Version 4.3.b
TDD and Focus
time
to fix
07-cs-test - 4
© Copyright 2016 Pivotal. All rights reserved - 114 - Version 4.3.b
Topics in this Session
• Unit Testing
– Tests one unit of functionality
– Keeps dependencies minimal
– Isolated from the environment (including Spring)
– Uses simplified alternatives for dependencies
• Stubs and/or Mocks
• See Appendix for more details
07-cs-test - 5
© Copyright 2016 Pivotal. All rights reserved - 115 - Version 4.3.b
Integration Testing Integration Testing
With Spring
Injected Injected
by Spring by Spring
JpaAccountRepo JpaAccountRepo
Production DB Test DB
07-cs-test - 6
© Copyright 2016 Pivotal. All rights reserved - 116 - Version 4.3.b
Spring’s Integration Test Support
@Test
@Test
public
public void
void shouldTransferMoneySuccessfully()
shouldTransferMoneySuccessfully() {{
TransferConfirmation
TransferConfirmation conf
conf == transferService.transfer(...);
transferService.transfer(...);
...
...
}} Test the system as normal
}}
No need for @Before method
07-cs-test - 7
© Copyright 2016 Pivotal. All rights reserved - 117 - Version 4.3.b
Including Configuration as an inner class
@RunWith(SpringJUnit4ClassRunner.class)
Don't specify config
@ContextConfiguration
classes
public class JdbcAccountRepoTest {
@Test
public void shouldUpdateDatabaseSuccessfully() {...}
Looks for configuration
@Configuration
embedded in the class
@Import(SystemTestConfig.class)
static class TestConfiguration {
@Bean public DataSource dataSource() { … }
}
} Override a bean with
a test alternative
@ContextConfiguration – XML
@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) Defaults to
@ContextConfiguration ${classname}-context.xml
@ContextConfiguration
public in same package
public class
class TransferServiceTests
TransferServiceTests {{ …
… }}
Loads TransferServiceTests-context.xml
07-cs-test - 8
© Copyright 2016 Pivotal. All rights reserved - 118 - Version 4.3.b
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
The ApplicationContext is
public
public void
void successfulTransfer()
successfulTransfer() {{
instantiated only once for
...
...
}} all tests that use the same
set of config files
@Test (even across test classes)
@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
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=SystemTestConfig.class)
@ContextConfiguration(classes=SystemTestConfig.class)
@TestPropertySource(properties
@TestPropertySource(properties == {{ "username=foo",
"username=foo", "password=bar"
"password=bar" }}
locations
locations == "classpath:/transfer-test.properties")
"classpath:/transfer-test.properties")
public
public final
final class
class TransferServiceTests
TransferServiceTests {{
...
...
}}
07-cs-test - 9
© Copyright 2016 Pivotal. All rights reserved - 119 - Version 4.3.b
Spring 4.3
Spring 4.3 Simplification
@RunWith(SpringRunner.class)
@RunWith(SpringRunner.class)
@ContextConfiguration(classes=SystemTestConfig.class)
@ContextConfiguration(classes=SystemTestConfig.class)
public
public final
final class
class TransferServiceTests
TransferServiceTests {{
...
...
}}
07-cs-test - 10
© Copyright 2016 Pivotal. All rights reserved - 120 - Version 4.3.b
Topics in this Session
07-cs-test - 11
© Copyright 2016 Pivotal. All rights reserved - 121 - Version 4.3.b
Profiles Activation with JavaConfig
@RunWith(SpringJUnit4ClassRunner.class) @Configuration
@ContextConfiguration(classes=DevConfig.class) @Profile("jdbc")
@ActiveProfiles("jdbc") public class DevConfig {
public class TransferServiceTests
{...} @Bean
{...}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=DevConfig.class) @Repository
@ActiveProfiles("jdbc") @Profile("jdbc")
public class TransferServiceTests public class
{...} JdbcAccountRepository
{ ...}
07-cs-test - 12
© Copyright 2016 Pivotal. All rights reserved - 122 - Version 4.3.b
Profiles Activation with XML
07-cs-test - 13
© Copyright 2016 Pivotal. All rights reserved - 123 - Version 4.3.b
Spring 4.1
Spring 4.1
@Sql Examples
Run these scripts before
@RunWith(SpringJUnit4ClassRunner.class)
@RunWith(SpringJUnit4ClassRunner.class) each @Test method
@ContextConfiguration(...)
@ContextConfiguration(...)
@Sql({ “/testfiles/schema.sql”,””“/testfiles/general-data.sql
@Sql({ “/testfiles/schema.sql”, }} ))
“/testfiles/general-data.sql
public
public final
final class
class MainTests
MainTests {{
Run script named (by default)
@Test
@Test MainTests.success.sql
@Sql
@Sql in same package
public
public void
void success()
success() {{ …
… }}
Run before @Test method...
@Test
@Test
@Sql
@Sql (( “/testfiles/error.sql”
“/testfiles/error.sql” )) ...run after @Test method
@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() {{ …
… }}
}}
07-cs-test - 14
© Copyright 2016 Pivotal. All rights reserved - 124 - Version 4.3.b
@Sql Options
Summary
07-cs-test - 15
© Copyright 2016 Pivotal. All rights reserved - 125 - Version 4.3.b
Lab
Testing Spring Applications
07-cs-test - 16
© Copyright 2016 Pivotal. All rights reserved - 126 - Version 4.3.b
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
• Discussed Integration Testing earlier
– Let's discuss Unit Testing here
– Remember: Unit Testing does not use Spring
Unit Testing
07-cs-test - 17
© Copyright 2016 Pivotal. All rights reserved - 127 - Version 4.3.b
Unit Testing example
AuthenticatorImplTest
AuthenticatorImpl
AuthenticatorImpl JUnit
Injected by Spring
JpaAccountRepo
AccountRepoStub
“fake” implementation
Spring config JPA config
NO Database!!
Production DB
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
07-cs-test - 18
© Copyright 2016 Pivotal. All rights reserved - 128 - Version 4.3.b
Implementing a Stub
AccountRepository
JPA Stub
AccountRepository AccountRepository
public
public class
class AuthenticatorImplTests
AuthenticatorImplTests {{
private
private AuthenticatorImpl Spring not in charge of
AuthenticatorImpl authenticator;
authenticator;
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”));
}}
}}
07-cs-test - 19
© Copyright 2016 Pivotal. All rights reserved - 129 - Version 4.3.b
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
07-cs-test - 20
© Copyright 2016 Pivotal. All rights reserved - 130 - Version 4.3.b
EasyMock
Example: Using a Mock - I
• Setup
– A Mock class is created at startup time
import static org.easymock.classextensions.EasyMock.*;
EasyMock
Example: Using a Mock - II
// … continued from previous slide
verify(accountRepository); Verification
}
} No planned method call
has been omitted
07-cs-test - 21
© Copyright 2016 Pivotal. All rights reserved - 131 - Version 4.3.b
Mockito
Same Example using Mockito
import static org.mockito.Mockito.*;
Mock Considerations
07-cs-test - 22
© Copyright 2016 Pivotal. All rights reserved - 132 - Version 4.3.b
Mocks or Stubs?
07-cs-test - 23
© Copyright 2016 Pivotal. All rights reserved - 133 - Version 4.3.b
Developing Aspects
with Spring AOP
Aspect Oriented Programming For
Declarative Enterprise Services
08-cs-aop - 1
© Copyright 2016 Pivotal. All rights reserved - 134 - Version 4.3.b
What Problem Does AOP Solve?
08-cs-aop - 2
© Copyright 2016 Pivotal. All rights reserved - 135 - Version 4.3.b
An Example Requirement
08-cs-aop - 3
© Copyright 2016 Pivotal. All rights reserved - 136 - Version 4.3.b
Symptom #1: Tangling
Account a = accountRepository.findByCreditCard(…
Restaurant r = restaurantRepository.findByMerchantNumber(…
MonetaryAmount amt = r.calculateBenefitFor(account, dining);
…
}
}
08-cs-aop - 4
© Copyright 2016 Pivotal. All rights reserved - 137 - Version 4.3.b
System Evolution Without Modularization
Security
Transactions Code
scattering
Logging
Code
tangling
08-cs-aop - 5
© Copyright 2016 Pivotal. All rights reserved - 138 - Version 4.3.b
How AOP Works
08-cs-aop - 6
© Copyright 2016 Pivotal. All rights reserved - 139 - Version 4.3.b
Leading AOP Technologies
• AspectJ
– Original AOP technology (first version in 1995)
– 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
08-cs-aop - 7
© Copyright 2016 Pivotal. All rights reserved - 140 - Version 4.3.b
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
08-cs-aop - 8
© Copyright 2016 Pivotal. All rights reserved - 141 - Version 4.3.b
AOP Quick Start
08-cs-aop - 9
© Copyright 2016 Pivotal. All rights reserved - 142 - Version 4.3.b
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…”);
}
}
OR
Using XML
<beans>
<aop:aspectj-autoproxy />
08-cs-aop - 10
© Copyright 2016 Pivotal. All rights reserved - 143 - Version 4.3.b
Include the 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”); }
}
@Autowired @Qualifier(”cacheA”);
private Cache cache;
…
cache.setCacheSize(2500);
08-cs-aop - 11
© Copyright 2016 Pivotal. All rights reserved - 144 - Version 4.3.b
How Aspects are Applied
setCacheSize()
<<interface>>
2. Proxy implements Cache
3. All calls routed target interface(s)
through proxy
interceptor
Spring AOP Proxy (this) Target
setCacheSize(2500) Method SimpleCache
Simple
Interceptor (target)
Cache
08-cs-aop - 12
© Copyright 2016 Pivotal. All rights reserved - 145 - Version 4.3.b
Topics in this session
Defining Pointcuts
08-cs-aop - 13
© Copyright 2016 Pivotal. All rights reserved - 146 - Version 4.3.b
Common Pointcut Designator
• execution(<method pattern>)
– The method must match the pattern
• Method Pattern
– [Modifiers] ReturnType [ClassType]
MethodName ([Arguments]) [throws ExceptionType]
Writing Expressions
execution(* rewards.restaurant.*Service.find*(..))
08-cs-aop - 14
© Copyright 2016 Pivotal. All rights reserved - 147 - Version 4.3.b
Execution Expression Examples
Any Class or Package
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
• Restrict by class
execution(void example.MessageServiceImpl.*(..))
– Any void method in the MessageServiceImpl class
• Including any sub-class
– But will be ignored if a different implementation is used
• Restrict by interface
execution(void example.MessageService.send(*))
– Any void send method taking one argument, in any object
implementing MessageService
– More flexible choice – works if implementation changes
08-cs-aop - 15
© Copyright 2016 Pivotal. All rights reserved - 148 - Version 4.3.b
Execution Expression Examples
Using Annotations
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
08-cs-aop - 16
© Copyright 2016 Pivotal. All rights reserved - 149 - Version 4.3.b
Topics in this session
Proxy
Proxy BeforeAdvice
BeforeAdvice Target
Target
08-cs-aop - 17
© Copyright 2016 Pivotal. All rights reserved - 150 - Version 4.3.b
Before Advice Example
@Before(“execution(void set*(*))”)
public void trackChange() {
logger.info(“Property about to change…”);
}
}
Proxy
Proxy AfterReturningAdvice
AfterReturningAdvice Target
Target
Successful return
08-cs-aop - 18
© Copyright 2016 Pivotal. All rights reserved - 151 - Version 4.3.b
After Returning Advice - Example
@AfterReturning(value=“execution(* service..*.*(..))”,
returning=“reward”)
public void audit(JoinPoint jp, Reward reward) {
auditService.logEvent(jp.getSignature() +
“ returns the following reward object :” + reward.toString() );
}
Proxy
Proxy AfterThrowingAdvice
AfterThrowingAdvice Target
Target
Exception
08-cs-aop - 19
© Copyright 2016 Pivotal. All rights reserved - 152 - Version 4.3.b
After Throwing Advice - Example
If you wish to stop the exception from propagating any further, you can
use an @Around advice (see later)
08-cs-aop - 20
© Copyright 2016 Pivotal. All rights reserved - 153 - Version 4.3.b
Advice Types: After
Proxy
Proxy AfterAdvice
AfterAdvice Target
Target
@After(“execution(void update*(..))”)
public void trackUpdate() {
logger.info(“An update has been attempted …”);
}
}
We don't know how the method terminated
08-cs-aop - 21
© Copyright 2016 Pivotal. All rights reserved - 154 - Version 4.3.b
Advice Types: Around
Proxy
Proxy AroundAdvice
AroundAdvice Target
Target
proceed()
@Around(“execution(@example.Cacheable * rewards.service..*.*(..))”)
public Object cache(ProceedingJoinPoint point) throws Throwable {
Object value = cacheStore.get(CacheUtils.toKey(point));
return value;
}
Cache values returned by cacheable services
08-cs-aop - 22
© Copyright 2016 Pivotal. All rights reserved - 155 - Version 4.3.b
Limitations of Spring AOP
Summary
08-cs-aop - 23
© Copyright 2016 Pivotal. All rights reserved - 156 - Version 4.3.b
Lab
Developing Aspects using Spring AOP
47
08-cs-aop - 24
© Copyright 2016 Pivotal. All rights reserved - 157 - Version 4.3.b
Alternative Spring AOP Syntax - XML
08-cs-aop - 25
© Copyright 2016 Pivotal. All rights reserved - 158 - Version 4.3.b
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>
08-cs-aop - 26
© Copyright 2016 Pivotal. All rights reserved - 159 - Version 4.3.b
Named Pointcuts in XML
<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>
@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() {}
}
The method name becomes the pointcut ID.
The method is not executed.
08-cs-aop - 27
© Copyright 2016 Pivotal. All rights reserved - 160 - Version 4.3.b
Named Pointcuts
@Aspect
public class ServiceMethodInvocationMonitor {
private Logger logger = Logger.getLogger(getClass());
@Before( “com.acme.Pointcuts.serviceMethods()” )
public void monitor() {
logger.info(“A service method has been accessed…”);
}
} Fully-qualified pointcut name
08-cs-aop - 28
© Copyright 2016 Pivotal. All rights reserved - 161 - Version 4.3.b
Topics in this session
08-cs-aop - 29
© Copyright 2016 Pivotal. All rights reserved - 162 - Version 4.3.b
Context Selecting Example
08-cs-aop - 30
© Copyright 2016 Pivotal. All rights reserved - 163 - Version 4.3.b
With Context Selection
@Before(“execution(void example.Server.start(java.util.Map))
&& target(server) && args(input)”)
public void logServerStartup(Server server, Map input) {
…
}
@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) {}
08-cs-aop - 31
© Copyright 2016 Pivotal. All rights reserved - 164 - Version 4.3.b
Topics in this session
08-cs-aop - 32
© Copyright 2016 Pivotal. All rights reserved - 165 - Version 4.3.b
AOP and Annotations - Example
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
}
08-cs-aop - 33
© Copyright 2016 Pivotal. All rights reserved - 166 - Version 4.3.b
Advanced Topics Summary
08-cs-aop - 34
© Copyright 2016 Pivotal. All rights reserved - 167 - Version 4.3.b
Introduction to Data
Management with
Spring
Implementing Data Access and Caching
09-cs-data-management - 1
© Copyright 2016 Pivotal. All rights reserved - 168 - Version 4.3.b
Spring Resource Management Works Everywhere
Works consistently with leading data access technologies
Jdbc
JDBC
Repository
Relational
Hibernate Database
Repository Hibernate
DataNucleus
EclipseLink EclipseLink
Hibernate
OpenJPA
JPA
other ...
Data Nucleus
Repository Apache MyBatis
• Steps Required
– Access a data source and establish a connection
– Begin a transaction
– Do the work – execute business logic
– Commit or rollback the transaction
– Close the connection
• Spring Advantages
– No code to implement (classic cross-cutting concern)
– No connection or session leakage
– Throws own exceptions, independent of underlying API
09-cs-data-management - 2
© Copyright 2016 Pivotal. All rights reserved - 169 - Version 4.3.b
Declarative Transaction Management
public class TransferServiceImpl implements TransferService {
@Transactional // marks method as needing a txn
public void transfer(…) { // your application logic }
}
Spring Proxy
Target
transfer(“$50”, “1”, 2”)
Spring
TransferServiceImpl
TransactionInterceptor
begin commit
Transaction
management
Transaction behavior is added
Manager around your code
09-cs-data-management - 3
© Copyright 2016 Pivotal. All rights reserved - 170 - Version 4.3.b
Where are my Transactions?
09-cs-data-management - 4
© Copyright 2016 Pivotal. All rights reserved - 171 - Version 4.3.b
Topics in this Session
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
09-cs-data-management - 5
© Copyright 2016 Pivotal. All rights reserved - 172 - Version 4.3.b
Data Access Exceptions
• SQLException
– Too general – one exception for every database error
– Calling class 'knows' you are using JDBC
– Tight coupling
• Spring provides DataAccessException hierarchy
– Hides whether you are using JPA, Hibernate, JDBC …
– Actually a hierarchy of sub-exceptions
• Not just one exception for everything
– Consistent across all supported Data Access technologies
– Unchecked
Example: BadSqlGrammarException
Select iddd from T_ACCOUNT
Plain JDBC Spring
java.sql.SQLException java.sql.SQLException
Message: Column not found: Message: Column not found:
IDDD in statement IDDD in statement
errorCode: -28 errorCode: -28
Error code mapping
BadSqlGrammarException
Message: PreparedStatementCallback;
bad SQL grammar … Column not found:
IDDD in statement
09-cs-data-management - 6
© Copyright 2016 Pivotal. All rights reserved - 173 - Version 4.3.b
Spring Data Access Exceptions
RuntimeException
DataAccessException
DataAccessResource DataIntegrity
FailureException ViolationException
CleanupFailure BadSqlGrammar
DataAccessException Exception
OptimisticLocking
...
FailureException
09-cs-data-management - 7
© Copyright 2016 Pivotal. All rights reserved - 174 - Version 4.3.b
Embedded Database Builder
@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();
}
09-cs-data-management - 8
© Copyright 2016 Pivotal. All rights reserved - 175 - Version 4.3.b
Initializing an Existing Test Database
XML provides jdbc:initialize-database
http://stackoverflow.com/questions/16038360
© Copyright 2014 Pivotal. All rights reserved. 18
09-cs-data-management - 9
© Copyright 2016 Pivotal. All rights reserved - 176 - Version 4.3.b
Initializing and Existing Test Database
Java Configuration is not so Easy … (continued)
– Bean can have any name, we won't use it (but Spring will)
http://stackoverflow.com/questions/16038360
© Copyright 2014 Pivotal. All rights reserved. 19
09-cs-data-management - 10
© Copyright 2016 Pivotal. All rights reserved - 177 - Version 4.3.b
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
Caching Support
Spring Application
@Cacheable("countries") In-memory
public Country[] loadAllCountries() { … } cache
09-cs-data-management - 11
© Copyright 2016 Pivotal. All rights reserved - 178 - Version 4.3.b
Caching with @Cacheable
@Cacheable(value="topBooks", key="#refId.toUpperCase()")
public Book findBook(String refId) {...}
@Cacheable(value="topBooks", key="T(example.KeyGen).hash(#author)")
public Book findBook3(Author author, boolean checkWarehouse) { ... }
custom key
@CacheEvict(value="topBooks")
generator
public void loadBooks() { ... }
clear cache before method invoked
...
09-cs-data-management - 12
© Copyright 2016 Pivotal. All rights reserved - 179 - Version 4.3.b
Enabling Caching Proxy
@Configuration
@EnableCaching
public class MyConfig {
@Bean
public BookService bookService() { … }
}
OR
<cache:annotation-driven />
09-cs-data-management - 13
© Copyright 2016 Pivotal. All rights reserved - 180 - Version 4.3.b
Setup Cache Manager
09-cs-data-management - 14
© Copyright 2016 Pivotal. All rights reserved - 181 - Version 4.3.b
Third-Party Cache Manager – EHCache
@Bean EHcache
public CacheManager cacheManager(CacheManager ehCache) {
EhCacheCacheManager cmgr = new EhCacheCacheManager();
cmgr.setCacheManager(ehCache);
Wrapper for an
return cmgr;
y EhCache cache
r
} facto s
te
crea ehcache.xml
@Bean EhCacheManagerFactoryBean
ehCacheManagerFactoryBean(String location) {
EhCacheManagerFactoryBean eh = new EhCacheManagerFactoryBean();
eh.setConfigLocation(context.getResource(location));
return eh;
}
09-cs-data-management - 15
© Copyright 2016 Pivotal. All rights reserved - 182 - Version 4.3.b
Spring Gemfire Project
09-cs-data-management - 16
© Copyright 2016 Pivotal. All rights reserved - 183 - Version 4.3.b
Not Only Relational
• 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 ...
09-cs-data-management - 17
© Copyright 2016 Pivotal. All rights reserved - 184 - Version 4.3.b
Summary
09-cs-data-management - 18
© Copyright 2016 Pivotal. All rights reserved - 185 - Version 4.3.b
Introduction to
Spring JDBC
Using JdbcTemplate
10-cs-jdbc - 1
© Copyright 2016 Pivotal. All rights reserved - 186 - Version 4.3.b
Redundant, Error Prone Code
10-cs-jdbc - 2
© Copyright 2016 Pivotal. All rights reserved - 187 - Version 4.3.b
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 {
try { What can
conn.close(); you do?
} catch (SQLException e) { /* ??? */ }
}
return personList;
}
10-cs-jdbc - 3
© Copyright 2016 Pivotal. All rights reserved - 188 - Version 4.3.b
Spring’s JdbcTemplate
JdbcTemplate in a Nutshell
10-cs-jdbc - 4
© Copyright 2016 Pivotal. All rights reserved - 189 - Version 4.3.b
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
}
}
Creating a JdbcTemplate
• Requires a DataSource
10-cs-jdbc - 5
© Copyright 2016 Pivotal. All rights reserved - 190 - Version 4.3.b
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)
10-cs-jdbc - 6
© Copyright 2016 Pivotal. All rights reserved - 191 - Version 4.3.b
Querying with JdbcTemplate
10-cs-jdbc - 7
© Copyright 2016 Pivotal. All rights reserved - 192 - Version 4.3.b
Query With Bind Variables
return jdbcTemplate.queryForObject
(sql, Integer.class, age, nationality.toString());
}
Generic Queries
10-cs-jdbc - 8
© Copyright 2016 Pivotal. All rights reserved - 193 - Version 4.3.b
Querying for Generic Maps (1)
• returns:
Map { ID=1, FIRST_NAME="John", LAST_NAME="Doe" }
10-cs-jdbc - 9
© Copyright 2016 Pivotal. All rights reserved - 194 - Version 4.3.b
Domain Object Queries
RowMapper
10-cs-jdbc - 10
© Copyright 2016 Pivotal. All rights reserved - 195 - Version 4.3.b
Querying for Domain Objects (1)
10-cs-jdbc - 11
© Copyright 2016 Pivotal. All rights reserved - 196 - Version 4.3.b
Querying for Domain Objects (3)
RowCallbackHandler
10-cs-jdbc - 12
© Copyright 2016 Pivotal. All rights reserved - 197 - Version 4.3.b
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"
10-cs-jdbc - 13
© Copyright 2016 Pivotal. All rights reserved - 198 - Version 4.3.b
ResultSetExtractor
10-cs-jdbc - 14
© Copyright 2016 Pivotal. All rights reserved - 199 - Version 4.3.b
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 = ?",
(ResultSetExtractor<Order>)(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;
}, public interface ResultSetExtractor<T> {
number); T extractData(ResultSet rs)
} throws SQLException, DataAccessException;
} }
• 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, especially large queries
• ResultSetExtractor
– Best choice when multiple rows of a ResultSet map to a
single object
10-cs-jdbc - 15
© Copyright 2016 Pivotal. All rights reserved - 200 - Version 4.3.b
Inserts and Updates (1)
10-cs-jdbc - 16
© Copyright 2016 Pivotal. All rights reserved - 201 - Version 4.3.b
Exception Handling
DataAccessException
CleanupFailure DataIntegrity
DataAccessException ViolationException
...
Summary
• JDBC is useful
– But using JDBC API directly is tedious and error-prone
• JdbcTemplate simplifies data access and enforces
consistency
– DRY principle hides most of the JDBC
– Many options for reading data
• SQLExceptions typically cannot be handled where
thrown
– Should not be checked Exceptions
– Spring provides DataAccessException instead
10-cs-jdbc - 17
© Copyright 2016 Pivotal. All rights reserved - 202 - Version 4.3.b
Lab
Reimplementing repositories using
Spring's JdbcTemplate
10-cs-jdbc - 18
© Copyright 2016 Pivotal. All rights reserved - 203 - Version 4.3.b
Transaction
Management with
Spring
Spring's Consistent Approach
11-cs-tx - 1
© Copyright 2016 Pivotal. All rights reserved - 204 - Version 4.3.b
What is a Transaction?
• 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
11-cs-tx - 2
© Copyright 2016 Pivotal. All rights reserved - 205 - Version 4.3.b
Transactions in the RewardNetwork
findByCreditCard(String)
1. SELECT
findByMerchantNumber(String)
2. SELECT
calculateBenefitFor(Account, Dining)
makeContribution(MonetaryAmount) 3. UPDATE
updateBeneficiaries(Account)
4. INSERT
confirmReward(AccountContribution, Dining)
DATABASE
Naïve Approach
Connection per Data Access Operation
11-cs-tx - 3
© Copyright 2016 Pivotal. All rights reserved - 206 - Version 4.3.b
Running non-Transactionally
findByCreditCard(String)
getConnection()
close() connection-1
findByMerchantNumber(String)
1. SELECT
getConnection()
close() connection-2 2. SELECT
updateBeneficiaries(Account)
3. UPDATE
getConnection()
close() connection-3
4. INSERT
confirmReward(AccountContribution, Dining)
getConnection()
close() connection-4
DATABASE
Partial Failures
11-cs-tx - 4
© Copyright 2016 Pivotal. All rights reserved - 207 - Version 4.3.b
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
Running in a Transaction
getConnection()
connection-1
findByCreditCard(String)
1. SELECT
findByMerchantNumber(String)
2. SELECT
updateBeneficiaries(Account)
3. UPDATE
close()
DATABASE
11-cs-tx - 5
© Copyright 2016 Pivotal. All rights reserved - 208 - Version 4.3.b
Topics in this session
11-cs-tx - 6
© Copyright 2016 Pivotal. All rights reserved - 209 - Version 4.3.b
Local and Global Transaction Management
Your
Application Database
…
Programatic
conn.commit(); Transaction
} catch (Exception e) { Demarcation
conn.rollback();
...
} Checked
Exceptions
11-cs-tx - 7
© Copyright 2016 Pivotal. All rights reserved - 210 - Version 4.3.b
JMS Transaction Management Example
try {
session = connection.createSession ( true, 0 ); Specific To
JMS API
…
session.commit();
} catch (Exception e) { Programatic
session.rollback(); Transaction
... Demarcation
}
Checked
Exceptions
API
Specific
// Hibernate // JPA
Transaction tx = Transaction tx =
session.beginTransaction(); entityManager.getTransaction();
tx.begin();
…
Programatic
Transaction …
Demarcation
tx.commit(); tx.commit();
11-cs-tx - 8
© Copyright 2016 Pivotal. All rights reserved - 211 - Version 4.3.b
Java Transaction API (JTA)
Example
try {
UserTransaction ut =
(UserTransaction) new InitialContext()
.lookup(“java:comp/UserTransaction”);
ut.begin();
…
Programatic
ut.commit(); Transaction
} catch (Exception e) { Demarcation
ut.rollback();
...
}
Checked
Exceptions
11-cs-tx - 9
© Copyright 2016 Pivotal. All rights reserved - 212 - Version 4.3.b
Topics in this session
11-cs-tx - 10
© Copyright 2016 Pivotal. All rights reserved - 213 - Version 4.3.b
Spring Transaction Management – 2
PlatformTransactionManager
11-cs-tx - 11
© Copyright 2016 Pivotal. All rights reserved - 214 - Version 4.3.b
Deploying the Transaction Manager
@Transactional Configuration
In your code
implements RewardNetwork {
public class RewardNetworkImpl
@Transactional
public RewardConfirmation rewardAccountFor(Dining d) {
// atomic unit-of-work
}
}
11-cs-tx - 12
© Copyright 2016 Pivotal. All rights reserved - 215 - Version 4.3.b
@Transactional: What Happens Exactly?
Spring Proxy
• Target object wrapped in a proxy
Reward
– Uses an Around advice 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
11-cs-tx - 13
© Copyright 2016 Pivotal. All rights reserved - 216 - Version 4.3.b
JDBC Java EE Configuration No code changes
Just configuration
Spring Proxy
Reward uses
NetworkImpl • How?
– Use container-managed
datasource (JNDI)
JdbcAccount JdbcCustomer – JTA Transaction
Repository Repository
Manager
• Purpose
JEE Container JTA – Deploy to JEE container
Managed Transaction
DataSource Manager <tx:jta-transaction-manager/>
11-cs-tx - 14
© Copyright 2016 Pivotal. All rights reserved - 217 - Version 4.3.b
@Transactional
– Class and method levels
• Combining class and method levels
default settings
@Transactional(timeout=60)
public class RewardNetworkImpl implements RewardNetwork {
11-cs-tx - 15
© Copyright 2016 Pivotal. All rights reserved - 218 - Version 4.3.b
Isolation levels
Dirty Reads
Transactions
should be
isolated –
unable to see
the results of
another
uncommitted
unit-of-work rollback X
11-cs-tx - 16
© Copyright 2016 Pivotal. All rights reserved - 219 - Version 4.3.b
READ_UNCOMMITTED
READ_COMMITTED
11-cs-tx - 17
© Copyright 2016 Pivotal. All rights reserved - 220 - Version 4.3.b
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
11-cs-tx - 18
© Copyright 2016 Pivotal. All rights reserved - 221 - Version 4.3.b
Understanding Transaction Propagation
A Single Transaction
B Transaction 1
Transaction 2
11-cs-tx - 19
© Copyright 2016 Pivotal. All rights reserved - 222 - Version 4.3.b
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 )
REQUIRED
• REQUIRED
– Default value
– Execute within a current transaction, create a new one if
none exists
tx1 tx1
tx1
no tx
@Transactional(propagation=Propagation.REQUIRED)
11-cs-tx - 20
© Copyright 2016 Pivotal. All rights reserved - 223 - Version 4.3.b
REQUIRES_NEW
• REQUIRES_NEW
– Create a new transaction, suspending the current
transaction if one exists
tx1
no tx
tx1 tx2
@Transactional(propagation=Propagation.REQUIRES_NEW)
11-cs-tx - 21
© Copyright 2016 Pivotal. All rights reserved - 224 - Version 4.3.b
Default Behavior
} Triggers a rollback
}
@Transactional(rollbackFor=MyCheckedException.class,
noRollbackFor={JmxException.class, MailException.class})
public RewardConfirmation rewardAccountFor(Dining d) throws Exception {
// ...
}
11-cs-tx - 22
© Copyright 2016 Pivotal. All rights reserved - 225 - Version 4.3.b
Topics in this session
@ContextConfiguration(classes=RewardsConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class RewardNetworkTest { This test is now
@Test @Transactional transactional
public void testRewardAccountFor() {
...
}
}
11-cs-tx - 23
© Copyright 2016 Pivotal. All rights reserved - 226 - Version 4.3.b
Controlling Transactional Tests
@ContextConfiguration(classes=RewardsConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
Make all tests
@Transactional transactional
public class RewardNetworkTest {
Commit transaction
@Test
at end of test
@Commit
public void testRewardAccountFor() {
... // Whatever happens here will be committed
}
}
Lab
Managing Transactions Declaratively
using Spring Annotations
11-cs-tx - 24
© Copyright 2016 Pivotal. All rights reserved - 227 - Version 4.3.b
Topics in this session
• Advanced topics
(1) XML Configuration
(2) Programmatic transactions
(3) Read-only transactions
(4) More on Transactional Tests
(5) Multiple and Global Transactions
(6) Propagation Options
<bean id=“transactionManager”
class=”org.springframework.jdbc.datasource.DataSourceTransactionManager”>
<property name=“dataSource” ref=“dataSource”/>
</bean>
A dataSource
must be defined
elsewhere
11-cs-tx - 25
© Copyright 2016 Pivotal. All rights reserved - 228 - Version 4.3.b
Automatic JTA Implementation Resolution
<tx:jta-transaction-manager/>
<bean id=“transactionManager”
class=”org.springframework.jdbc.datasource.DataSourceTransactionManager”>
<property name=“dataSource” ref=“dataSource”/>
</bean>
11-cs-tx - 26
© Copyright 2016 Pivotal. All rights reserved - 229 - Version 4.3.b
100% XML-based Spring Transactions
11-cs-tx - 27
© Copyright 2016 Pivotal. All rights reserved - 230 - Version 4.3.b
2. Programmatic Transactions with Spring
11-cs-tx - 28
© Copyright 2016 Pivotal. All rights reserved - 231 - Version 4.3.b
3. Read-only Transactions – Faster
@Transactional(readOnly=true, isolation=Isolation.REPEATABLE_READ)
public void importantAccounts() {
List accounts = jdbcTemplate.queryForList
("SELECT * FROM Accounts WHERE balance > 1000000");
process(accounts);
int nAccounts = jdbcTemplate.queryForInt
("SELECT count(*) FROM Accounts WHERE balance > 1000000");
assert accounts.size() == nAccounts;
}
11-cs-tx - 29
© Copyright 2016 Pivotal. All rights reserved - 232 - Version 4.3.b
4. Transactional Tests
@Before vs @BeforeTransaction
@ContextConfiguration(locations={"/rewards-config.xml"})
• @Before runs in the transaction
@RunWith(SpringJUnit4ClassRunner.class)
• @BeforeTransaction
public class RewardNetworkTestruns
{ 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() { … }
11-cs-tx - 30
© Copyright 2016 Pivotal. All rights reserved - 233 - Version 4.3.b
5. Multiple Transaction Managers
Global Transactions
Oracle
DB
Your Transaction
SQL
Application Manager
Server
Message
Queue
11-cs-tx - 31
© Copyright 2016 Pivotal. All rights reserved - 234 - Version 4.3.b
Global Transactions → Spring Integration
11-cs-tx - 32
© Copyright 2016 Pivotal. All rights reserved - 235 - Version 4.3.b
JPA with Spring
and Spring Data
Object Relational Mapping with
Spring & Java Persistence API
• Introduction to JPA
– General Concepts
– Mapping
– Querying
• Configuring JPA in Spring
• Implementing JPA DAOs
• Spring Data – JPA
• Lab
• Optional and Advanced Topics
12-cs-jpa-spring-data - 1
© Copyright 2016 Pivotal. All rights reserved - 236 - Version 4.3.b
Introduction to JPA
About JPA
12-cs-jpa-spring-data - 2
© Copyright 2016 Pivotal. All rights reserved - 237 - Version 4.3.b
JPA Configuration
• Persistence Unit
– Describes a group of persistent classes (entities)
– Defines provider(s)
– Defines transactional types (local vs JTA)
– Multiple Units per application are allowed
– Defined by the file: persistence.xml
• EntityManager
– Manages a unit of work and persistent objects therein: the
PersistenceContext
– Lifecycle often bound to a Transaction (usually container-
managed)
• EntityManagerFactory
– thread-safe, shareable object that represents a single data
source / persistence unit
– Provides access to new application-managed
EntityManagers
12-cs-jpa-spring-data - 3
© Copyright 2016 Pivotal. All rights reserved - 238 - Version 4.3.b
Persistence Context and EntityManager
Entity
Manager
creates
Factory
12-cs-jpa-spring-data - 4
© Copyright 2016 Pivotal. All rights reserved - 239 - Version 4.3.b
JPA Providers
Hibernate JPA
Hibernate
Implementation
12-cs-jpa-spring-data - 5
© Copyright 2016 Pivotal. All rights reserved - 240 - Version 4.3.b
JPA Mapping
• 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
12-cs-jpa-spring-data - 6
© Copyright 2016 Pivotal. All rights reserved - 241 - Version 4.3.b
Mapping Using Fields (Data-Members)
Mark as an entity
@Entity
@Entity
Optionally override
@Table(name=
@Table(name= “T_CUSTOMER”)
“T_CUSTOMER”)
table name
public
public class
class Customer
Customer {{
@Id
@Id Mark id-field
@Column(name=“cust_id”)
@Column(name=“cust_id”) (primary key)
private
private Long
Long id;
id;
Optionally override
@Column(name=“first_name”)
@Column(name=“first_name”) column names
private
private String
String firstName;
firstName;
Not stored in database
@Transient
@Transient
private
private User
User currentUser;
currentUser; Data members set directly
- using reflection
...
... - “field” access
Only @Entity and @Id are mandatory - no setters needed
@Id
@Id
@Column
@Column (name=“cust_id”)
(name=“cust_id”)
Other annotations now also public
public Long
Long getId()
getId()
placed on getter methods {{ return
return this.id;
this.id; }}
@Column
@Column (name=“first_name”)
(name=“first_name”)
public
public String
String getFirstName()
getFirstName()
{{ return
return this.firstName;
this.firstName; }}
public
public void
void setFirstName(String
setFirstName(String fn)
fn)
{{ this.firstName
this.firstName == fn;
fn; }}
}}
12-cs-jpa-spring-data - 7
© Copyright 2016 Pivotal. All rights reserved - 242 - Version 4.3.b
Relationships
• Common relationship mappings supported
– Single entities and entity collections both supported
– Associations can be uni- or bi-directional
@Entity
@Entity @Table(name= “T_ADDRESS”)
@Table(name= “T_CUSTOMER”) public class Address {
public class Customer { @Id private Long id;
@Id private String street;
@Column (name=“cust_id”) private String suburb;
private Long id; private String city;
private String postcode;
@OneToMany private String country;
}
@JoinColumn (name=“cid”)
private Set<Address> addresses; Foreign key in
… Address table
Embeddables
12-cs-jpa-spring-data - 8
© Copyright 2016 Pivotal. All rights reserved - 243 - Version 4.3.b
JPA Querying
12-cs-jpa-spring-data - 9
© Copyright 2016 Pivotal. All rights reserved - 244 - Version 4.3.b
JPA Querying: JPQL
- SELECT clause required
- can't use *
• Introduction to JPA
– General Concepts
– Mapping
– Querying
• Configuring JPA in Spring
• Implementing JPA DAOs
• Spring Data – JPA
• Lab
• Optional and Advanced Topics
12-cs-jpa-spring-data - 10
© Copyright 2016 Pivotal. All rights reserved - 245 - Version 4.3.b
Quick Start – Spring JPA Configuration
LocalContainerEntityManagerFactoryBean emfb =
new LocalContainerEntityManagerFactoryBean();
emfb.setDataSource(dataSource);
emfb.setPackagesToScan("rewards.internal");
emfb.setJpaProperties(props); NOTE: no persistence.xml
emfb.setJpaVendorAdapter(adapter); needed when using
packagesToScan property
return emfb;
}
12-cs-jpa-spring-data - 11
© Copyright 2016 Pivotal. All rights reserved - 246 - Version 4.3.b
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>
@Bean
public DataSource dataSource() { // Lookup via JNDI or create locally. }
12-cs-jpa-spring-data - 12
© Copyright 2016 Pivotal. All rights reserved - 247 - Version 4.3.b
EntityManagerFactoryBean Configuration
CustomerServiceImpl
DataSource
JPA
LocalContainer Entity CustomerRepository
creates
EntityManager Manager
FactoryBean Factory
creates EntityManager
Spring Proxy
• Introduction to JPA
– General Concepts
– Mapping
– Querying
• Configuring JPA in Spring
• Implementing JPA DAOs
• Spring Data – JPA
• Lab
• Optional and Advanced Topics
12-cs-jpa-spring-data - 13
© Copyright 2016 Pivotal. All rights reserved - 248 - Version 4.3.b
Implementing JPA DAOs
12-cs-jpa-spring-data - 14
© Copyright 2016 Pivotal. All rights reserved - 249 - Version 4.3.b
Spring-Managed Transactions &
EntityManager (2)
• The code – no Spring dependencies
@Bean
public CustomerRepository jpaCustomerRepository() { Automatic injection of
return new JpaCustomerRepository(); entity-manager proxy
}
@Bean
public PlatformTransactionManager
transactionManager(EntityManagerFactory emf) throws Exception {
return new JpaTransactionManager(emf);
}
12-cs-jpa-spring-data - 15
© Copyright 2016 Pivotal. All rights reserved - 250 - Version 4.3.b
How it Works (JPA)
Spring AOP Proxy
invoke(input)
Spring
CustomerServiceImpl
TransactionInterceptor
invoke(input)
Spring
CustomerServiceImpl
TransactionInterceptor
Service
proxy handles get order
transaction begin commit data Proxy gets EM
for current txn
JtaTransaction
CustomerRepository
Manager
12-cs-jpa-spring-data - 16
© Copyright 2016 Pivotal. All rights reserved - 251 - Version 4.3.b
Topics in this session
• Introduction to JPA
– General Concepts
– Mapping
– Querying
• Configuring JPA in Spring
• Implementing JPA DAOs
• Spring Data – JPA
• Lab
• Optional and Advanced Topics
12-cs-jpa-spring-data - 17
© Copyright 2016 Pivotal. All rights reserved - 252 - Version 4.3.b
Instant Repositories
• How?
– Step 1: Annotate domain class
• define keys & enable persistence
– Step 2: Define your repository as an interface
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private Date oderDate;
private String email; Note: Key is a Long
12-cs-jpa-spring-data - 18
© Copyright 2016 Pivotal. All rights reserved - 253 - Version 4.3.b
Domain Objects: Other Data Stores
12-cs-jpa-spring-data - 19
© Copyright 2016 Pivotal. All rights reserved - 254 - Version 4.3.b
Generating Repositories
• XML
<jpa:repositories base-package="com.acme.**.repository" />
<mongo:repositories base-package="com.acme.**.repository" />
<gfe:repositories base-package="com.acme.**.repository" />
12-cs-jpa-spring-data - 20
© Copyright 2016 Pivotal. All rights reserved - 255 - Version 4.3.b
Extend Repository
Convention over Configuration and build your own
interface using
conventions.
Interface Interface
CustomerRepository CustomerRepository
implements
$Proxy1
@Configuration
@EnableJpaRepositories(basePackages="com.acme.repository")
public class CustomerConfig { … }
<jpa:repositories base-package="com.acme.repository"/>
12-cs-jpa-spring-data - 21
© Copyright 2016 Pivotal. All rights reserved - 256 - Version 4.3.b
Accessing the Repository
@Configuration
@EnableJpaRepositories(basePackages="com.acme.repository")
public class CustomerConfig {
@Autowired
public CustomerRepository customerRepository;
@Bean
public CustomerService customerService() {
return new CustomerService( customerRepository );
}
}
Summary
12-cs-jpa-spring-data - 22
© Copyright 2016 Pivotal. All rights reserved - 257 - Version 4.3.b
Lab
Reimplementing Repositories using
Spring and JPA
• Introduction to JPA
• Configuring JPA in Spring
• Implementing JPA DAOs
• Spring Data – JPA
• Lab
• Optional and Advanced Topics
– JPA Typed Queries / Native Queries
– EntityManagerFactoryBean alternatives / persistence.xml
– Exception Translation
– Customized Spring Data Repositories
12-cs-jpa-spring-data - 23
© Copyright 2016 Pivotal. All rights reserved - 258 - Version 4.3.b
JPA Querying: Typed Queries
12-cs-jpa-spring-data - 24
© Copyright 2016 Pivotal. All rights reserved - 259 - Version 4.3.b
Topics in this session
• Introduction to JPA
• Configuring JPA in Spring
• Implementing JPA DAOs
• Spring Data – JPA
• Lab
• Optional and Advanced Topics
– JPA Typed Queries / Native Queries
– EntityManagerFactoryBean alternatives / persistence.xml
– Exception Translation
– Customized Spring Data Repositories
Setting up an EntityManagerFactory
12-cs-jpa-spring-data - 25
© Copyright 2016 Pivotal. All rights reserved - 260 - Version 4.3.b
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!
LocalEntityManagerFactoryBean
@Bean
public LocalEntityManagerFactoryBean entityManagerFactory() {
LocalEntityManagerFactoryBean em =
new LocalEntityManagerFactoryBean();
em.setPersistenceUnitName(“rewardNetwork”);
return em;
}
12-cs-jpa-spring-data - 26
© Copyright 2016 Pivotal. All rights reserved - 261 - Version 4.3.b
LocalContainer
EntityManagerFactoryBean
• Provides full JPA capabilities
• Integrates with existing DataSources
• Useful when fine-grained customization needed
– Can specify vendor-specific configuration
Persistence
Configuration – Spring and Unit
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean emfb =
new LocalContainerEntityManagerFactoryBean(); Minimal Spring config
emfb.setDataSource(dataSource);
emfb.setPersistenceUnitName("rewardNetwork");
return emfb;
} <persistence-unit name="rewardNetwork">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.dialect"
Do JPA config in value="org.hibernate.dialect.HSQLDialect"/>
persistence.xml <property name="hibernate.hbm2ddl.auto" value="create"/>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
12-cs-jpa-spring-data - 27
© Copyright 2016 Pivotal. All rights reserved - 262 - Version 4.3.b
JNDI Lookups
OR
• Introduction to JPA
• Configuring JPA in Spring
• Implementing JPA DAOs
• Spring Data – JPA
• Lab
• Optional and Advanced Topics
– JPA Typed Queries / Native Queries
– EntityManagerFactoryBean alternatives / persistence.xml
– Exception Translation
– Customized Spring Data Repositories
12-cs-jpa-spring-data - 28
© Copyright 2016 Pivotal. All rights reserved - 263 - Version 4.3.b
Transparent Exception Translation (1)
@Repository
public class JpaCustomerRepository implements CustomerRepository {
...
}
<bean class=“org.springframework.dao.annotation.
PersistenceExceptionTranslationPostProcessor”/>
12-cs-jpa-spring-data - 29
© Copyright 2016 Pivotal. All rights reserved - 264 - Version 4.3.b
Transparent Exception Translation (3)
<bean id=“persistenceExceptionInterceptor”
class=“org.springframework.dao.support.
PersistenceExceptionTranslationInterceptor”/>
<aop:config>
<aop:advisor pointcut=“execution(* *..CustomerRepository+.*(..))”
advice-ref=“persistenceExceptionInterceptor” />
</aop:config>
• Introduction to JPA
• Configuring JPA in Spring
• Implementing JPA DAOs
• Spring Data – JPA
• Lab
• Optional and Advanced Topics
– JPA Typed Queries / Native Queries
– EntityManagerFactoryBean alternatives / persistence.xml
– Exception Translation
– Customized Spring Data Repositories
12-cs-jpa-spring-data - 30
© Copyright 2016 Pivotal. All rights reserved - 265 - Version 4.3.b
JPA Specific Interface
12-cs-jpa-spring-data - 31
© Copyright 2016 Pivotal. All rights reserved - 266 - Version 4.3.b
Adding Custom Behavior (2)
Topics Covered
• Introduction to JPA
• Configuring JPA in Spring
• Implementing JPA DAOs
• Spring Data – JPA
• Advanced
– JPA Typed Queries / Native Queries
– EntityManagerFactoryBean alternatives and
persistence.xml
– Exception Translation
– Customized Spring Data Repositories
12-cs-jpa-spring-data - 32
© Copyright 2016 Pivotal. All rights reserved - 267 - Version 4.3.b
Overview of Spring
Web
Developing Modern Web Applications
• Introduction
• Using Spring in Web Applications
• Overview of Spring Web
• Spring and other Web frameworks
13-cs-web-intro - 1
© Copyright 2016 Pivotal. All rights reserved - 268 - Version 4.3.b
Web Layer Integration
• However, you are free to use Spring with any Java web
framework
– Integration might be provided by Spring or by the other
framework itself
– Spring also integrates with many of the common REST
frameworks
Clients
Web Layer
Application Layer
(Spring)
13-cs-web-intro - 2
© Copyright 2016 Pivotal. All rights reserved - 269 - Version 4.3.b
Topics in this Session
• Introduction
• Using Spring in Web Applications
• Overview of Spring Web
• Spring and other Web frameworks
13-cs-web-intro - 3
© Copyright 2016 Pivotal. All rights reserved - 270 - Version 4.3.b
Configuration via WebApplicationInitializer
public class MyWebAppInitializer Implements
WebApplicationInitializer
extends AbstractContextLoaderInitializer {
Automatically detected
by servlet container.
@Override
protected WebApplicationContext createRootApplicationContext() {
rootContext.getEnvironment().setActiveProfiles("jpa"); // optional
rootContext.register(RootConfig.class);
return rootContext; Multiple classes
} may be listed
...
Available in Servlet 3.0+ Environments, no more web.xml!
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener> Loads the ApplicationContext into the ServletContext
before any Servlets are initialized
13-cs-web-intro - 4
© Copyright 2016 Pivotal. All rights reserved - 271 - Version 4.3.b
web.xml Configuration Options
Servlet
Context Root ApplicationContext
Application Layer
(Spring) Bound in ServletContext
under a well-known name
Now accessible to
any Servlet or other
web-layer artifact
13-cs-web-intro - 5
© Copyright 2016 Pivotal. All rights reserved - 272 - Version 4.3.b
Instantiating Servlets
• Override onStartup() method to define servlets
– Warning: Can't access Spring beans, not available yet
public class MyWebAppInitializer extends AbstractContextLoaderInitializer {
13-cs-web-intro - 6
© Copyright 2016 Pivotal. All rights reserved - 273 - Version 4.3.b
Spring MVC Supports Dependency Injection
@Autowired
public TopSpendersReportController(ClientService service) {
this.clientService = service;
}
Dependency is automatically injected by type
…
}
• Introduction
• Using Spring in Web Applications
• Overview of Spring Web
• Spring and other Web frameworks
13-cs-web-intro - 7
© Copyright 2016 Pivotal. All rights reserved - 274 - Version 4.3.b
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.
13-cs-web-intro - 8
© Copyright 2016 Pivotal. All rights reserved - 275 - Version 4.3.b
Spring Web Flow
<end-state id="finish"/>
</flow>
13-cs-web-intro - 9
© Copyright 2016 Pivotal. All rights reserved - 276 - Version 4.3.b
More about WebFlow
• Introduction
• Using Spring in Web Applications
• Overview of Spring Web
• Spring and other Web frameworks
13-cs-web-intro - 10
© Copyright 2016 Pivotal. All rights reserved - 277 - Version 4.3.b
Spring – Struts 2 Integration
Java Configuration
@Action("/doLogin")
@ResultPath("/WEB-INF/views")
@Result(name = "success", location = "LoginSuccess.jsp"),
@Result(name = "error", location = "LoginError.jsp")
public class DoLoginAction extends ActionSupport {
@Autowired
private UserDAO userDAO;
private User user; Inject Spring Beans in
... The normal way
return ERROR;
}
}
13-cs-web-intro - 11
© Copyright 2016 Pivotal. All rights reserved - 278 - Version 4.3.b
Spring – JSF Integration
• Two options
– Spring-centric integration
• Provided by Spring Faces sub-project of Spring Web Flow
– JSF-centric integration
• Spring plugs in as as the 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>
</managed-property> JSF-centric integration
</managed-bean>
• Wicket
– Comes with an integration to Spring
https://cwiki.apache.org/confluence/display/WICKET/Spring
• Tapestry 5
– Provides a dedicated integration module for Spring
https://tapestry.apache.org/integrating-with-spring-framework.html
13-cs-web-intro - 12
© Copyright 2016 Pivotal. All rights reserved - 279 - Version 4.3.b
Summary
13-cs-web-intro - 13
© Copyright 2016 Pivotal. All rights reserved - 280 - Version 4.3.b
Spring Web MVC
Essentials
Getting Started With Spring MVC
14-cs-mvc - 1
© Copyright 2016 Pivotal. All rights reserved - 281 - Version 4.3.b
Topics in this Session
• Key Artifacts
– DispatcherServlet
– Controllers
– Views
• Quick Start
14-cs-mvc - 2
© Copyright 2016 Pivotal. All rights reserved - 282 - Version 4.3.b
Request Processing Lifecycle
Co
name)
ns
ul
render
ts
(v
ie
w)
Model
View
Resolver
Resolver(s)
View
• Key Artifacts
– DispatcherServlet
– Controllers
– Views
• Quick Start
14-cs-mvc - 3
© Copyright 2016 Pivotal. All rights reserved - 283 - Version 4.3.b
DispatcherServlet:
The Heart of Spring Web MVC
• A “front controller”
– coordinates all request handling activities
– analogous to Struts ActionServlet / JSF FacesServlet
• Fully customizable
– interfaces for all infrastructure beans
– many extension points
DispatcherServlet Configuration
14-cs-mvc - 4
© Copyright 2016 Pivotal. All rights reserved - 284 - Version 4.3.b
Dispatcher Servlet
Java Configuration Example
Servlet 3.0+
public class MyWebInitializer
extends AbstractAnnotationConfigDispatcherServletInitializer {
14-cs-mvc - 5
© Copyright 2016 Pivotal. All rights reserved - 285 - Version 4.3.b
Dispatcher Servlet
XML 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>/rewardsadmin/*</url-pattern>
</servlet-mapping> web.xml
Pre-Servlet 3.0
14-cs-mvc - 6
© Copyright 2016 Pivotal. All rights reserved - 286 - Version 4.3.b
Topics in this Session
• Key Artifacts
– DispatcherServlet
– Controllers
– Views
• Quick Start
Controller Implementation
@Controller
public class AccountController {
@RequestMapping("/listAccounts")
public String list(Model model) {...}
}
Example of calling URL:
http://localhost:8080 / mvc-1 / rewardsadmin / listAccounts
14-cs-mvc - 7
© Copyright 2016 Pivotal. All rights reserved - 287 - Version 4.3.b
URL-Based Mapping Rules
• 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) {
...
} Model holds data for view
View name
}
14-cs-mvc - 8
© Copyright 2016 Pivotal. All rights reserved - 288 - Version 4.3.b
Extracting Request Parameters
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
14-cs-mvc - 9
© Copyright 2016 Pivotal. All rights reserved - 289 - Version 4.3.b
Method Signature Examples Example URLs
http://.../accounts
@RequestMapping("/accounts")
public String show(HttpServletRequest request, Model model)
http://.../orders/1234/items/2
@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") http://.../orders?id=1234&itemId=2
public String show(@RequestParam Long id,
@RequestParam(“itemId”) int itemId,
Principal user, Map<String,Object> model,
View name HttpSession session )
• Key Artifacts
– DispatcherServlet
– Controllers
– Views
• Quick Start
14-cs-mvc - 10
© Copyright 2016 Pivotal. All rights reserved - 290 - Version 4.3.b
Views
View Resolvers
14-cs-mvc - 11
© Copyright 2016 Pivotal. All rights reserved - 291 - Version 4.3.b
Internal Resource View Resolver Example
request (URL) Dispatcher handle GET /reward/list
response Servlet Model Controller
“rewardList”
co
ns
Logical view name
ul
render
Vi
ts
ew
Model View Resolved
Resolver Physical Path
JstlView /WEB-INF/views/rewardList.jsp
@Bean
public ViewResolver simpleViewResolver() {
InternalResourceViewResolver vr =
- WEB-INF new InternalResourceViewResolver();
- views vr.setPrefix ( "/WEB-INF/views/" );
rewardList.jsp vr.setSuffix ( ".jsp" );
return vr;
}
• Key Artifacts
– DispatcherServlet
– Controllers
– Views
• Quick Start
14-cs-mvc - 12
© Copyright 2016 Pivotal. All rights reserved - 292 - Version 4.3.b
Quick Start
// Root context:
@Override protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{ RootConfig.class };
}
Services, Repositories ...
// 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/*"};
}
14-cs-mvc - 13
© Copyright 2016 Pivotal. All rights reserved - 293 - Version 4.3.b
1b. Deploy DispatcherServlet
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
14-cs-mvc - 14
© Copyright 2016 Pivotal. All rights reserved - 294 - Version 4.3.b
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,
Model model) { Automatically filled
Reward reward = lookupService.lookupReward(id); in by Spring
model.addAttribute(“reward”, reward);
return “rewardView”;
} Selects the “rewardView” to
} to render the reward
@Configuration
@EnableWebMvc
@ComponentScan("accounts.web")
public class MvcConfig() {
14-cs-mvc - 15
© Copyright 2016 Pivotal. All rights reserved - 295 - Version 4.3.b
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>
</html> References result model object by name
/WEB-INF/views/rewardView.jsp
5. Register ViewResolver
@Configuration
@EnableWebMvc
@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
14-cs-mvc - 16
© Copyright 2016 Pivotal. All rights reserved - 296 - Version 4.3.b
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
Summary
Learn More:
Spring-Web – 4 day course on Spring Web Modules
14-cs-mvc - 17
© Copyright 2016 Pivotal. All rights reserved - 297 - Version 4.3.b
Lab
Adding a Web Interface
14-cs-mvc - 18
© Copyright 2016 Pivotal. All rights reserved - 298 - Version 4.3.b
@EnableWebMvc
@Configuration
@EnableWebMvc
public class RewardConfig {
@Bean
public rewardController(RewardLookupService service) {
return new RewardController(service);
}
...
WebMvcConfigurerAdapter
@Configuration
@EnableWebMvc
public class RewardConfig extends WebMvcConfigurerAdapter {
@Override
public void addFormatters(FormatterRegistry registry) {
// Register your own type converters and formatters...
}
Example: add
... custom formatters
14-cs-mvc - 19
© Copyright 2016 Pivotal. All rights reserved - 299 - Version 4.3.b
MVC Namespace
<!-- Provides default conversion service, validator and message converters -->
<mvc:annotation-driven/>
Learn More:
Spring-Web – 4 day course on Spring Web Modules
14-cs-mvc - 20
© Copyright 2016 Pivotal. All rights reserved - 300 - Version 4.3.b
Spring Boot - Basics
Getting started with Spring Boot
15-cs-spring-boot-basics - 1
© Copyright 2016 Pivotal. All rights reserved - 301 - Version 4.3.b
What is Spring Boot?
• It is not:
– A code generator
– An IDE plugin
15-cs-spring-boot-basics - 2
© Copyright 2016 Pivotal. All rights reserved - 302 - Version 4.3.b
Opinionated Runtime?
pom.xml
Setup Spring Boot dependencies
HelloController class
Basic Spring MVC controller
application.properties hello.jsp
View setup
Application class
Application launcher
15-cs-spring-boot-basics - 3
© Copyright 2016 Pivotal. All rights reserved - 303 - Version 4.3.b
Hello World (1) – Maven descriptor
<parent>
<groupId>org.springframework.boot</groupId> parent
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build> pom.xml
Maven is just one option. You can also use Gradle or Ant/Ivy
@Controller
public class HelloController { Nothing to do, just
@RequestMapping("/") return view name
public String hello() {
return "hello";
}
} Controller.java
15-cs-spring-boot-basics - 4
© Copyright 2016 Pivotal. All rights reserved - 304 - Version 4.3.b
Hello World (3) – Implement the View
<html>
<head><title>Hello</title></head>
<body>
<p>Hello Spring Boot</p>
</body>
</html> /WEB-INF/views/hello.jsp
application.properties
spring.mvc.view.prefix=/WEB-INF/views
spring.mvc.view.suffix=.jsp
Configure an InternalResourceViewResolver
@SpringBootApplication
public class Application {
} application.java
Main method will be used to run the packaged application from the
command line – old style!
15-cs-spring-boot-basics - 5
© Copyright 2016 Pivotal. All rights reserved - 305 - Version 4.3.b
Putting it all together
Maven command to generate an
mvn package archive file
Deployment
15-cs-spring-boot-basics - 6
© Copyright 2016 Pivotal. All rights reserved - 306 - Version 4.3.b
Topics in this Session
15-cs-spring-boot-basics - 7
© Copyright 2016 Pivotal. All rights reserved - 307 - Version 4.3.b
Spring Boot Parent POM
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>
15-cs-spring-boot-basics - 8
© Copyright 2016 Pivotal. All rights reserved - 308 - Version 4.3.b
Spring Web Dependencies
Test Dependencies
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
Resolves
spring-test-*.jar
junit-*.jar
mockito-*.jar
…
15-cs-spring-boot-basics - 9
© Copyright 2016 Pivotal. All rights reserved - 309 - Version 4.3.b
Available Starter POMs
• Not essential but strongly recommended
• Coordinated dependencies for common Java enterprise
frameworks
– Pick the starters you need in your project
• To name a few:
– spring-boot-starter-jdbc
– spring-boot-starter-jpa
– spring-boot-starter-batch
15-cs-spring-boot-basics - 10
© Copyright 2016 Pivotal. All rights reserved - 310 - Version 4.3.b
Spring Boot @EnableAutoConfiguration
@Configuration
@EnableAutoConfiguration
public class MyAppConfig {
public static void main(String[] args) {
SpringApplication.run(MyAppConfig.class, args);
}
}
Spring Boot class
Shortcut @SpringBootApplication
@Configuration
@ComponentScan
@EnableAutoConfiguration @SpringBootApplication
public class MyAppConfig { public class MyAppConfig {
... ...
} }
15-cs-spring-boot-basics - 11
© Copyright 2016 Pivotal. All rights reserved - 311 - Version 4.3.b
Auto-configuration: Examples
At Runtime, Spring What Spring
What you include
Boot checks if Boot does
Spring MVC on DispatcherServlet
Starter Web
classpath registered
Embedded
HSQLDB HSQLDB, H2 or
DataSource
dependency Derby on classpath
registered
If DataSource JdbcTemplate
Starter JDBC
registered registered
15-cs-spring-boot-basics - 12
© Copyright 2016 Pivotal. All rights reserved - 312 - Version 4.3.b
Packaging
Maven Packaging
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
15-cs-spring-boot-basics - 13
© Copyright 2016 Pivotal. All rights reserved - 313 - Version 4.3.b
Packaging Result
22M yourapp-0.0.1-SNAPSHOT.jar
5K yourapp-0.0.1-SNAPSHOT.jar.original
15-cs-spring-boot-basics - 14
© Copyright 2016 Pivotal. All rights reserved - 314 - Version 4.3.b
Spring Boot as a Runtime
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Jetty Support
15-cs-spring-boot-basics - 15
© Copyright 2016 Pivotal. All rights reserved - 315 - Version 4.3.b
JAR vs WAR?
15-cs-spring-boot-basics - 16
© Copyright 2016 Pivotal. All rights reserved - 316 - Version 4.3.b
Spring Boot in a Servlet Container
15-cs-spring-boot-basics - 17
© Copyright 2016 Pivotal. All rights reserved - 317 - Version 4.3.b
Spring Boot in a Servlet Container
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
22M yourapp-0.0.1-SNAPSHOT.war
20M yourapp-0.0.1-SNAPSHOT.war.original
15-cs-spring-boot-basics - 18
© Copyright 2016 Pivotal. All rights reserved - 318 - Version 4.3.b
Servlet Container and Containerless
@SpringBootApplication
public class Application extends SpringBootServletInitializer {
15-cs-spring-boot-basics - 19
© Copyright 2016 Pivotal. All rights reserved - 319 - Version 4.3.b
Topics in this session
Externalized Properties – 1
application.properties
15-cs-spring-boot-basics - 20
© Copyright 2016 Pivotal. All rights reserved - 320 - Version 4.3.b
Externalized Properties – 2
application.properties
Externalized Properties – 3
YAML Alternative
database:
host: localhost
user: admin
application.yml
15-cs-spring-boot-basics - 21
© Copyright 2016 Pivotal. All rights reserved - 321 - Version 4.3.b
Controlling Logging Level
logging.level.org.springframework=DEBUG
logging.level.com.acme.your.code=INFO
application.properties
DataSource Configuration
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 the library is found on
the classpath!
15-cs-spring-boot-basics - 22
© Copyright 2016 Pivotal. All rights reserved - 322 - Version 4.3.b
Web Application Convenience – 1
Bottom Line: Most Spring Boot web applications do not specify @EnableWebMvc
15-cs-spring-boot-basics - 23
© Copyright 2016 Pivotal. All rights reserved - 323 - Version 4.3.b
Summary
Lab
Simplification using Spring Boot
15-cs-spring-boot-basics - 24
© Copyright 2016 Pivotal. All rights reserved - 324 - Version 4.3.b
Spring Boot – Going
Further
Going beyond default settings
• Understanding Auto-Configuration
• Customizing Spring Boot
• More on Properties
• Fine-tuning Logging
• Using YAML for Configuration
• Testing
16-cs-spring-boot-adv - 1
© Copyright 2016 Pivotal. All rights reserved - 325 - Version 4.3.b
How Does Spring Boot Work?
@Conditional Annotations
16-cs-spring-boot-adv - 2
© Copyright 2016 Pivotal. All rights reserved - 326 - Version 4.3.b
What are AutoConfiguration Classes
• Understanding Auto-Configuration
• Customizing Spring Boot
• More on Properties
• Fine-tuning Logging
• Using YAML for Configuration
• Testing
16-cs-spring-boot-adv - 3
© Copyright 2016 Pivotal. All rights reserved - 327 - Version 4.3.b
Controlling What Spring Boot does
1. Using Properties
16-cs-spring-boot-adv - 4
© Copyright 2016 Pivotal. All rights reserved - 328 - Version 4.3.b
2. Replacing Generated Beans
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder().
setName("RewardsDb").build();
}
@EnableAutoConfiguration(exclude=DataSourceAutoConfiguration.class)
public class ApplicationConfiguration {
…
}
16-cs-spring-boot-adv - 5
© Copyright 2016 Pivotal. All rights reserved - 329 - Version 4.3.b
4a. Overriding Dependency Versions
<properties>
<spring.version>4.2.0.RELEASE</spring.version>
</properties>
This only works if you inherit from the starter. You need to redefine the
artifact if you directly import the dependency
16-cs-spring-boot-adv - 6
© Copyright 2016 Pivotal. All rights reserved - 330 - Version 4.3.b
Configuration Example: DataSource (1)
• Typical customizations
– Use the predefined properties
– Change the underlying data source connection pool
implementation
– Define your own DataSource
bean (shown earlier)
?
16-cs-spring-boot-adv - 7
© Copyright 2016 Pivotal. All rights reserved - 331 - Version 4.3.b
Example: DataSource Configuration (3)
Pool
DB
• Also available
– SSL (keystore, truststore for client authentication)
– Tomcat specifics (access log, compression, etc)
16-cs-spring-boot-adv - 8
© Copyright 2016 Pivotal. All rights reserved - 332 - Version 4.3.b
Topics in this Session
• Understanding Auto-Configuration
• Customizing Spring Boot
• More on Properties
• Fine-tuning Logging
• Using YAML for Configuration
• Testing
Applies to Spring
Overriding Properties or Spring Boot
16-cs-spring-boot-adv - 9
© Copyright 2016 Pivotal. All rights reserved - 333 - Version 4.3.b
Renaming application.properties
Application.java
public static void main(String[] args) {
System.setProperty("spring.config.name", "myserver");
SpringApplication.run(Application.class, args);
}
16-cs-spring-boot-adv - 10
© Copyright 2016 Pivotal. All rights reserved - 334 - Version 4.3.b
The Problem with Property Placeholders
@Configuration
public class RewardsClientConfiguration {
...
}
Use @ConfigurationProperties
@Component
@ConfigurationProperties(prefix="rewards.client")
public class ConnectionSettings {
16-cs-spring-boot-adv - 11
© Copyright 2016 Pivotal. All rights reserved - 335 - Version 4.3.b
Use @EnableConfigurationProperties
• Understanding Auto-Configuration
• Customizing Spring Boot
• More on Properties
• Fine-tuning Logging
• Using YAML for Configuration
• Testing
16-cs-spring-boot-adv - 12
© Copyright 2016 Pivotal. All rights reserved - 336 - Version 4.3.b
Logging frameworks
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<exclusions>
<exclusion>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
</dependency>
16-cs-spring-boot-adv - 13
© Copyright 2016 Pivotal. All rights reserved - 337 - Version 4.3.b
Logging Output
• Understanding Auto-Configuration
• Customizing Spring Boot
• More on Properties
• Fine-tuning Logging
• Using YAML for Configuration
• Testing
16-cs-spring-boot-adv - 14
© Copyright 2016 Pivotal. All rights reserved - 338 - Version 4.3.b
What is YAML?
16-cs-spring-boot-adv - 15
© Copyright 2016 Pivotal. All rights reserved - 339 - Version 4.3.b
Multiple Profiles Inside a Single YAML File
• YAML file can contain configuration for multiple profiles
– '---' implies a separation between profiles
logging.level:
org.springframework: INFO
---
spring.profiles: development
database:
host: localhost
user: dev
---
spring.profiles: production
database:
host: 198.18.200.9
user: admin
application.yml
16-cs-spring-boot-adv - 16
© Copyright 2016 Pivotal. All rights reserved - 340 - Version 4.3.b
Topics in this Session
• Understanding Auto-Configuration
• Customizing Spring Boot
• More on Properties
• Fine-tuning Logging
• Using YAML for Configuration
• Testing
Testing: @SpringBootTest
Alias for SpringJUnit4ClassRunner
class)
class) @RunWith(SpringRunner.
@RunWith(SpringRunner.
@SpringBootTest(classes=TransferApplication.class)
@SpringBootTest(classes=TransferApplication.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() {{
TransferConfirmation
TransferConfirmation conf
conf == transferService.
transferService. transfer(...);
transfer(...);
...
...
}} Sets up same configuration
@SpringBootApplication for the tests that the
}} public class TransferApplication { application would use
public static void main(String[] args) {
SpringApplication.run(TransferApplication.class, args);
}
}
16-cs-spring-boot-adv - 17
© Copyright 2016 Pivotal. All rights reserved - 341 - Version 4.3.b
Can use with or
Web Application Testing without Spring Boot
@RunWith(SpringRunner.class)
@RunWith(SpringRunner.class)
@WebAppConfiguration
@WebAppConfiguration
public
public final
final class
class TransferServiceTests
TransferServiceTests {{ ...
... }}
Summary
16-cs-spring-boot-adv - 18
© Copyright 2016 Pivotal. All rights reserved - 342 - Version 4.3.b
Spring Security
Web Application Security
17-cs-security - 1
© Copyright 2016 Pivotal. All rights reserved - 343 - Version 4.3.b
Security Concepts
• Principal
– User, device or system that performs an action
• Authentication
– Establishing that a principal’s credentials are valid
• Authorization
– Deciding if a principal is allowed to perform an action
• Secured item
– Resource that is being secured
Authentication
17-cs-security - 2
© Copyright 2016 Pivotal. All rights reserved - 344 - Version 4.3.b
Authorization
17-cs-security - 3
© Copyright 2016 Pivotal. All rights reserved - 345 - Version 4.3.b
Motivations - I
• 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
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
17-cs-security - 4
© Copyright 2016 Pivotal. All rights reserved - 346 - Version 4.3.b
Consistency of Approach
Spring Security –
the Big Picture
17-cs-security - 5
© Copyright 2016 Pivotal. All rights reserved - 347 - Version 4.3.b
Topics in this Session
17-cs-security - 6
© Copyright 2016 Pivotal. All rights reserved - 348 - Version 4.3.b
Configuration in the Application Context
• Java Configuration (XML also available)
– Extend WebSecurityConfigurerAdapter for more control
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
authorizeRequests()
17-cs-security - 7
© Copyright 2016 Pivotal. All rights reserved - 349 - Version 4.3.b
Specifying login and logout
17-cs-security - 8
© Copyright 2016 Pivotal. All rights reserved - 350 - Version 4.3.b
Topics in this Session
Configure Authentication
17-cs-security - 9
© Copyright 2016 Pivotal. All rights reserved - 351 - Version 4.3.b
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");
}
login password Supported roles
• Configuration:
auth.jdbcAuthentication().dataSource(dataSource);
17-cs-security - 10
© Copyright 2016 Pivotal. All rights reserved - 352 - Version 4.3.b
Sourcing Users from a Database
Password Encoding
auth.jdbcAuthentication()
.dataSource(dataSource) SHA-256 encoding
.passwordEncoder(new StandardPasswordEncoder());
auth.jdbcAuthentication()
.dataSource(dataSource) encoding with salt
.passwordEncoder(new StandardPasswordEncoder(“sodium-chloride”));
17-cs-security - 11
© Copyright 2016 Pivotal. All rights reserved - 353 - Version 4.3.b
Other Authentication Options
@Configuration
@EnableWebSecurity
Use in-memory provider
@Profile(“development”)
public class SecurityDevConfig extends SecurityBaseConfig {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("hughie").password("hughie").roles("GENERAL");
}
}
17-cs-security - 12
© Copyright 2016 Pivotal. All rights reserved - 354 - Version 4.3.b
@Profile with Security Configuration
@Configuration
Use database provider
@EnableWebSecurity
@Profile(“production”)
public class SecurityProdConfig extends SecurityBaseConfig {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.jdbcAuthentication().dataSource(dataSource);
}
}
17-cs-security - 13
© Copyright 2016 Pivotal. All rights reserved - 355 - Version 4.3.b
Tag library declaration
17-cs-security - 14
© Copyright 2016 Pivotal. All rights reserved - 356 - Version 4.3.b
Authorization in JSP based on intercept-url
Matching roles
17-cs-security - 15
© Copyright 2016 Pivotal. All rights reserved - 357 - Version 4.3.b
Method Security
import javax.annotation.security.RolesAllowed;
17-cs-security - 16
© Copyright 2016 Pivotal. All rights reserved - 358 - Version 4.3.b
Method Security - @Secured
import org.springframework.security.annotation.Secured;
import org.springframework.security.annotation.PreAuthorize;
17-cs-security - 17
© Copyright 2016 Pivotal. All rights reserved - 359 - Version 4.3.b
Topics in this Session
• SpringSecurityFilterChain
– Spring Boot does this automatically
– Or declare in servlet configuration
• This single proxy filter delegates to a chain of Spring-
managed filters
– Drive authentication
– Enforce authorization
– Manage logout
– Maintain SecurityContext in HttpSession
– and more
17-cs-security - 18
© Copyright 2016 Pivotal. All rights reserved - 360 - Version 4.3.b
Example: Configuration in web.xml
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Servlet Container
Web
User DelegatingFilterProxy
Servlet
springSecurityFilterChain
Spring ApplicationContext
17-cs-security - 19
© Copyright 2016 Pivotal. All rights reserved - 361 - Version 4.3.b
The Filter Chain
17-cs-security - 20
© Copyright 2016 Pivotal. All rights reserved - 362 - Version 4.3.b
Access Secured Resource Prior to Login
Web Browser
Login Form
No context in session
Establishes empty SecurityContextPersistenceFilter
security context
x
point
AUTHENTICATED
EXCEPTION
SecuredResource
No context in session
Establishes empty SecurityContextPersistenceFilter
security context
17-cs-security - 21
© Copyright 2016 Pivotal. All rights reserved - 363 - Version 4.3.b
Access Resource With Required Role
Web Browser
Consults attributes,
obtains context, and FilterSecurityInterceptor Does nothing
delegates to access
decision manager
SecuredResource
x
delegates to access
decision manager
SecuredResource
Throws ACCESS DENIED EXCEPTION
© Copyright 2014 Pivotal. All rights reserved. 44
17-cs-security - 22
© Copyright 2016 Pivotal. All rights reserved - 364 - Version 4.3.b
Submit Logout Request
Web Browser
Logout Success
Finds context in
session and sets SecurityContextPersistenceFilter
for current thread
ExceptionTranslationFilter
FilterSecurityInterceptor
SecuredResource
17-cs-security - 23
© Copyright 2016 Pivotal. All rights reserved - 365 - Version 4.3.b
Custom Filter Chain
Summary
• Spring Security
– Secure URLs using a chain of Servlet filters
– And/or methods on Spring beans using AOP proxies
• Out-of-the-box setup usually sufficient – you define:
– URL and/or method restrictions
– How to login (typically using an HTML form)
– Supports in-memory, database, LDAP credentials (and
more)
– Password encryption using familiar hashing techniques
– Support for security tags in JSP views
17-cs-security - 24
© Copyright 2016 Pivotal. All rights reserved - 366 - Version 4.3.b
Lab
Applying Spring Security to a Web
Application
17-cs-security - 25
© Copyright 2016 Pivotal. All rights reserved - 367 - Version 4.3.b
Practical REST Web
Services
Using Spring MVC to build RESTful Web
Services
• REST introduction
• Spring MVC support for RESTful applications
– Request/Response Processing
– Accessing Request/Response Data
– Putting it all together
• RESTful Clients with the RestTemplate
• Advanced Topics
18-cs-rest-ws - 1
© Copyright 2016 Pivotal. All rights reserved - 368 - Version 4.3.b
REST Introduction
18-cs-rest-ws - 2
© Copyright 2016 Pivotal. All rights reserved - 369 - Version 4.3.b
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
18-cs-rest-ws - 3
© Copyright 2016 Pivotal. All rights reserved - 370 - Version 4.3.b
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
18-cs-rest-ws - 4
© Copyright 2016 Pivotal. All rights reserved - 371 - Version 4.3.b
REST and Java: Spring-MVC
• REST introduction
• Spring MVC support for RESTful applications
– Request/Response Processing
– Accessing Request/Response Data
– Putting it all together
• RESTful Clients with the RestTemplate
• Advanced Topics
18-cs-rest-ws - 5
© Copyright 2016 Pivotal. All rights reserved - 372 - Version 4.3.b
Spring-MVC and REST
• REST introduction
• Spring MVC support for RESTful applications
– Request/Response Processing
– Accessing Request/Response Data
– Putting it all together
• RESTful Clients with the RestTemplate
• Advanced Topics
18-cs-rest-ws - 6
© Copyright 2016 Pivotal. All rights reserved - 373 - Version 4.3.b
Request Mapping Based on HTTP Method
@RequestMapping(path="/orders", method=RequestMethod.POST)
public void createOrder( ... ) {
// process the order data from the request
}
Spring 4.3
Simpler Mapping Annotations
18-cs-rest-ws - 7
© Copyright 2016 Pivotal. All rights reserved - 374 - Version 4.3.b
HTTP Status Code Support
18-cs-rest-ws - 8
© Copyright 2016 Pivotal. All rights reserved - 375 - Version 4.3.b
Accessing Request/Response Data
• The Problem
– HTTP GET needs to return data in response body
– HTTP POST and PUT receive data in request body
– Typically XML or JSON
– Want to deal in Java objects
– Want to avoid converting between formats manually
• The Solution
– Use Marshaling via dedicated message-converters
– Annotate incoming data with @RequestBody
– Annotate outgoing data with @ResponseBody
HttpMessageConverter
18-cs-rest-ws - 9
© Copyright 2016 Pivotal. All rights reserved - 376 - Version 4.3.b
@RequestBody
@RequestMapping(path="/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);
}
@ResponseBody
18-cs-rest-ws - 10
© Copyright 2016 Pivotal. All rights reserved - 377 - Version 4.3.b
What Return Format? Accept Header
@RequestMapping(path="/orders/{id}", method=RequestMethod.GET)
@ResponseStatus(HttpStatus.OK) // 200
public @ResponseBody Order getOrder(@PathVariable("id") long id) {
return orderService.findOrderById(id);
}
HTTP/1.1
HTTP/1.1 200
200 OK
OK
Date:
Date: ……
GET Content-Length:
Content-Length: 1456
GET /store/orders/123
/store/orders/123 Content-Type:
1456
Host: Content-Type: application/xml
application/xml
Host: shop.spring.io
shop.spring.io
Accept: <order
<order id=”123”>
Accept: application/xml,
application/xml, ...
... ……
id=”123”>
……
</order>
</order>
HTTP/1.1
HTTP/1.1 200
200 OK
OK
Date:
Date: ……
GET
GET /store/orders/123
/store/orders/123 Content-Length:
Content-Length: 756
756
Host: Content-Type:
Content-Type: application/json
Host: shop.spring.io
shop.spring.io application/json
Accept:
Accept: application/json,
application/json, ...
... {{
…… "order":
"order": {"id":
{"id": 123,
123,
"items":
"items": [[ …… ],
], …… }}
}}
Spring 4.0
@RestController Simplification
@Controller
public class OrderController {
@RequestMapping(path="/orders/{id}", method=RequestMethod.GET)
public @ResponseBody Order getOrder(@PathVariable
("id") long id) {
return orderService.findOrderById(id);
}
…
}
@RestController
public class OrderController {
@RequestMapping(path="/orders/{id}", method=RequestMethod.GET)
public Order getOrder(@PathVariable("id") long id) {
return orderService.findOrderById(id);
}
…
} No need for @ResponseBody on GET methods
18-cs-rest-ws - 11
© Copyright 2016 Pivotal. All rights reserved - 378 - Version 4.3.b
Topics in this Session
• REST introduction
• Spring MVC support for RESTful applications
– Request/Response Processing
– Accessing Request/Response Data
– Putting it all together
• RESTful Clients with the RestTemplate
• Advanced Topics
18-cs-rest-ws - 12
© Copyright 2016 Pivotal. All rights reserved - 379 - Version 4.3.b
HttpEntity and ResponseEntity
@RequestMapping(path="/orders/{id}", method=RequestMethod.GET)
public HttpEntity<Order> getOrder(@RequestParam("id") long id) {
String order = orderService.find(id);
Response Response
body type body
18-cs-rest-ws - 13
© Copyright 2016 Pivotal. All rights reserved - 380 - Version 4.3.b
POST
Building URIs
// http://store.spring.io/orders/123456/items/item%20A
18-cs-rest-ws - 14
© Copyright 2016 Pivotal. All rights reserved - 381 - Version 4.3.b
ServletUriComponentsBuilder
return ResponseEntity.created(location).build();
// http://.../items/item%20A
Lesson Roadmap
18-cs-rest-ws - 15
© Copyright 2016 Pivotal. All rights reserved - 382 - Version 4.3.b
Putting it all Together What have
we learned?
• We have covered many new concepts
– @ResponseStatus
– HTTP Message Converters
– @RequestBody, @ResponseBody
– HttpEntity, ResponseEntity
– UriComponentsBuilder
Retrieving a Representation
: GET
HTTP/1.1
HTTP/1.1 200
200 OK
OK
Date:
Date: ……
GET
GET /store/orders/123
/store/orders/123 Content-Length:
Host: Content-Length: 1456
1456
Host: shop.spring.io
shop.spring.io Content-Type:
Content-Type: application/xml
application/xml
Accept:
Accept: application/xml,
application/xml,
...
... <order
<order id=”123”>
id=”123”>
...
... ……
</order>
</order>
@GetMapping(path="/orders/{id}")
public @ResponseBody Order getOrder(@PathVariable("id") long id) {
return orderService.findOrderById(id);
}
@RequestMapping(path="/orders/{id}", method=RequestMethod.GET)
18-cs-rest-ws - 16
© Copyright 2016 Pivotal. All rights reserved - 383 - Version 4.3.b
Creating a new Resource: POST (1)
POST
POST /store/orders/123/items
/store/orders/123/items
Host:
Host: shop.spring.io HTTP/1.1
shop.spring.io HTTP/1.1 201
201 Created
Created
Content-Type:
Content-Type: application/xml Date:
application/xml Date: ……
Content-Length:
Content-Length: 00
<item>
<item>
…… Location:
Location: http://shop.spring.io/
http://shop.spring.io/
</item> store/orders/123/items/abc
store/orders/123/items/abc
</item>
@PostMapping(path="/orders/{id}/items")
@ResponseStatus(HttpStatus.CREATED) // 201
public ResponseEntity<Void>
createItem(@PathVariable("id") long id, @RequestBody Item newItem) {
// Add the new item to the order
orderService.findOrderById(id).addItem(newItem);
return ResponseEntity.created(location).build();
}
@RequestMapping(path="/orders/...", method=RequestMethod.POST)
18-cs-rest-ws - 17
© Copyright 2016 Pivotal. All rights reserved - 384 - Version 4.3.b
Updating existing Resource: PUT
PUT
PUT /store/orders/123/items/abc
/store/orders/123/items/abc
Host: shop.spring.io
Host: shop.spring.io HTTP/1.1
HTTP/1.1 204
204 No
No Content
Content
Content-Type:
Content-Type: application/xml Date:
application/xml Date: ……
Content-Length:
Content-Length: 0 0
<item>
<item>
……
</item>
</item>
@PutMapping(path="/orders/{orderId}/items/{itemId}")
@ResponseStatus(HttpStatus.NO_CONTENT) // 204
public void updateItem(@PathVariable("orderId") long orderId,
@PathVariable("itemId") String itemId,
@RequestBody Item item) {
orderService.findOrderById(orderId).updateItem(itemId, item);
}
@RequestMapping(path="/orders/...", method=RequestMethod.PUT)
Deleting a Resource:
DELETE
DELETE HTTP/1.1
HTTP/1.1 204
204 No
No Content
DELETE /store/orders/123/items/abc
/store/orders/123/items/abc Content
Date:
Date: ……
Host: shop.spring.io
Host: shop.spring.io
... Content-Length: 0 Content-Length: 0
...
@DeleteMapping(path="/orders/{orderId}/items/{itemId}")
@ResponseStatus(HttpStatus.NO_CONTENT) // 204
public void deleteItem(@PathVariable("orderId") long orderId,
@PathVariable("itemId") String itemId) {
orderService.findOrderById(orderId).deleteItem(itemId);
}
@RequestMapping(path="/orders/...", method=RequestMethod.DELETE)
18-cs-rest-ws - 18
© Copyright 2016 Pivotal. All rights reserved - 385 - Version 4.3.b
Topics in this Session
• REST introduction
• Spring MVC support for RESTful applications
• RESTful Clients with the RestTemplate
• Advanced Topics
RestTemplate
18-cs-rest-ws - 19
© Copyright 2016 Pivotal. All rights reserved - 386 - Version 4.3.b
Defining a RestTemplate
18-cs-rest-ws - 20
© Copyright 2016 Pivotal. All rights reserved - 387 - Version 4.3.b
Summary
Lab
Restful applications with Spring MVC
18-cs-rest-ws - 21
© Copyright 2016 Pivotal. All rights reserved - 388 - Version 4.3.b
Topics in this Session
• REST introduction
• Spring MVC support for RESTful applications
• RESTful clients with the RestTemplate
• Advanced Topics
– More on Spring REST
– Spring HATEOAS
18-cs-rest-ws - 22
© Copyright 2016 Pivotal. All rights reserved - 389 - Version 4.3.b
@ExceptionHandler
@ResponseStatus(HttpStatus.CONFLICT) // 409
@ExceptionHandler({DataIntegrityViolationException.class})
public void conflict() {
// could add the exception, response, etc. as method params
}
Spring MVC offers several ways to handle exceptions, for more details
see http://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
18-cs-rest-ws - 23
© Copyright 2016 Pivotal. All rights reserved - 390 - Version 4.3.b
Mixing Views and Annotations – 2
• Recommendation
RESTful Method
@GetMapping(path="/orders/{id}",
produces = {"application/json","application/xml"})
@ResponseStatus(HttpStatus.OK) // 200
public @ResponseBody Order getOrder(@PathVariable("id") long id) {
// Access data here ...
return orderService.findOrderById(id);
}
@GetMapping(path="/orders/{id}")
public String getOrder(Model model, @PathVariable("id") long id) {
// Invoke RESTful method, use result to populate model
model.addAttribute(getOrder(id));
return "orderDetails"; // View name View method calls
} RESTful method
View Method
18-cs-rest-ws - 24
© Copyright 2016 Pivotal. All rights reserved - 391 - Version 4.3.b
HttpMethodFilter
• REST introduction
• Spring MVC support for RESTful applications
– Request/Response Processing
– Using MessageConverters
– Putting it all together
• RESTful clients with the RestTemplate
• Advanced Topics
– More on Spring REST
– Spring HATEOAS
18-cs-rest-ws - 25
© Copyright 2016 Pivotal. All rights reserved - 392 - Version 4.3.b
HATEOAS - Concepts
Spring HATEOAS
HATEOAS Account Example provides an API for
generating these
<account> links in MVC
<account-number>12345</account-number> Controller responses
<balance currency="usd">100.00</balance>
<link rel="self" href=
/> "/account/12345"
<link rel="deposit" href="/account/12345/deposits" />
<link rel="withdraw" href="/account/12345/withdrawls" />
<link rel="transfer" href="/account/12345/transfers" />
<link rel="close" href="/account/12345/close" />
</account>
Note: links change
<account> as state changes
<account-number>12345</account-number>
<balance currency="usd">-25.00</balance>
<link rel="self" href="/account/12345" />
<link rel="deposit" href="/account/12345/deposits" />
</account>
There is no standard for links yet. This example uses the link style from the
Hypertext Application Language (HAL), one possible representation
From: http://restcookbook.com/Basics/hateoas/
© Copyright 2014 Pivotal. All rights reserved. 52
18-cs-rest-ws - 26
© Copyright 2016 Pivotal. All rights reserved - 393 - Version 4.3.b
Managing Links
Converting to a Resource
@Controller
@EnableHypermediaSupport(type=HypermediaType.HAL)
public class OrderController {
@GetMapping(value="/orders/{id}")
public @ResponseBody Resource<Order>
getOrder(@PathVariable("id") long id) {
Links[] = ...; // Some links (see previous slide)
return new Resource<Order>
(orderService.findOrderById(id), links);
}
}
18-cs-rest-ws - 27
© Copyright 2016 Pivotal. All rights reserved - 394 - Version 4.3.b
Spring HATEOAS
18-cs-rest-ws - 28
© Copyright 2016 Pivotal. All rights reserved - 395 - Version 4.3.b
Microservices with
Spring
Building Cloud Native Applications
© Copyright 2015
2014 Pivotal. All rights reserved. 1
Roadmap
19-cs-microservices - 1
© Copyright 2016 Pivotal. All rights reserved - 396 - Version 4.3.b
Introduction
http://martinfowler.com/articles/microservices.html
Without Microservices
Server
Shopping Application
Store, Config, Cart...
DB
19-cs-microservices - 2
© Copyright 2016 Pivotal. All rights reserved - 397 - Version 4.3.b
With Microservices
Shopping
Store Catalog Cart Service
Roadmap
19-cs-microservices - 3
© Copyright 2016 Pivotal. All rights reserved - 398 - Version 4.3.b
Core Spring Concepts
Applied to Application Architecture
Microservice Benefits
19-cs-microservices - 4
© Copyright 2016 Pivotal. All rights reserved - 399 - Version 4.3.b
Microservice Challenges
19-cs-microservices - 5
© Copyright 2016 Pivotal. All rights reserved - 400 - Version 4.3.b
Roadmap
Microservice Infrastructure
We cover these today
19-cs-microservices - 6
© Copyright 2016 Pivotal. All rights reserved - 401 - Version 4.3.b
Roadmap
19-cs-microservices - 7
© Copyright 2016 Pivotal. All rights reserved - 402 - Version 4.3.b
What is Spring Cloud?
http://projects.spring.io/spring-cloud
© Copyright 2015 Pivotal. All rights reserved. 15
Spring Cloud
Spring Cloud Spring Cloud Spring Cloud
Spring Cloud Spring Cloud
Connectors Config Netflix * Security Data Flow
Spring Cloud Spring Cloud Spring Cloud Spring Cloud Spring Cloud
Cloud Foundry Bus Consul CLI Modules
19-cs-microservices - 8
© Copyright 2016 Pivotal. All rights reserved - 403 - Version 4.3.b
Spring Cloud Usage Examples
Need
Service
Discovery Order Which Cart
DB Instance? DB
19-cs-microservices - 9
© Copyright 2016 Pivotal. All rights reserved - 404 - Version 4.3.b
Why We Need Service Discovery – 2
2. Register
1. Register Discovery
Discovery Cart
Checkout Server(s) Service
Server(s)
Service
register register
3. Find Cart Cart
consult URL(s)
Service
Product REST request Cart
Checkout Cart
Cart
Catalog Service
Service Service
Service
Service JSON
19-cs-microservices - 10
© Copyright 2016 Pivotal. All rights reserved - 405 - Version 4.3.b
Implementing Client-Side Load Balancing
Roadmap
19-cs-microservices - 11
© Copyright 2016 Pivotal. All rights reserved - 406 - Version 4.3.b
Our Simple Microservice System
C B
requests
Consumer Producer
data from
19-cs-microservices - 12
© Copyright 2016 Pivotal. All rights reserved - 407 - Version 4.3.b
Maven Dependencies
<parent>
<groupId>org.springframework.cloud</groupId> Parent
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Brixton.SR4</version>
</parent> “Release train” = a consolidated
<dependencies> set of releases
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
</dependencies> pom.xml
eureka:
eureka:
• All you need to implement instance:
instance:
your own registry service! hostname:
hostname: localhost
localhost
## Not
Not aa client
client:
client:
client
registerWithEureka:
registerWithEureka: false
false
@SpringBootApplication
@SpringBootApplication fetchRegistry:
fetchRegistry: false
false
@EnableEurekaServer
@EnableEurekaServer
public
public class
class EurekaApplication
EurekaApplication {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
SpringApplication.run(EurekaApplication.class,
SpringApplication.run(EurekaApplication.class, args);
args);
}}
}} main.java
<dependency>
<dependency> pom.xml
<groupId>org.springframework.cloud</groupId>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
<artifactId>spring-cloud-starter-eureka-server</artifactId>
</dependency>
</dependency>
19-cs-microservices - 13
© Copyright 2016 Pivotal. All rights reserved - 408 - Version 4.3.b
(B) Accounts Producer Microservice
Performs Service Registration
@SpringBootApplication
@SpringBootApplication
@EnableDiscoveryClient
@EnableDiscoveryClient
public
public class
class FrontEndApplication
FrontEndApplication {{
public
public static
static void
void main(String[]
main(String[] args)
args) {{
SpringApplication.run(Application.class,
SpringApplication.run(Application.class, args);
args);
}}
//
// Will
Will use
use this
this template
template to
to access
access the
the microservice
microservice
//
// Spring
Spring will
will enhance
enhance this
this to
to do
do service
service discovery
discovery
@Bean
@Bean @LoadBalanced
@LoadBalanced
public
public RestTemplate
RestTemplate restTemplate()
restTemplate() {{
return
return new
new RestTemplate();
RestTemplate();
}}
}}
19-cs-microservices - 14
© Copyright 2016 Pivotal. All rights reserved - 409 - Version 4.3.b
(C) Consumer Service – Step 2
Let our consumer use the producer
@Service
@Service
public
public class
class RemoteAccountManager
RemoteAccountManager implements
implements AccountService
AccountService {{
//
// Spring
Spring injects
injects the
the “smart”
“smart” service-aware
service-aware template
template
//
// defined
defined on
on previous
previous slide
slide
//
// It
It performs
performs aa load-balanced
load-balanced lookup
lookup (see
(see next
next slide)
slide)
@Autowired
@Autowired
@LoadBalanced
@LoadBalanced
RestTemplate
RestTemplate restTemplate;
restTemplate;
public
public Account
Account findAccount(String
findAccount(String id)
id) {{
//
// Fetch
Fetch data
data
return
return restTemplate.getForObject
restTemplate.getForObject
("http://accounts-microservice/accounts/{id}",
("http://accounts-microservice/accounts/{id}",
Account.class,
Account.class, id);
id);
}}
Service name
}}
19-cs-microservices - 15
© Copyright 2016 Pivotal. All rights reserved - 410 - Version 4.3.b
Load Balancing with Ribbon
19-cs-microservices - 16
© Copyright 2016 Pivotal. All rights reserved - 411 - Version 4.3.b
Summary
19-cs-microservices - 17
© Copyright 2016 Pivotal. All rights reserved - 412 - Version 4.3.b
Finishing Up
Course Completed
What's Next?
What's Next
• What to do next?
– Certification
– Other courses
– Resources
– Evaluation
20-cs-completed - 1
© Copyright 2016 Pivotal. All rights reserved - 413 - Version 4.3.b
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 available online
https://pivotal.io/academy/certification
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
20-cs-completed - 2
© Copyright 2016 Pivotal. All rights reserved - 414 - Version 4.3.b
Certification: Logistics
Voucher is
valid for 3 months
– do it soon!
• Where?
– Online at PSI (Innovative Exams)
• https://www.examslocal.com
• How?
– You should receive a certification voucher by email
– Register/sign-in and book an exam using the voucher
• http://it.psionline.com/exam-faqs/pivotal-faq
– Take the test from any location
• For more information, email
– education@pivotal.io
Other courses
20-cs-completed - 3
© Copyright 2016 Pivotal. All rights reserved - 415 - Version 4.3.b
Spring Web
• Four-day workshop
Enterprise Spring
20-cs-completed - 4
© Copyright 2016 Pivotal. All rights reserved - 416 - Version 4.3.b
Spring Boot Developer
• Course topics:
– Introduction to Spring Boot
• Underpins all Spring Cloud projects
– Pushing Applications to a PaaS
• Using Pivotal Cloud Foundry
– What are Microservices?
• Architecting a microservices solution
– Cloud infrastructure services and Netflix OSS
• Service Configuration
• Service Registration
• Load-balancing and fault tolerance
• Security using OAuth
20-cs-completed - 5
© Copyright 2016 Pivotal. All rights reserved - 417 - Version 4.3.b
Cloud Foundry Developer
20-cs-completed - 6
© Copyright 2016 Pivotal. All rights reserved - 418 - Version 4.3.b
Pivotal Support Offerings
Pivotal Consulting
• Pivotal Labs
– Agile development experts
– Mentoring: design, development and product management
• http://www.pivotal.io/agile
• http://pivotallabs.com
20-cs-completed - 7
© Copyright 2016 Pivotal. All rights reserved - 419 - Version 4.3.b
Resources
Resources (2)
20-cs-completed - 8
© Copyright 2016 Pivotal. All rights reserved - 420 - Version 4.3.b
Thank You!
If your course
• Please fill out the evaluation form is registered at
– Americas: http://tinyurl.com/usa-eval Pivotal Academy
– EMEA: http://tinyurl.com/emea-eval
– Asia-Pac: http://tinyurl.com/apj-eval
• Once you've done, login to Pivotal Academy
– You can download your Attendance Certificate
20-cs-completed - 9
© Copyright 2016 Pivotal. All rights reserved - 421 - Version 4.3.b
XML Dependency
Injection
Advanced Features & Best Practices
30-cs-xml-di-best-practices - 1
© Copyright 2016 Pivotal. All rights reserved - 422 - Version 4.3.b
Advanced Bean Instantiation
• Four techniques:
– @Bean method in @Configuration class
• 100% Java code available, write whatever code
you need
– Beans implementing Spring's FactoryBean interface
30-cs-xml-di-best-practices - 2
© Copyright 2016 Pivotal. All rights reserved - 423 - Version 4.3.b
The factory-method Attribute
• Non-intrusive
– Useful for existing Singletons or Factories
public class AccountServiceSingleton implements AccountService {
…
public static AccountService getInstance() { // … }
}
30-cs-xml-di-best-practices - 3
© Copyright 2016 Pivotal. All rights reserved - 424 - Version 4.3.b
Topics in this session
30-cs-xml-di-best-practices - 4
© Copyright 2016 Pivotal. All rights reserved - 425 - Version 4.3.b
Using Constructor Types
class MailService {
public MailService(String username) { … }
public MailService(int maxMessages) { … }
Is a String in XML
<bean name=“example” class=“com.app.MailService”>
<constructor-arg type=“int” value=“2000”/>
</bean>
Force use of second consturctor
Without type, Spring passes “2000” as the username
class MailService {
Specify arg
@ConstructorProperties( { “username”, “email” } )
names in order
public MailService(String username, String email) { … }
30-cs-xml-di-best-practices - 5
© Copyright 2016 Pivotal. All rights reserved - 426 - Version 4.3.b
Topics in this session
• Before
>
<bean id="transferService" class="com.acme.BankServiceImpl"
class="com.acme.BankServiceImpl">
<constructor-argref=”bankRepository"
name=”bankRepository"
/> 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:customer-service-ref="customerService" /> Use camel case or hyphens
30-cs-xml-di-best-practices - 6
© Copyright 2016 Pivotal. All rights reserved - 427 - Version 4.3.b
The c and p namespaces
<beans xmlns:c="http://www.springframework.org/schema/c"
xmlns:p="http://www.springframework.org/schema/p"
...>
No schemaLocation needed
30-cs-xml-di-best-practices - 7
© Copyright 2016 Pivotal. All rights reserved - 428 - Version 4.3.b
'c' and 'p' Pros and Cons
• Pros
– More concise
– Well supported in STS
• CTRL+space works well
• Cons
– Less widely known than the usual XML configuration
syntax
30-cs-xml-di-best-practices - 8
© Copyright 2016 Pivotal. All rights reserved - 429 - Version 4.3.b
Bean Definition Inheritance (1)
30-cs-xml-di-best-practices - 9
© Copyright 2016 Pivotal. All rights reserved - 430 - Version 4.3.b
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" />
</bean> Can override
</beans>
Each pool inherits its parent configuration
30-cs-xml-di-best-practices - 10
© Copyright 2016 Pivotal. All rights reserved - 431 - Version 4.3.b
Inheritance for service and repository beans
30-cs-xml-di-best-practices - 11
© Copyright 2016 Pivotal. All rights reserved - 432 - Version 4.3.b
Inner beans
NoSuchBeanDefinitionException!!
<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>
30-cs-xml-di-best-practices - 12
© Copyright 2016 Pivotal. All rights reserved - 433 - Version 4.3.b
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>
30-cs-xml-di-best-practices - 13
© Copyright 2016 Pivotal. All rights reserved - 434 - Version 4.3.b
Inner Beans: pros and cons
• Pros
– You only expose what needs to be exposed
– Very commonly used technique in online examples
• Cons
– Can be harder to read
– Avoid really deep nesting
• General recommendation
– Use them when it makes sense
• As for inner classes in Java
• Complex "infrastructure beans" configuration
Lab (Optional)
Using Bean Definition Inheritance, Property
Placeholders and Namespaces
30-cs-xml-di-best-practices - 14
© Copyright 2016 Pivotal. All rights reserved - 435 - Version 4.3.b
Topics in this session
• Recall:
– Can access System properties and environment
– Properties of Spring beans
30-cs-xml-di-best-practices - 15
© Copyright 2016 Pivotal. All rights reserved - 436 - Version 4.3.b
SpEL examples – XML
• 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>
30-cs-xml-di-best-practices - 16
© Copyright 2016 Pivotal. All rights reserved - 437 - Version 4.3.b
Topics in this session
Autowiring in XML
30-cs-xml-di-best-practices - 17
© Copyright 2016 Pivotal. All rights reserved - 438 - Version 4.3.b
Topics in this session
• beans collections
– From the default beans namespace
– Simple and easy, legacy from Spring V1
• util collections
– From the util namespace
• Requires additional namespace declaration
– More features available, since Spring V2
Both offer support for set, map, list and properties collections
30-cs-xml-di-best-practices - 18
© Copyright 2016 Pivotal. All rights reserved - 439 - Version 4.3.b
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>
</property> public void setCustomerPolicies(java.util.List policies) { .. }
</bean>
Equivalent to:
TransferServiceImpl service = new TransferServiceImpl();
service.setCustomerPolicies(list); // create list with bean references
ApplicationContext
service -> instance of TransferServiceImpl
30-cs-xml-di-best-practices - 19
© Copyright 2016 Pivotal. All rights reserved - 440 - Version 4.3.b
Injecting a Set or Map
Properties
Injecting a collection of type
30-cs-xml-di-best-practices - 20
© Copyright 2016 Pivotal. All rights reserved - 441 - Version 4.3.b
util collections
bean id
</util:set>
Also: util:list, util:map, util:properties
30-cs-xml-di-best-practices - 21
© Copyright 2016 Pivotal. All rights reserved - 442 - Version 4.3.b
Summary
30-cs-xml-di-best-practices - 22
© Copyright 2016 Pivotal. All rights reserved - 443 - Version 4.3.b
Object Relational
Mapping
Using OR Mapping in the Enterprise
31-cs-orm - 1
© Copyright 2016 Pivotal. All rights reserved - 444 - Version 4.3.b
The Object/Relational Mismatch (1)
31-cs-orm - 2
© Copyright 2016 Pivotal. All rights reserved - 445 - Version 4.3.b
Object/Relational Mapping
31-cs-orm - 3
© Copyright 2016 Pivotal. All rights reserved - 446 - Version 4.3.b
ORM in context
31-cs-orm - 4
© Copyright 2016 Pivotal. All rights reserved - 447 - Version 4.3.b
O/R Mismatch: Granularity (2)
just one example…
Domain Model in Java Table in Database
Customer CUSTOME
- customerId EmailAddress R
CUST_ID <<PK>>
- firstName FIRST_NAME
- lastName PhoneNumber LAST_NAME
EMAIL
PHONE
STREET_NUMBER
Address
STREET_NAME
- streetNumber CITY
- streetName STATE
- city ZIP_CODE
- state
- zipCode
31-cs-orm - 5
© Copyright 2016 Pivotal. All rights reserved - 448 - Version 4.3.b
O/R Mismatch: Identity (2)
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
31-cs-orm - 6
© Copyright 2016 Pivotal. All rights reserved - 449 - Version 4.3.b
O/R Mismatch:
Inheritance and Associations (2)
31-cs-orm - 7
© Copyright 2016 Pivotal. All rights reserved - 450 - Version 4.3.b
Benefits of ORM
31-cs-orm - 8
© Copyright 2016 Pivotal. All rights reserved - 451 - Version 4.3.b
Automatic Change Detection
invoke(input)
begin
find
find
modify
commit
flush
Database
output
Persistence by Reachability
31-cs-orm - 9
© Copyright 2016 Pivotal. All rights reserved - 452 - Version 4.3.b
(Un)Persistence by Reachability
= Make Transient
Caching
31-cs-orm - 10
© Copyright 2016 Pivotal. All rights reserved - 453 - Version 4.3.b
Summary
31-cs-orm - 11
© Copyright 2016 Pivotal. All rights reserved - 454 - Version 4.3.b
Spring Security
XML Configuration
Classic configuration options for
Web Application Security
32-cs-xml-security - 1
© Copyright 2016 Pivotal. All rights reserved - 455 - Version 4.3.b
Configuration in web.xml
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
intercept-url
• intercept-urls are evaluated in the order listed
– first match is used, put specific matches first
<beans>
<security:http>
<security:intercept-url pattern="/accounts/edit*"
access="ROLE_ADMIN" />
<security:intercept-url pattern="/accounts/account*"
access="ROLE_ADMIN,ROLE_USER" />
<security:intercept-url pattern="/accounts/**"
access="IS_AUTHENTICATED_FULLY" />
<security:intercept-url pattern="/customers/**"
access="IS_AUTHENTICATED_ANONYMOUSLY" />
</security:http>
</beans> Syntax available since Spring Security 2.0
32-cs-xml-security - 2
© Copyright 2016 Pivotal. All rights reserved - 456 - Version 4.3.b
Security EL expressions
• hasRole('role')
– Checks whether the principal has the given role
• hasAnyRole('role1', 'role2', …)
– Checks whether the principal has any of the given roles
• isAnonymous()
– Allows access for unauthenticated principals
• isAuthenticated()
– Allows access for authenticated or remembered principals
</security:http>
</beans> Syntax available from Spring Security 3.0
32-cs-xml-security - 3
© Copyright 2016 Pivotal. All rights reserved - 457 - Version 4.3.b
Working with roles
• Checking if the user has one single role
<security:intercept-url pattern="/accounts/update*" access="hasRole('ROLE_ADMIN')" />
• “or” clause
<security:intercept-url pattern="/accounts/update*"
access="hasAnyRole('ROLE_ADMIN', 'ROLE_MANAGER')" />
• “and” clause
<security:intercept-url pattern="/accounts/update*"
access="hasRole('ROLE_ADMIN') and hasRole('ROLE_MANAGER')" />
<security:http use-expressions="true">
Specify login options
<security:form-login login-page="/accounts/login"
default-target-url="/accounts/home"/>
<security:intercept-url pattern="/accounts/update*"
access="hasAnyRole('ROLE_ADMIN', 'ROLE_MANAGER')" />
<security:intercept-url pattern="/accounts/**"
access="hasRole('ROLE_ADMIN')" />
<security:logout logout-success-url="/home.html"
Must be declared explicitly
</security:http> or no logout possible
... Spring configuration file
32-cs-xml-security - 4
© Copyright 2016 Pivotal. All rights reserved - 458 - Version 4.3.b
Setting up User Login
<security:http>
• Default auth. provider <security:form-login/>
assumes form-based …
</security:http>
login
– This is web security after <security:authentication-manager>
<security:authentication-provider>
all
...
– Must specify form-login </security:authentication-provider>
element <security:authentication-manager>
– A basic form is provided
– Configure to use your
own login-page
32-cs-xml-security - 5
© Copyright 2016 Pivotal. All rights reserved - 459 - Version 4.3.b
The In-Memory User Service
admin=secret,ROLE_ADMIN,ROLE_MEMBER,ROLE_GUEST
testuser1=pass,ROLE_MEMBER,ROLE_GUEST
testuser2=pass,ROLE_MEMBER
guest=guest,ROLE_GUEST
List of roles separated by commas
login password
• Configuration:
<beans>
<security:http> … <security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:jdbc-user-service data-source-ref="myDatasource" />
</security:authentication-provider>
</security:authentication-manager>
</beans> Spring configuration file
32-cs-xml-security - 6
© Copyright 2016 Pivotal. All rights reserved - 460 - Version 4.3.b
Password Encoding
<security:global-method-security>
<security:protect-pointcut
expression="execution(* com.springsource..*Service.*(..))"
access="ROLE_USER,ROLE_MEMBER" />
</security:global-method-security> Spring configuration file
32-cs-xml-security - 7
© Copyright 2016 Pivotal. All rights reserved - 461 - Version 4.3.b
Custom Filter Chain
32-cs-xml-security - 8
© Copyright 2016 Pivotal. All rights reserved - 462 - Version 4.3.b
Spring JMS
Simplifying Messaging Applications
• Introduction to JMS
• Apache ActiveMQ
• Configuring JMS Resources with Spring
• Spring’s JmsTemplate
• Sending Messages
• Receiving Messages
• Advanced Features
33-cs-jms - 1
© Copyright 2016 Pivotal. All rights reserved - 463 - Version 4.3.b
Java Message Service (JMS)
• Message
• Destination
• Connection
• Session
• MessageProducer
• MessageConsumer
33-cs-jms - 2
© Copyright 2016 Pivotal. All rights reserved - 464 - Version 4.3.b
JMS Message Types
33-cs-jms - 3
© Copyright 2016 Pivotal. All rights reserved - 465 - Version 4.3.b
JMS Queues: Point-to-point
1
Producer Consumer
1
2 2
2
Producer Consumer
Queue
1 2
Producer Consumer
2 2 1
1 2
Producer Consumer
Topic
33-cs-jms - 4
© Copyright 2016 Pivotal. All rights reserved - 466 - Version 4.3.b
The JMS Connection
// use session
if (everythingOkay) {
session.commit();
} else {
session.rollback();
}
33-cs-jms - 5
© Copyright 2016 Pivotal. All rights reserved - 467 - Version 4.3.b
Creating Messages
session.createObjectMessage(someSerializableObject);
producer = session.createProducer(someDestination);
consumer = session.createConsumer(someDestination);
33-cs-jms - 6
© Copyright 2016 Pivotal. All rights reserved - 468 - Version 4.3.b
Topics in this Session
• Introduction to JMS
• Apache ActiveMQ
• Configuring JMS Resources with Spring
• Spring’s JmsTemplate
• Sending Messages
• Receiving Messages
• Advanced Features
JMS Providers
33-cs-jms - 7
© Copyright 2016 Pivotal. All rights reserved - 469 - Version 4.3.b
Apache ActiveMQ
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
33-cs-jms - 8
© Copyright 2016 Pivotal. All rights reserved - 470 - Version 4.3.b
Topics in this Session
• Introduction to JMS
• Apache ActiveMQ
• Configuring JMS Resources with Spring
• Spring’s JmsTemplate
• Sending Messages
• Receiving Messages
• Advanced Features
33-cs-jms - 9
© Copyright 2016 Pivotal. All rights reserved - 471 - Version 4.3.b
Configuring a ConnectionFactory
Configuring Destinations
33-cs-jms - 10
© Copyright 2016 Pivotal. All rights reserved - 472 - Version 4.3.b
Topics in this Session
• Introduction to JMS
• Apache ActiveMQ
• Configuring JMS Resources with Spring
• Spring’s JmsTemplate
• Sending Messages
• Receiving Messages
• Advanced Features
Spring’s JmsTemplate
33-cs-jms - 11
© Copyright 2016 Pivotal. All rights reserved - 473 - Version 4.3.b
Exception Handling
Exception RuntimeException
JmsTemplate configuration
33-cs-jms - 12
© Copyright 2016 Pivotal. All rights reserved - 474 - Version 4.3.b
(1) MessageConverter
XML MessageConverter
XML
jibx JAXB
XStream Message
XML
Castor
Beans
DOM SAX
33-cs-jms - 13
© Copyright 2016 Pivotal. All rights reserved - 475 - Version 4.3.b
MarshallingMessageConverter Example
@Bean public JmsTemplate jmsTemplate () {
JmsTemplate template = new JmsTemplate( connectionFactory() );
template.setMessageConverter ( msgConverter() );
return template;
}
(2) DestinationResolver
• Convenient to use destination names at Name
runtime
• DynamicDestinationResolver used by Destination
default Resolver
– Resolves topic and queue names
– Not their Spring bean names
Destination
• JndiDestinationResolver also available
33-cs-jms - 14
© Copyright 2016 Pivotal. All rights reserved - 476 - Version 4.3.b
(3) Default Destination
33-cs-jms - 15
© Copyright 2016 Pivotal. All rights reserved - 477 - Version 4.3.b
Sending Messages
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
public void placeOrder(Order order) { is wired by name
String stringMessage = "New order " + order.getNumber();
jmsTemplate.convertAndSend("message.queue", stringMessage );
// use destination resolver and message converter
33-cs-jms - 16
© Copyright 2016 Pivotal. All rights reserved - 478 - Version 4.3.b
Sending JMS Messages
• Introduction to JMS
• Apache ActiveMQ
• Configuring JMS Resources with Spring
• Spring’s JmsTemplate
• Sending Messages
• Receiving Messages
• Advanced Features
33-cs-jms - 17
© Copyright 2016 Pivotal. All rights reserved - 479 - Version 4.3.b
Receiving Objects
Receiving Messages
33-cs-jms - 18
© Copyright 2016 Pivotal. All rights reserved - 480 - Version 4.3.b
Synchronous Message Exchange
Asynchronous or Synchronous
VS
• Sending messages is asynchronous
– The send methods return immediately
• Even if the message takes time to be delivered
• Recall the acknowledgement modes in createSession()
• But receive() and receiveAndConvert() are blocking
– Synchronous – will wait for ever for a new message
• optional timeout: setReceiveTimeout()
• How can we receive data asynchronously?
– JMS defines Message Driven Beans
– But you normally need a full JEE container to use them
33-cs-jms - 19
© Copyright 2016 Pivotal. All rights reserved - 481 - Version 4.3.b
Spring’s MessageListener Containers
Quick Start
33-cs-jms - 20
© Copyright 2016 Pivotal. All rights reserved - 482 - Version 4.3.b
Spring 4.1
Step (1)
Define POJO / Bean to Process Message
Spring 4.1
Step (2)
Define JmsListenerContainerFactory to use
• JmsListenerContainerFactory
– Separates JMS API from your POJO:
Enable annotations
@Configuration @EnableJms
public class MyConfiguration {
Default container name
@Bean
public DefaultJmsListenerContainerFactory
jmsListenerContainerFactory () {
Set ConnectionFactory
DefaultJmsListenerContainerFactory cf =
new DefaultJmsListenerContainerFactory( );
cf.setConnectionFactory(connectionFactory());
...
return cf;
Many settings available:
}
TransactionManager, TaskExecutor, ContainerType ...
}
33-cs-jms - 21
© Copyright 2016 Pivotal. All rights reserved - 483 - Version 4.3.b
Spring 4.1
Step (3)
Define Receiving Method with @JmsListener
• Advantages
– Application freed from messaging concerns
• Resilience, guaranteed delivery (compare to REST)
– Asynchronous support built-in
– Interoperable – languages, environments
• Disadvantages
– Requires additional third-party software
• Can be expensive to install and maintain
– More complex to use – but not with JmsTemplate!
33-cs-jms - 22
© Copyright 2016 Pivotal. All rights reserved - 484 - Version 4.3.b
Lab
Sending and Receiving Messages in
a Spring Application
• Introduction to JMS
• Apache ActiveMQ
• Configuring JMS Resources with Spring
• Spring’s JmsTemplate
• Sending Messages
• Receiving Messages
• Optional Features
– Using XML
33-cs-jms - 23
© Copyright 2016 Pivotal. All rights reserved - 485 - Version 4.3.b
Alternative Step (2)
Use 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"/>
33-cs-jms - 24
© Copyright 2016 Pivotal. All rights reserved - 486 - Version 4.3.b
Message-Driven POJO in XML
<jms:listener
ref="orderService" 1
method="order" 2
destination="queue.orders" 3
response-destination="queue.confirmation"/>
CachingConnectionFactory
33-cs-jms - 25
© Copyright 2016 Pivotal. All rights reserved - 487 - Version 4.3.b
Performance and
Operations
Management and Monitoring of Spring Java
Applications
• Introduction
• JMX
• Introducing Spring JMX
• Automatically exporting existing MBeans
• Spring Insight
34-cs-jmx - 1
© Copyright 2016 Pivotal. All rights reserved - 488 - Version 4.3.b
Overall Goals
• Introduction
• JMX
• Introducing Spring JMX
• Automatically exporting existing MBeans
• Spring Insight
34-cs-jmx - 2
© Copyright 2016 Pivotal. All rights reserved - 489 - Version 4.3.b
What is JMX?
• Management
– Changing configuration properties at runtime
• Monitoring
– Reporting cache hit/miss ratios at runtime
34-cs-jmx - 3
© Copyright 2016 Pivotal. All rights reserved - 490 - Version 4.3.b
JMX Architecture
JSR-160 JSR-160
Connector Connector
MBeanServer
JMX Architecture
34-cs-jmx - 4
© Copyright 2016 Pivotal. All rights reserved - 491 - Version 4.3.b
JMX Architecture
34-cs-jmx - 5
© Copyright 2016 Pivotal. All rights reserved - 492 - Version 4.3.b
Plain JMX – Exposing an MBean
try {
ObjectName name = new ObjectName("ourapp:name=counter");
server.registerMBean(bean, name);
} catch (Exception e) {
e.printStackTrace();
}
• Introduction
• JMX
• Introducing Spring JMX
• Automatically exporting existing MBeans
• Spring Insight
34-cs-jmx - 6
© Copyright 2016 Pivotal. All rights reserved - 493 - Version 4.3.b
Goals of Spring JMX
34-cs-jmx - 7
© Copyright 2016 Pivotal. All rights reserved - 494 - Version 4.3.b
Spring JMX Steps
• Or declare it explicitly
or JavaConfig
@Bean
public MBeanServerFactoryBean mbeanServer () {
MBeanServerFactoryBean server = new MBeanServerFactoryBean();
server.setLocateExistingServerIfPossible( true );
...
return server;
}
34-cs-jmx - 8
© Copyright 2016 Pivotal. All rights reserved - 495 - Version 4.3.b
Step 2: Exporting a Bean as an MBean
or XML
<context:mbean-export/>
34-cs-jmx - 9
© Copyright 2016 Pivotal. All rights reserved - 496 - Version 4.3.b
3. Control Attribute/Operation Exposure:
<<interface>>
<<interface>>
JmxCounter
JmxCounter
MBean
Server
Client Spring JmxCounterImpl
MBean
Proxy
Spring
Generated
Registration MBeanExporter
at startup
at startup
34-cs-jmx - 10
© Copyright 2016 Pivotal. All rights reserved - 497 - Version 4.3.b
Topics in this session
• Introduction
• JMX
• Introducing Spring JMX
• Automatically exporting existing MBeans
• Spring Insight
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>
34-cs-jmx - 11
© Copyright 2016 Pivotal. All rights reserved - 498 - Version 4.3.b
Topics in this session
• Introduction
• JMX
• Introducing Spring JMX
• Automatically exporting existing MBeans
• Spring Insight
34-cs-jmx - 12
© Copyright 2016 Pivotal. All rights reserved - 499 - Version 4.3.b
Spring Insight Overview
Timeline
Servlet Selector
34-cs-jmx - 13
© Copyright 2016 Pivotal. All rights reserved - 500 - Version 4.3.b
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
Optional Lab
Monitoring and Managing a Java
Application
34-cs-jmx - 14
© Copyright 2016 Pivotal. All rights reserved - 501 - Version 4.3.b