Spring Framework 4.0 to 4.1

Sam Brannen
Sam BrannenStaff Software Engineer at VMware
Spring Framework 4.0 to 4.1
Sam Brannen
@sam_brannen
AJUG | Atlanta, GA, USA | April 22, 2014
Atlanta User Group
2
Sam Brannen
•  Spring and Java Consultant @ Swiftmind
•  Georgia Tech College of Computing Alumnus
•  Java Developer for over 15 years
•  Spring Framework Core Committer since 2007
•  Spring Trainer
•  Speaker on Spring, Java, OSGi, and testing
•  Swiss Spring User Group Lead
3
Swiftmind
Your experts for Enterprise Java
Areas of expertise
•  Spring *
•  Java EE
•  OSGi
•  Software Architecture
•  Software Engineering Best Practices
Where you find us
•  Zurich, Switzerland
•  @swiftmind
•  http://www.swiftmind.com
4
A Show of Hands…
5
Agenda
•  Spring 3.x in Review
•  Themes in Spring 4.0
•  Java EE & SE
•  Spring 4 on Java 8
•  Spring 4.1
6
Spring 3.x in Review
7
Major Themes in Spring 3.x
•  Powerful annotated component model
•  Spring Expression Language (SpEL)
•  Comprehensive REST support
•  Support for async MVC processing
•  Validation and Formatting
•  Scheduling
•  Caching
8
Spring 3.x: Key Specs (1/2)
•  JSR-330
–  Dependency Injection for Java
–  @Inject, @Qualifier, Provider mechanism
•  JSR-303
–  Bean Validation 1.0
–  declarative constraints
–  embedded validation engine
9
Spring 3.x: Key Specs (2/2)
•  JPA 2.0
–  persistence provider integration
–  Spring transactions
•  Servlet 3.0
–  web.xml-free deployment
–  async request processing
10
Testing in Spring 3.x
•  Embedded databases via <jdbc /> namespace
•  @Configuration classes & @ActiveProfiles	
•  @WebAppConfiguration	
•  @ContextHierarchy	
•  Spring MVC Test framework
11
Annotated Components
12
Configuration Classes
13
Composable Stereotypes
•  Combining meta-annotations on a custom stereotype
•  Automatically detected: no configuration necessary!
14
Spring 4.0 Themes
15
Ready for New Application Architectures
•  Embedded web servers and non-traditional data stores
•  Lightweight messaging and WebSocket-style architectures
•  Custom asynchronous processing with convenient APIs
16
New Baselines
•  Java SE 6+
•  Java EE 6+
–  Servlet 3.0/3.1 focus
–  Servlet 2.5 compatible
•  All deprecated packages removed
•  Many deprecated methods and fields removed as well
17
Third Party Libraries
•  Minimum versions ~ mid 2010 now
•  For example
–  Hibernate 3.6+
–  Quartz 1.8+
–  Ehcache 2.1+
18
Java 8 Language and API Features
•  Lambda expressions
•  Method references
•  JSR-310 Date and Time
•  Repeatable annotations
•  Parameter name discovery
19
Groovy + Spring 4.0
•  A smooth out-of-the-box experience for Groovy-based
Spring applications
•  AOP adaptations
–  special handling of GroovyObject calls
–  consider a Spring application with all components
written in the Groovy language instead of Java
•  Groovy-based bean definitions
–  formerly known as the Bean Builder in Grails
–  now lives alongside Spring's configuration class model
20
Spring Bean Def’s with Groovy DSL
import org.mypackage.domain.Person;	
beans {	
xmlns util: 'http://www.springframework.org/schema/util'	
person1(Person) {	
name = "homer"	
age = 45	
props = [overweight: true, height: "1.8m"]	
children = ["bart", "lisa"]	
}	
util.list(id: 'foo') {	
value 'one'	
value 'two'	
}	
}
21
Conditional Beans
•  A generalized model for conditional bean definitions
•  A more flexible and more dynamic variant of bean
definition profiles (as known from Spring 3.1)
•  Can be used for smart defaulting
•  See Spring Boot J
22
@Conditional
•  @Conditional annotation with programmatic Condition
implementations
•  Can react to rich context (existing bean definitions, etc.)
•  @Profile support now simply a ProfileCondition
implementation class
23
Composable Annotations w/ Overrides
•  Composable annotations may override attributes of meta-
annotations
•  Purely convention-based
–  Matched by attribute name and type
•  Cannot override the value attribute
24
Optional Annotation Attribute Override
@Scope("session")	
@Retention(RUNTIME)	
public @interface SessionScoped {	
	
ScopedProxyMode proxyMode() default ScopedProxyMode.NO;	
}	
	
	
@SessionScoped(proxyMode = TARGET_CLASS)	
public class MyScopedService {	
// ...	
}
optional
25
Required Annotation Attribute Override
@Transactional(rollbackFor = Exception.class)	
@Service	
@Retention(RUNTIME)	
public @interface TransactionalService {	
	
boolean readOnly(); // No default!	
}	
	
	
@TransactionalService(readOnly = true)	
public class MyService {	
// ...	
}
required
26
Lazy Bean Resolution Proxies
•  @Autowired @Lazy on injection point
•  Alternative to:
–  Spring’s ObjectFactory	
–  JSR-330’s Provider<MyTargetType>
27
Ordered Injection of Lists & Arrays
•  Ordered / @Order on candidate beans
•  Relative order within specific injection result
28
DI and Generics
•  Generic factory methods now fully supported in XML
configuration files
–  Mockito
–  EasyMock
–  custom
•  Type matching based on full generic type
–  e.g., MyRepository<Account>
29
Generics-based Injection Matching
@Bean	
public MyRepository<Account> accountRepository() {	
return new MyAccountRepositoryImpl();	
}	
	
	
@Service	
public class MyBookService implements BookService {	
	
@Autowired	
public MyBookService(MyRepository<Account> repo) {	
// ...	
}	
}
30
Target-class Proxies & Arbitrary Ctors
•  Before:
–  Constructor invoked when creating proxy with CGLIB
–  Potentially with adverse side effects
•  constructor invoked twice
•  Now:
–  Using Objenesis instead of CGLIB directly
–  Constructor not invoked on proxy
–  Arbitrary constructor supported on target
31
spring-messaging
•  New org.springframework.messaging module
•  Extracted from Spring Integration
•  Core message and channel abstractions
32
WebSockets
•  WebSocket endpoint model along the lines of Spring MVC
•  JSR-356 but also covering SockJS and STOMP
•  Endpoints using generic messaging patterns
33
STOMP over WebSocket
@Controller	
public class MyStompController {	
	
@SubscribeMapping("/portfolios")	
public List<Portfolio> getPortfolios(Principal user) {	
// ...	
}	
	
@MessageMapping("/trade")	
public void executeTrade(Trade trade, Principal user) {	
// ...	
}	
}
34
AsyncRestTemplate
•  Analogous to existing RestTemplate	
•  Based on ListenableFuture return values
•  Custom listeners implement ListenableFutureCallback
35
Spring + Java SE & Java EE
36
Java SE Support
•  Spring 3.1 / 3.2
–  explicit Java 7 support
–  JDK 5 à JDK 7
•  Spring 4.0
–  introduces explicit Java 8 support
–  JDK 6 à JDK 8
37
Java EE Support
•  Spring 3.1 / 3.2
–  strong Servlet 3.0 focus
–  J2EE 1.4 (deprecated) à Java EE 6
•  Spring 4.0
–  introduces explicit Java EE 7 support
–  Java EE 5 (with JPA 2.0 feature pack) à Java EE 7
38
Enterprise API Updates
•  JMS 2.0
–  delivery delay, JMS 2.0 createSession() variants, etc.
•  JTA 1.2
–  @javax.transaction.Transactional annotation
•  JPA 2.1
–  unsynchronized persistence contexts
•  Bean Validation 1.1
–  method parameter and return value constraints
39
Java 8 Programming Model
40
Java 8 Bytecode Level
•  Generated by -target 1.8	
–  compiler's default
•  Not accepted by ASM 4.x
–  Spring's bytecode parsing library
•  Spring Framework 4.0 comes with a patched, inlined (i.e.,
jarjar’ed) ASM 4.1 variant
•  Spring Framework 4.0.3 comes with ASM 5.0 inlined (i.e.,
jarjar’ed)
41
HashMap / HashSet Differences
•  Different hash algorithms in use
•  Leading to different hash iteration order
•  Code shouldn't rely on such an order but sometimes does
42
Java 8 Lambda Conventions
Simple rule: interface with single method
–  typically callback interfaces
–  for example: Runnable, Callable	
–  formerly “Single Abstract Method” (SAM) types
–  now “functional interfaces”
•  see @FunctionalInterface
43
Lambda + Spring = Natural Fit
Many Spring APIs are candidates for lambdas
–  simply by following the lambda interface conventions
44
Lambdas with JmsTemplate
MessageCreator
Message createMessage(Session session)	
	throws JMSException
45
Lambdas with TransactionTemplate
TransactionCallback
Object doInTransaction(TransactionStatus status)
46
Lambdas with JdbcTemplate
RowMapper
Object mapRow(ResultSet rs, int rowNum)	
	throws SQLException
47
Ex: Lambdas with JdbcTemplate #1
JdbcTemplate jt = new JdbcTemplate(dataSource);	
jt.query(	
"SELECT name, age FROM person WHERE dep = ?",	
ps -> ps.setString(1, "Sales"),	
(rs, rowNum) -> new Person(rs.getString(1),	
rs.getInt(2))	
);
48
Ex: Lambdas with JdbcTemplate #2
JdbcTemplate jt = new JdbcTemplate(dataSource);	
	
jt.query(	
"SELECT name, age FROM person WHERE dep = ?",	
ps -> {	
ps.setString(1, "Sales");	
},	
(rs, rowNum) -> {	
return new Person(rs.getString(1), rs.getInt(2));	
}	
);
49
Method References
public List<Person> getPersonList(String department) {	
JdbcTemplate jt = new JdbcTemplate(dataSource);	
return jt.query(	
"SELECT name, age FROM person WHERE dep = ?",	
ps -> {	
ps.setString(1, "Sales");	
},	
this::mapPerson);	
}	
	
private Person mapPerson(ResultSet rs, int rowNum)	
throws SQLException {	
return new Person(rs.getString(1), rs.getInt(2));	
}
50
JSR-310 Date and Time
import java.time.*;	
import org.springframework.format.annotation.*;	
	
public class Customer {	
	
// @DateTimeFormat(iso=ISO.DATE)	
private LocalDate birthDate;	
	
@DateTimeFormat(pattern="M/d/yy h:mm")	
private LocalDateTime lastContact;	
	
// ...	
	
}
51
@Repeatable Annotations
@Scheduled(cron = "0 0 12 * * ?")	
@Scheduled(cron = "0 0 18 * * ?")	
public void performTempFileCleanup() { /* ... */ }	
	
	
	
@Schedules({	
@Scheduled(cron = "0 0 12 * * ?"),	
@Scheduled(cron = "0 0 18 * * ?")	
})	
public void performTempFileCleanup() { /* ... */ }	
JDK 8
JDK 5+
container
repeated
52
Parameter Name Discovery
•  Java 8 defines a Parameter reflection type for methods
–  application sources compiled with –parameters	
•  Spring's StandardReflectionParameterNameDiscoverer	
–  reads parameter names via Java 8's new Parameter
type
•  Spring's DefaultParameterNameDiscoverer	
–  now checks Java 8 first (-parameters)
–  ASM-based reading of debug symbols next (-debug)
53
Ex: Parameter Name Discovery
@Controller	
public void BookController {	
	
@RequestMapping(value = "/books/{id}", method = GET)	
public Book findBook(@PathVariable long id) {	
return this.bookService.findBook(isbn);	
}	
	
}	
path variable
parameter name
54
Spring Framework 4.1
55
Themes in Spring 4.1
•  Comprehensive web resource handling
–  Resource pipelining, cache control refinements
•  Caching support revisited
–  Alignment with JCache 1.0 final, user-requested enhancements
•  JMS support overhaul
–  Alignment with messaging module, annotation-driven endpoints
•  Performance and container improvements
–  Application startup, SpEL expression evaluation, DI for generics and factory
methods
•  Unified meta-annotation programming model
–  Custom attribute overrides, value-aliases, etc.
•  Numerous new testing features
–  Groovy config, SQL script execution, bootstrap strategy, programmatic
transaction management, etc.
56
Spring MVC and Messaging
•  GroovyWebApplicationContext (SPR-11371)
•  Static resource handling in Spring MVC (SPR-10933)
•  WebSocket scope (SPR-11305)
57
Static Resource Handling in Web MVC
•  ResourceResolver API for resolving:
–  Internal static resources
–  External resource paths (i.e., links)
•  ResourceResolverChain
–  Maintains a chain of resolvers
–  Allowing for delegation
•  Configured via ResourceHandlerRegistry	
–  For example, via WebMvcConfigurationSupport
58
ResourceResolver Implementations
•  PathResourceResolver	
–  Default
–  Configure at end of chain
•  PrefixResourceResolver	
–  Custom prefix: version, release date, etc.
•  FingerprintResourceResolver	
–  MD5 hash in file name
•  GzipResourceResolver	
–  gzip compressed resources
59
Ex: Registering Resource Resolvers
@Configuration	
public class WebConfig extends WebMvcConfigurationSupport {	
	
@Override	
public void addResourceHandlers(ResourceHandlerRegistry 	
registry) {	
	
registry.addResourceHandler("/resources/**")	
.addResourceLocations("classpath:/web-resources/")	
.setResourceResolvers(new FingerprintResourceResolver(),	
new PathResourceResolver());	
}	
	
}	
resolver chain
60
JCache (JSR-107) and Spring
•  JCache 1.0 annotations now supported in Spring
•  Integration based on Spring’s own Cache and CacheManager
APIs
–  JCacheCache and JCacheCacheManager	
•  Enabled via Spring’s standard mechanisms:
–  XML: <cache:annotation-driven />	
–  Java: @EnableCaching	
•  Cache Abstraction: JCache (JSR-107) Annotations Support
–  https://spring.io/blog/2014/04/14/cache-abstraction-
jcache-jsr-107-annotations-support
61
Caching Annotation Comparison
Spring JCache
@Cacheable	 @CacheResult	
@CachePut	 @CachePut	
@CacheEvict	 @CacheRemove	
@CacheEvict(allEntries=true)	 @CacheRemoveAll
62
JMS Overhaul
•  Alignment with spring-messaging module
•  Annotation-driven endpoints
–  Analogous to <jms:listener-container />
–  Listener methods declared via @JmsListener	
–  Configured via:
•  XML: <jms:annotation-driven />	
•  Java: @EnableJms and JmsListenerConfigurer
63
Ex: @EnableJms and JavaConfig
@Configuration	
@EnableJms	
public class JmsConfig {	
	
@Bean	
public JmsListenerContainerFactory jmsListenerContainerFactory() {	
DefaultJmsListenerContainerFactory factory =	
new DefaultJmsListenerContainerFactory();	
	
factory.setConnectionFactory(connectionFactory());	
factory.setDestinationResolver(destinationResolver());	
factory.setConcurrency("5");	
	
return factory;	
}	
// other @Bean definitions	
}
64
Ex: @JmsListener
@Service	
public class MyService {	
	
@JmsListener(destination = "myQueue")	
public void process(String msg) {	
// process incoming message	
}	
}
65
Container Odds & Ends
•  @javax.annotation.Priority can be used as an
alternative to Spring’s:
–  @Order (SPR-11639)
–  @Primary (SPR-10548)
•  Annotation-driven application event listeners (SPR-11622)
–  @Listen methods instead of implementing
ApplicationListener
•  Unified meta-annotation programming model (SPR-11511)
–  Custom attribute overrides, value-aliases, etc.
66
Testing with Spring 4.1
•  Groovy config for bean definitions
•  SQL script execution and database configuration
–  ScriptUtils, ResourceDatabasePopulator, @SqlScript
•  TestContextBootstrapper strategy
–  Programmatic configuration for default
TestExecutionListeners and SmartContextLoader	
–  Configured via @BootstrapWith	
•  Programmatic starting and stopping of transactions in
integration tests
•  Numerous configuration, caching, and performance
improvements
67
Ex: EmbeddedDatabaseBuilder
EmbeddedDatabase db = new EmbeddedDatabaseBuilder()	
.setType(H2)	
.setScriptEncoding("UTF-8")	
.ignoreFailedDrops(true)	
.addScript("schema.sql")	
.addScripts("user_data.sql", "country_data.sql")	
.build();	
	
// ...	
	
db.shutdown();
68
Spring Framework 4.1 Roadmap
•  4.1 RC1: June 2014
•  4.1 RC2: July 2014
•  4.1 GA: September 2014
69
In Closing…
70
Upgrade Considerations
•  Spring 3.2 does not support 1.8 bytecode level
–  upgrade to Spring 4.0+ to enable Java 8 language features
–  caveat: partial support added in 3.2.9 (SPR-11656)
•  We strongly recommend an early upgrade to Spring 4
–  Spring Framework 4.0 still compatible with JDK 6 and 7
–  Spring Framework 3.2 is in maintenance mode
•  Spring Framework 4.0 GA released in December 2013
–  4.0.3 was released on March 26th, 2014
–  4.0.4 scheduled for end of April 2014
•  Spring Framework 4.1 GA scheduled for Sep. 2014
71
Acknowledgements
Thanks to Jürgen Höller and Stéphane Nicoll for
permitting reuse of some of their content.
72
Spring Resources
•  Spring Framework
–  http://projects.spring.io/spring-framework
•  Spring Guides
–  http://spring.io/guides
•  Spring Forums
–  http://forum.spring.io
•  Spring JIRA
–  https://jira.spring.io
•  Spring on GitHub
–  https://github.com/spring-projects/spring-framework
73
Blogs
•  Swiftmind Blog
–  http://www.swiftmind.com/blog
•  Spring Blog
–  http://spring.io/blog
74
Q & A
Sam Brannen
twitter: @sam_brannen
www.slideshare.net/sbrannen
www.swiftmind.com
1 of 74

Recommended

Spring Framework 4.0 - The Next Generation - Soft-Shake 2013 by
Spring Framework 4.0 - The Next Generation - Soft-Shake 2013Spring Framework 4.0 - The Next Generation - Soft-Shake 2013
Spring Framework 4.0 - The Next Generation - Soft-Shake 2013Sam Brannen
11.4K views58 slides
Spring framework by
Spring frameworkSpring framework
Spring frameworkAircon Chen
655 views143 slides
Introduction to Spring Framework by
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
26K views52 slides
Spring Framework - Core by
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
34.8K views117 slides
Spring Framework Rohit by
Spring Framework RohitSpring Framework Rohit
Spring Framework RohitRohit Prabhakar
2.3K views19 slides
Spring Framework by
Spring FrameworkSpring Framework
Spring FrameworkNexThoughts Technologies
3.3K views66 slides

More Related Content

What's hot

Spring introduction by
Spring introductionSpring introduction
Spring introductionManav Prasad
426 views17 slides
Spring Framework Presantation Part 1-Core by
Spring Framework Presantation Part 1-CoreSpring Framework Presantation Part 1-Core
Spring Framework Presantation Part 1-CoreDonald Lika
176 views15 slides
Spring framework core by
Spring framework coreSpring framework core
Spring framework coreTaemon Piya-Lumyong
6.5K views93 slides
Java spring framework by
Java spring frameworkJava spring framework
Java spring frameworkRajiv Gupta
2.1K views22 slides
Introduction to Spring Framework and Spring IoC by
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCFunnelll
2.1K views46 slides
Introduction to Spring Framework by
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring FrameworkASG
180 views20 slides

What's hot(19)

Spring Framework Presantation Part 1-Core by Donald Lika
Spring Framework Presantation Part 1-CoreSpring Framework Presantation Part 1-Core
Spring Framework Presantation Part 1-Core
Donald Lika176 views
Java spring framework by Rajiv Gupta
Java spring frameworkJava spring framework
Java spring framework
Rajiv Gupta2.1K views
Introduction to Spring Framework and Spring IoC by Funnelll
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
Funnelll2.1K views
Introduction to Spring Framework by ASG
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
ASG180 views
Spring Framework by tola99
Spring Framework  Spring Framework
Spring Framework
tola991.2K views
Introduction to Spring Framework by Raveendra R
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
Raveendra R427 views
Spring bean mod02 by Guo Albert
Spring bean mod02Spring bean mod02
Spring bean mod02
Guo Albert767 views
Java & J2EE Struts with Hibernate Framework by Mohit Belwal
Java & J2EE Struts with Hibernate FrameworkJava & J2EE Struts with Hibernate Framework
Java & J2EE Struts with Hibernate Framework
Mohit Belwal11.4K views
JAZOON'13 - Sam Brannen - Spring Framework 4.0 - The Next Generation by jazoon13
JAZOON'13 - Sam Brannen - Spring Framework 4.0 - The Next GenerationJAZOON'13 - Sam Brannen - Spring Framework 4.0 - The Next Generation
JAZOON'13 - Sam Brannen - Spring Framework 4.0 - The Next Generation
jazoon131.7K views
Spring core module by Raj Tomar
Spring core moduleSpring core module
Spring core module
Raj Tomar1.4K views
Spring MVC framework by Mohit Gupta
Spring MVC frameworkSpring MVC framework
Spring MVC framework
Mohit Gupta919 views
JavaOne 2011: Migrating Spring Applications to Java EE 6 by Bert Ertman
JavaOne 2011: Migrating Spring Applications to Java EE 6JavaOne 2011: Migrating Spring Applications to Java EE 6
JavaOne 2011: Migrating Spring Applications to Java EE 6
Bert Ertman119.7K views

Viewers also liked

Introduction to Spring Boot! by
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!Jakub Kubrynski
6.4K views28 slides
Spring Web MVC by
Spring Web MVCSpring Web MVC
Spring Web MVCzeeshanhanif
10.6K views44 slides
Spring Web Services: SOAP vs. REST by
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSam Brannen
22.4K views42 slides
Testing with Spring 4.x by
Testing with Spring 4.xTesting with Spring 4.x
Testing with Spring 4.xSam Brannen
1.3K views73 slides
That old Spring magic has me in its SpEL by
That old Spring magic has me in its SpELThat old Spring magic has me in its SpEL
That old Spring magic has me in its SpELCraig Walls
1.2K views141 slides
Modular Java - OSGi by
Modular Java - OSGiModular Java - OSGi
Modular Java - OSGiCraig Walls
1.4K views115 slides

Viewers also liked(19)

Spring Web MVC by zeeshanhanif
Spring Web MVCSpring Web MVC
Spring Web MVC
zeeshanhanif10.6K views
Spring Web Services: SOAP vs. REST by Sam Brannen
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
Sam Brannen22.4K views
Testing with Spring 4.x by Sam Brannen
Testing with Spring 4.xTesting with Spring 4.x
Testing with Spring 4.x
Sam Brannen1.3K views
That old Spring magic has me in its SpEL by Craig Walls
That old Spring magic has me in its SpELThat old Spring magic has me in its SpEL
That old Spring magic has me in its SpEL
Craig Walls1.2K views
Modular Java - OSGi by Craig Walls
Modular Java - OSGiModular Java - OSGi
Modular Java - OSGi
Craig Walls1.4K views
Java Configuration Deep Dive with Spring by Joshua Long
Java Configuration Deep Dive with SpringJava Configuration Deep Dive with Spring
Java Configuration Deep Dive with Spring
Joshua Long2.3K views
Spring Boot in Action by Alex Movila
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
Alex Movila3K views
Building RESTful applications using Spring MVC by IndicThreads
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC
IndicThreads9.6K views
Soap and restful webservice by Dong Ngoc
Soap and restful webserviceSoap and restful webservice
Soap and restful webservice
Dong Ngoc2K views
Spring Mvc Rest by Craig Walls
Spring Mvc RestSpring Mvc Rest
Spring Mvc Rest
Craig Walls5.2K views

Similar to Spring Framework 4.0 to 4.1

Spring 4-groovy by
Spring 4-groovySpring 4-groovy
Spring 4-groovyGR8Conf
4.6K views20 slides
Testing Spring MVC and REST Web Applications by
Testing Spring MVC and REST Web ApplicationsTesting Spring MVC and REST Web Applications
Testing Spring MVC and REST Web ApplicationsSam Brannen
3.1K views56 slides
Java SE 8 & EE 7 Launch by
Java SE 8 & EE 7 LaunchJava SE 8 & EE 7 Launch
Java SE 8 & EE 7 LaunchDigicomp Academy AG
2.1K views59 slides
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012 by
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012Sam Brannen
7.9K views83 slides
Spring Day | Spring 3.1 in a Nutshell | Sam Brannen by
Spring Day | Spring 3.1 in a Nutshell | Sam BrannenSpring Day | Spring 3.1 in a Nutshell | Sam Brannen
Spring Day | Spring 3.1 in a Nutshell | Sam BrannenJAX London
1.4K views73 slides
Spring 3.1 in a Nutshell - JAX London 2011 by
Spring 3.1 in a Nutshell - JAX London 2011Spring 3.1 in a Nutshell - JAX London 2011
Spring 3.1 in a Nutshell - JAX London 2011Sam Brannen
1.4K views73 slides

Similar to Spring Framework 4.0 to 4.1(20)

Spring 4-groovy by GR8Conf
Spring 4-groovySpring 4-groovy
Spring 4-groovy
GR8Conf4.6K views
Testing Spring MVC and REST Web Applications by Sam Brannen
Testing Spring MVC and REST Web ApplicationsTesting Spring MVC and REST Web Applications
Testing Spring MVC and REST Web Applications
Sam Brannen3.1K views
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012 by Sam Brannen
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012
Sam Brannen7.9K views
Spring Day | Spring 3.1 in a Nutshell | Sam Brannen by JAX London
Spring Day | Spring 3.1 in a Nutshell | Sam BrannenSpring Day | Spring 3.1 in a Nutshell | Sam Brannen
Spring Day | Spring 3.1 in a Nutshell | Sam Brannen
JAX London1.4K views
Spring 3.1 in a Nutshell - JAX London 2011 by Sam Brannen
Spring 3.1 in a Nutshell - JAX London 2011Spring 3.1 in a Nutshell - JAX London 2011
Spring 3.1 in a Nutshell - JAX London 2011
Sam Brannen1.4K views
Spring Day | Spring and Scala | Eberhard Wolff by JAX London
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
JAX London1.5K views
What's new in Java 8 by Kyle Smith
What's new in Java 8What's new in Java 8
What's new in Java 8
Kyle Smith445 views
Testing with Spring: An Introduction by Sam Brannen
Testing with Spring: An IntroductionTesting with Spring: An Introduction
Testing with Spring: An Introduction
Sam Brannen3.2K views
Playing with Java Classes and Bytecode by Yoav Avrahami
Playing with Java Classes and BytecodePlaying with Java Classes and Bytecode
Playing with Java Classes and Bytecode
Yoav Avrahami1.1K views
Spring Framework 3.2 - What's New by Sam Brannen
Spring Framework 3.2 - What's NewSpring Framework 3.2 - What's New
Spring Framework 3.2 - What's New
Sam Brannen7.6K views
Byte code manipulation and instrumentalization in Java by Alex Moskvin
Byte code manipulation and instrumentalization in JavaByte code manipulation and instrumentalization in Java
Byte code manipulation and instrumentalization in Java
Alex Moskvin250 views

More from Sam Brannen

Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023 by
Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023
Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023Sam Brannen
415 views36 slides
Testing with JUnit 5 and Spring - Spring I/O 2022 by
Testing with JUnit 5 and Spring - Spring I/O 2022Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022Sam Brannen
2.3K views44 slides
JUnit 5 - Evolution and Innovation - SpringOne Platform 2019 by
JUnit 5 - Evolution and Innovation - SpringOne Platform 2019JUnit 5 - Evolution and Innovation - SpringOne Platform 2019
JUnit 5 - Evolution and Innovation - SpringOne Platform 2019Sam Brannen
1.3K views61 slides
JUnit 5: What's New and What's Coming - Spring I/O 2019 by
JUnit 5: What's New and What's Coming - Spring I/O 2019JUnit 5: What's New and What's Coming - Spring I/O 2019
JUnit 5: What's New and What's Coming - Spring I/O 2019Sam Brannen
2K views70 slides
JUnit 5 - New Opportunities for Testing on the JVM by
JUnit 5 - New Opportunities for Testing on the JVMJUnit 5 - New Opportunities for Testing on the JVM
JUnit 5 - New Opportunities for Testing on the JVMSam Brannen
2.5K views65 slides
Get the Most out of Testing with Spring 4.2 by
Get the Most out of Testing with Spring 4.2Get the Most out of Testing with Spring 4.2
Get the Most out of Testing with Spring 4.2Sam Brannen
844 views64 slides

More from Sam Brannen(19)

Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023 by Sam Brannen
Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023
Testing with Spring, AOT, GraalVM, and JUnit 5 - Spring I/O 2023
Sam Brannen415 views
Testing with JUnit 5 and Spring - Spring I/O 2022 by Sam Brannen
Testing with JUnit 5 and Spring - Spring I/O 2022Testing with JUnit 5 and Spring - Spring I/O 2022
Testing with JUnit 5 and Spring - Spring I/O 2022
Sam Brannen2.3K views
JUnit 5 - Evolution and Innovation - SpringOne Platform 2019 by Sam Brannen
JUnit 5 - Evolution and Innovation - SpringOne Platform 2019JUnit 5 - Evolution and Innovation - SpringOne Platform 2019
JUnit 5 - Evolution and Innovation - SpringOne Platform 2019
Sam Brannen1.3K views
JUnit 5: What's New and What's Coming - Spring I/O 2019 by Sam Brannen
JUnit 5: What's New and What's Coming - Spring I/O 2019JUnit 5: What's New and What's Coming - Spring I/O 2019
JUnit 5: What's New and What's Coming - Spring I/O 2019
Sam Brannen2K views
JUnit 5 - New Opportunities for Testing on the JVM by Sam Brannen
JUnit 5 - New Opportunities for Testing on the JVMJUnit 5 - New Opportunities for Testing on the JVM
JUnit 5 - New Opportunities for Testing on the JVM
Sam Brannen2.5K views
Get the Most out of Testing with Spring 4.2 by Sam Brannen
Get the Most out of Testing with Spring 4.2Get the Most out of Testing with Spring 4.2
Get the Most out of Testing with Spring 4.2
Sam Brannen844 views
JUnit 5 - from Lambda to Alpha and beyond by Sam Brannen
JUnit 5 - from Lambda to Alpha and beyondJUnit 5 - from Lambda to Alpha and beyond
JUnit 5 - from Lambda to Alpha and beyond
Sam Brannen3.2K views
Spring Framework 4.1 by Sam Brannen
Spring Framework 4.1Spring Framework 4.1
Spring Framework 4.1
Sam Brannen1.7K views
Composable Software Architecture with Spring by Sam Brannen
Composable Software Architecture with SpringComposable Software Architecture with Spring
Composable Software Architecture with Spring
Sam Brannen2.2K views
Testing Web Apps with Spring Framework 3.2 by Sam Brannen
Testing Web Apps with Spring Framework 3.2Testing Web Apps with Spring Framework 3.2
Testing Web Apps with Spring Framework 3.2
Sam Brannen1.5K views
Spring 3.1 and MVC Testing Support - 4Developers by Sam Brannen
Spring 3.1 and MVC Testing Support - 4DevelopersSpring 3.1 and MVC Testing Support - 4Developers
Spring 3.1 and MVC Testing Support - 4Developers
Sam Brannen1.6K views
Effective out-of-container Integration Testing - 4Developers by Sam Brannen
Effective out-of-container Integration Testing - 4DevelopersEffective out-of-container Integration Testing - 4Developers
Effective out-of-container Integration Testing - 4Developers
Sam Brannen1.6K views
Spring 3.1 to 3.2 in a Nutshell - SDC2012 by Sam Brannen
Spring 3.1 to 3.2 in a Nutshell - SDC2012Spring 3.1 to 3.2 in a Nutshell - SDC2012
Spring 3.1 to 3.2 in a Nutshell - SDC2012
Sam Brannen930 views
Spring 3.1 and MVC Testing Support by Sam Brannen
Spring 3.1 and MVC Testing SupportSpring 3.1 and MVC Testing Support
Spring 3.1 and MVC Testing Support
Sam Brannen8.3K views
Spring 3.1 in a Nutshell by Sam Brannen
Spring 3.1 in a NutshellSpring 3.1 in a Nutshell
Spring 3.1 in a Nutshell
Sam Brannen5.4K views
Effective out-of-container Integration Testing by Sam Brannen
Effective out-of-container Integration TestingEffective out-of-container Integration Testing
Effective out-of-container Integration Testing
Sam Brannen2.2K views
What's New in Spring 3.0 by Sam Brannen
What's New in Spring 3.0What's New in Spring 3.0
What's New in Spring 3.0
Sam Brannen1.8K views
Modular Web Applications with OSGi by Sam Brannen
Modular Web Applications with OSGiModular Web Applications with OSGi
Modular Web Applications with OSGi
Sam Brannen3.2K views
Enterprise Applications With OSGi and SpringSource dm Server by Sam Brannen
Enterprise Applications With OSGi and SpringSource dm ServerEnterprise Applications With OSGi and SpringSource dm Server
Enterprise Applications With OSGi and SpringSource dm Server
Sam Brannen1.2K views

Recently uploaded

Top-5-production-devconMunich-2023.pptx by
Top-5-production-devconMunich-2023.pptxTop-5-production-devconMunich-2023.pptx
Top-5-production-devconMunich-2023.pptxTier1 app
8 views40 slides
JioEngage_Presentation.pptx by
JioEngage_Presentation.pptxJioEngage_Presentation.pptx
JioEngage_Presentation.pptxadmin125455
6 views4 slides
Programming Field by
Programming FieldProgramming Field
Programming Fieldthehardtechnology
5 views9 slides
EV Charging App Case by
EV Charging App Case EV Charging App Case
EV Charging App Case iCoderz Solutions
8 views1 slide
predicting-m3-devopsconMunich-2023.pptx by
predicting-m3-devopsconMunich-2023.pptxpredicting-m3-devopsconMunich-2023.pptx
predicting-m3-devopsconMunich-2023.pptxTier1 app
7 views24 slides
Dapr Unleashed: Accelerating Microservice Development by
Dapr Unleashed: Accelerating Microservice DevelopmentDapr Unleashed: Accelerating Microservice Development
Dapr Unleashed: Accelerating Microservice DevelopmentMiroslav Janeski
12 views29 slides

Recently uploaded(20)

Top-5-production-devconMunich-2023.pptx by Tier1 app
Top-5-production-devconMunich-2023.pptxTop-5-production-devconMunich-2023.pptx
Top-5-production-devconMunich-2023.pptx
Tier1 app8 views
JioEngage_Presentation.pptx by admin125455
JioEngage_Presentation.pptxJioEngage_Presentation.pptx
JioEngage_Presentation.pptx
admin1254556 views
predicting-m3-devopsconMunich-2023.pptx by Tier1 app
predicting-m3-devopsconMunich-2023.pptxpredicting-m3-devopsconMunich-2023.pptx
predicting-m3-devopsconMunich-2023.pptx
Tier1 app7 views
Dapr Unleashed: Accelerating Microservice Development by Miroslav Janeski
Dapr Unleashed: Accelerating Microservice DevelopmentDapr Unleashed: Accelerating Microservice Development
Dapr Unleashed: Accelerating Microservice Development
Miroslav Janeski12 views
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P... by NimaTorabi2
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...
Unlocking the Power of AI in Product Management - A Comprehensive Guide for P...
NimaTorabi215 views
FIMA 2023 Neo4j & FS - Entity Resolution.pptx by Neo4j
FIMA 2023 Neo4j & FS - Entity Resolution.pptxFIMA 2023 Neo4j & FS - Entity Resolution.pptx
FIMA 2023 Neo4j & FS - Entity Resolution.pptx
Neo4j12 views
Bootstrapping vs Venture Capital.pptx by Zeljko Svedic
Bootstrapping vs Venture Capital.pptxBootstrapping vs Venture Capital.pptx
Bootstrapping vs Venture Capital.pptx
Zeljko Svedic12 views
Quality Engineer: A Day in the Life by John Valentino
Quality Engineer: A Day in the LifeQuality Engineer: A Day in the Life
Quality Engineer: A Day in the Life
John Valentino6 views
Gen Apps on Google Cloud PaLM2 and Codey APIs in Action by Márton Kodok
Gen Apps on Google Cloud PaLM2 and Codey APIs in ActionGen Apps on Google Cloud PaLM2 and Codey APIs in Action
Gen Apps on Google Cloud PaLM2 and Codey APIs in Action
Márton Kodok11 views
360 graden fabriek by info33492
360 graden fabriek360 graden fabriek
360 graden fabriek
info33492138 views
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium... by Lisi Hocke
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Team Transformation Tactics for Holistic Testing and Quality (Japan Symposium...
Lisi Hocke35 views
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with... by sparkfabrik
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...
20231129 - Platform @ localhost 2023 - Application-driven infrastructure with...
sparkfabrik8 views
Copilot Prompting Toolkit_All Resources.pdf by Riccardo Zamana
Copilot Prompting Toolkit_All Resources.pdfCopilot Prompting Toolkit_All Resources.pdf
Copilot Prompting Toolkit_All Resources.pdf
Riccardo Zamana11 views

Spring Framework 4.0 to 4.1

  • 1. Spring Framework 4.0 to 4.1 Sam Brannen @sam_brannen AJUG | Atlanta, GA, USA | April 22, 2014 Atlanta User Group
  • 2. 2 Sam Brannen •  Spring and Java Consultant @ Swiftmind •  Georgia Tech College of Computing Alumnus •  Java Developer for over 15 years •  Spring Framework Core Committer since 2007 •  Spring Trainer •  Speaker on Spring, Java, OSGi, and testing •  Swiss Spring User Group Lead
  • 3. 3 Swiftmind Your experts for Enterprise Java Areas of expertise •  Spring * •  Java EE •  OSGi •  Software Architecture •  Software Engineering Best Practices Where you find us •  Zurich, Switzerland •  @swiftmind •  http://www.swiftmind.com
  • 4. 4 A Show of Hands…
  • 5. 5 Agenda •  Spring 3.x in Review •  Themes in Spring 4.0 •  Java EE & SE •  Spring 4 on Java 8 •  Spring 4.1
  • 7. 7 Major Themes in Spring 3.x •  Powerful annotated component model •  Spring Expression Language (SpEL) •  Comprehensive REST support •  Support for async MVC processing •  Validation and Formatting •  Scheduling •  Caching
  • 8. 8 Spring 3.x: Key Specs (1/2) •  JSR-330 –  Dependency Injection for Java –  @Inject, @Qualifier, Provider mechanism •  JSR-303 –  Bean Validation 1.0 –  declarative constraints –  embedded validation engine
  • 9. 9 Spring 3.x: Key Specs (2/2) •  JPA 2.0 –  persistence provider integration –  Spring transactions •  Servlet 3.0 –  web.xml-free deployment –  async request processing
  • 10. 10 Testing in Spring 3.x •  Embedded databases via <jdbc /> namespace •  @Configuration classes & @ActiveProfiles •  @WebAppConfiguration •  @ContextHierarchy •  Spring MVC Test framework
  • 13. 13 Composable Stereotypes •  Combining meta-annotations on a custom stereotype •  Automatically detected: no configuration necessary!
  • 15. 15 Ready for New Application Architectures •  Embedded web servers and non-traditional data stores •  Lightweight messaging and WebSocket-style architectures •  Custom asynchronous processing with convenient APIs
  • 16. 16 New Baselines •  Java SE 6+ •  Java EE 6+ –  Servlet 3.0/3.1 focus –  Servlet 2.5 compatible •  All deprecated packages removed •  Many deprecated methods and fields removed as well
  • 17. 17 Third Party Libraries •  Minimum versions ~ mid 2010 now •  For example –  Hibernate 3.6+ –  Quartz 1.8+ –  Ehcache 2.1+
  • 18. 18 Java 8 Language and API Features •  Lambda expressions •  Method references •  JSR-310 Date and Time •  Repeatable annotations •  Parameter name discovery
  • 19. 19 Groovy + Spring 4.0 •  A smooth out-of-the-box experience for Groovy-based Spring applications •  AOP adaptations –  special handling of GroovyObject calls –  consider a Spring application with all components written in the Groovy language instead of Java •  Groovy-based bean definitions –  formerly known as the Bean Builder in Grails –  now lives alongside Spring's configuration class model
  • 20. 20 Spring Bean Def’s with Groovy DSL import org.mypackage.domain.Person; beans { xmlns util: 'http://www.springframework.org/schema/util' person1(Person) { name = "homer" age = 45 props = [overweight: true, height: "1.8m"] children = ["bart", "lisa"] } util.list(id: 'foo') { value 'one' value 'two' } }
  • 21. 21 Conditional Beans •  A generalized model for conditional bean definitions •  A more flexible and more dynamic variant of bean definition profiles (as known from Spring 3.1) •  Can be used for smart defaulting •  See Spring Boot J
  • 22. 22 @Conditional •  @Conditional annotation with programmatic Condition implementations •  Can react to rich context (existing bean definitions, etc.) •  @Profile support now simply a ProfileCondition implementation class
  • 23. 23 Composable Annotations w/ Overrides •  Composable annotations may override attributes of meta- annotations •  Purely convention-based –  Matched by attribute name and type •  Cannot override the value attribute
  • 24. 24 Optional Annotation Attribute Override @Scope("session") @Retention(RUNTIME) public @interface SessionScoped { ScopedProxyMode proxyMode() default ScopedProxyMode.NO; } @SessionScoped(proxyMode = TARGET_CLASS) public class MyScopedService { // ... } optional
  • 25. 25 Required Annotation Attribute Override @Transactional(rollbackFor = Exception.class) @Service @Retention(RUNTIME) public @interface TransactionalService { boolean readOnly(); // No default! } @TransactionalService(readOnly = true) public class MyService { // ... } required
  • 26. 26 Lazy Bean Resolution Proxies •  @Autowired @Lazy on injection point •  Alternative to: –  Spring’s ObjectFactory –  JSR-330’s Provider<MyTargetType>
  • 27. 27 Ordered Injection of Lists & Arrays •  Ordered / @Order on candidate beans •  Relative order within specific injection result
  • 28. 28 DI and Generics •  Generic factory methods now fully supported in XML configuration files –  Mockito –  EasyMock –  custom •  Type matching based on full generic type –  e.g., MyRepository<Account>
  • 29. 29 Generics-based Injection Matching @Bean public MyRepository<Account> accountRepository() { return new MyAccountRepositoryImpl(); } @Service public class MyBookService implements BookService { @Autowired public MyBookService(MyRepository<Account> repo) { // ... } }
  • 30. 30 Target-class Proxies & Arbitrary Ctors •  Before: –  Constructor invoked when creating proxy with CGLIB –  Potentially with adverse side effects •  constructor invoked twice •  Now: –  Using Objenesis instead of CGLIB directly –  Constructor not invoked on proxy –  Arbitrary constructor supported on target
  • 31. 31 spring-messaging •  New org.springframework.messaging module •  Extracted from Spring Integration •  Core message and channel abstractions
  • 32. 32 WebSockets •  WebSocket endpoint model along the lines of Spring MVC •  JSR-356 but also covering SockJS and STOMP •  Endpoints using generic messaging patterns
  • 33. 33 STOMP over WebSocket @Controller public class MyStompController { @SubscribeMapping("/portfolios") public List<Portfolio> getPortfolios(Principal user) { // ... } @MessageMapping("/trade") public void executeTrade(Trade trade, Principal user) { // ... } }
  • 34. 34 AsyncRestTemplate •  Analogous to existing RestTemplate •  Based on ListenableFuture return values •  Custom listeners implement ListenableFutureCallback
  • 35. 35 Spring + Java SE & Java EE
  • 36. 36 Java SE Support •  Spring 3.1 / 3.2 –  explicit Java 7 support –  JDK 5 à JDK 7 •  Spring 4.0 –  introduces explicit Java 8 support –  JDK 6 à JDK 8
  • 37. 37 Java EE Support •  Spring 3.1 / 3.2 –  strong Servlet 3.0 focus –  J2EE 1.4 (deprecated) à Java EE 6 •  Spring 4.0 –  introduces explicit Java EE 7 support –  Java EE 5 (with JPA 2.0 feature pack) à Java EE 7
  • 38. 38 Enterprise API Updates •  JMS 2.0 –  delivery delay, JMS 2.0 createSession() variants, etc. •  JTA 1.2 –  @javax.transaction.Transactional annotation •  JPA 2.1 –  unsynchronized persistence contexts •  Bean Validation 1.1 –  method parameter and return value constraints
  • 40. 40 Java 8 Bytecode Level •  Generated by -target 1.8 –  compiler's default •  Not accepted by ASM 4.x –  Spring's bytecode parsing library •  Spring Framework 4.0 comes with a patched, inlined (i.e., jarjar’ed) ASM 4.1 variant •  Spring Framework 4.0.3 comes with ASM 5.0 inlined (i.e., jarjar’ed)
  • 41. 41 HashMap / HashSet Differences •  Different hash algorithms in use •  Leading to different hash iteration order •  Code shouldn't rely on such an order but sometimes does
  • 42. 42 Java 8 Lambda Conventions Simple rule: interface with single method –  typically callback interfaces –  for example: Runnable, Callable –  formerly “Single Abstract Method” (SAM) types –  now “functional interfaces” •  see @FunctionalInterface
  • 43. 43 Lambda + Spring = Natural Fit Many Spring APIs are candidates for lambdas –  simply by following the lambda interface conventions
  • 44. 44 Lambdas with JmsTemplate MessageCreator Message createMessage(Session session) throws JMSException
  • 45. 45 Lambdas with TransactionTemplate TransactionCallback Object doInTransaction(TransactionStatus status)
  • 46. 46 Lambdas with JdbcTemplate RowMapper Object mapRow(ResultSet rs, int rowNum) throws SQLException
  • 47. 47 Ex: Lambdas with JdbcTemplate #1 JdbcTemplate jt = new JdbcTemplate(dataSource); jt.query( "SELECT name, age FROM person WHERE dep = ?", ps -> ps.setString(1, "Sales"), (rs, rowNum) -> new Person(rs.getString(1), rs.getInt(2)) );
  • 48. 48 Ex: Lambdas with JdbcTemplate #2 JdbcTemplate jt = new JdbcTemplate(dataSource); jt.query( "SELECT name, age FROM person WHERE dep = ?", ps -> { ps.setString(1, "Sales"); }, (rs, rowNum) -> { return new Person(rs.getString(1), rs.getInt(2)); } );
  • 49. 49 Method References public List<Person> getPersonList(String department) { JdbcTemplate jt = new JdbcTemplate(dataSource); return jt.query( "SELECT name, age FROM person WHERE dep = ?", ps -> { ps.setString(1, "Sales"); }, this::mapPerson); } private Person mapPerson(ResultSet rs, int rowNum) throws SQLException { return new Person(rs.getString(1), rs.getInt(2)); }
  • 50. 50 JSR-310 Date and Time import java.time.*; import org.springframework.format.annotation.*; public class Customer { // @DateTimeFormat(iso=ISO.DATE) private LocalDate birthDate; @DateTimeFormat(pattern="M/d/yy h:mm") private LocalDateTime lastContact; // ... }
  • 51. 51 @Repeatable Annotations @Scheduled(cron = "0 0 12 * * ?") @Scheduled(cron = "0 0 18 * * ?") public void performTempFileCleanup() { /* ... */ } @Schedules({ @Scheduled(cron = "0 0 12 * * ?"), @Scheduled(cron = "0 0 18 * * ?") }) public void performTempFileCleanup() { /* ... */ } JDK 8 JDK 5+ container repeated
  • 52. 52 Parameter Name Discovery •  Java 8 defines a Parameter reflection type for methods –  application sources compiled with –parameters •  Spring's StandardReflectionParameterNameDiscoverer –  reads parameter names via Java 8's new Parameter type •  Spring's DefaultParameterNameDiscoverer –  now checks Java 8 first (-parameters) –  ASM-based reading of debug symbols next (-debug)
  • 53. 53 Ex: Parameter Name Discovery @Controller public void BookController { @RequestMapping(value = "/books/{id}", method = GET) public Book findBook(@PathVariable long id) { return this.bookService.findBook(isbn); } } path variable parameter name
  • 55. 55 Themes in Spring 4.1 •  Comprehensive web resource handling –  Resource pipelining, cache control refinements •  Caching support revisited –  Alignment with JCache 1.0 final, user-requested enhancements •  JMS support overhaul –  Alignment with messaging module, annotation-driven endpoints •  Performance and container improvements –  Application startup, SpEL expression evaluation, DI for generics and factory methods •  Unified meta-annotation programming model –  Custom attribute overrides, value-aliases, etc. •  Numerous new testing features –  Groovy config, SQL script execution, bootstrap strategy, programmatic transaction management, etc.
  • 56. 56 Spring MVC and Messaging •  GroovyWebApplicationContext (SPR-11371) •  Static resource handling in Spring MVC (SPR-10933) •  WebSocket scope (SPR-11305)
  • 57. 57 Static Resource Handling in Web MVC •  ResourceResolver API for resolving: –  Internal static resources –  External resource paths (i.e., links) •  ResourceResolverChain –  Maintains a chain of resolvers –  Allowing for delegation •  Configured via ResourceHandlerRegistry –  For example, via WebMvcConfigurationSupport
  • 58. 58 ResourceResolver Implementations •  PathResourceResolver –  Default –  Configure at end of chain •  PrefixResourceResolver –  Custom prefix: version, release date, etc. •  FingerprintResourceResolver –  MD5 hash in file name •  GzipResourceResolver –  gzip compressed resources
  • 59. 59 Ex: Registering Resource Resolvers @Configuration public class WebConfig extends WebMvcConfigurationSupport { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**") .addResourceLocations("classpath:/web-resources/") .setResourceResolvers(new FingerprintResourceResolver(), new PathResourceResolver()); } } resolver chain
  • 60. 60 JCache (JSR-107) and Spring •  JCache 1.0 annotations now supported in Spring •  Integration based on Spring’s own Cache and CacheManager APIs –  JCacheCache and JCacheCacheManager •  Enabled via Spring’s standard mechanisms: –  XML: <cache:annotation-driven /> –  Java: @EnableCaching •  Cache Abstraction: JCache (JSR-107) Annotations Support –  https://spring.io/blog/2014/04/14/cache-abstraction- jcache-jsr-107-annotations-support
  • 61. 61 Caching Annotation Comparison Spring JCache @Cacheable @CacheResult @CachePut @CachePut @CacheEvict @CacheRemove @CacheEvict(allEntries=true) @CacheRemoveAll
  • 62. 62 JMS Overhaul •  Alignment with spring-messaging module •  Annotation-driven endpoints –  Analogous to <jms:listener-container /> –  Listener methods declared via @JmsListener –  Configured via: •  XML: <jms:annotation-driven /> •  Java: @EnableJms and JmsListenerConfigurer
  • 63. 63 Ex: @EnableJms and JavaConfig @Configuration @EnableJms public class JmsConfig { @Bean public JmsListenerContainerFactory jmsListenerContainerFactory() { DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); factory.setConnectionFactory(connectionFactory()); factory.setDestinationResolver(destinationResolver()); factory.setConcurrency("5"); return factory; } // other @Bean definitions }
  • 64. 64 Ex: @JmsListener @Service public class MyService { @JmsListener(destination = "myQueue") public void process(String msg) { // process incoming message } }
  • 65. 65 Container Odds & Ends •  @javax.annotation.Priority can be used as an alternative to Spring’s: –  @Order (SPR-11639) –  @Primary (SPR-10548) •  Annotation-driven application event listeners (SPR-11622) –  @Listen methods instead of implementing ApplicationListener •  Unified meta-annotation programming model (SPR-11511) –  Custom attribute overrides, value-aliases, etc.
  • 66. 66 Testing with Spring 4.1 •  Groovy config for bean definitions •  SQL script execution and database configuration –  ScriptUtils, ResourceDatabasePopulator, @SqlScript •  TestContextBootstrapper strategy –  Programmatic configuration for default TestExecutionListeners and SmartContextLoader –  Configured via @BootstrapWith •  Programmatic starting and stopping of transactions in integration tests •  Numerous configuration, caching, and performance improvements
  • 67. 67 Ex: EmbeddedDatabaseBuilder EmbeddedDatabase db = new EmbeddedDatabaseBuilder() .setType(H2) .setScriptEncoding("UTF-8") .ignoreFailedDrops(true) .addScript("schema.sql") .addScripts("user_data.sql", "country_data.sql") .build(); // ... db.shutdown();
  • 68. 68 Spring Framework 4.1 Roadmap •  4.1 RC1: June 2014 •  4.1 RC2: July 2014 •  4.1 GA: September 2014
  • 70. 70 Upgrade Considerations •  Spring 3.2 does not support 1.8 bytecode level –  upgrade to Spring 4.0+ to enable Java 8 language features –  caveat: partial support added in 3.2.9 (SPR-11656) •  We strongly recommend an early upgrade to Spring 4 –  Spring Framework 4.0 still compatible with JDK 6 and 7 –  Spring Framework 3.2 is in maintenance mode •  Spring Framework 4.0 GA released in December 2013 –  4.0.3 was released on March 26th, 2014 –  4.0.4 scheduled for end of April 2014 •  Spring Framework 4.1 GA scheduled for Sep. 2014
  • 71. 71 Acknowledgements Thanks to Jürgen Höller and Stéphane Nicoll for permitting reuse of some of their content.
  • 72. 72 Spring Resources •  Spring Framework –  http://projects.spring.io/spring-framework •  Spring Guides –  http://spring.io/guides •  Spring Forums –  http://forum.spring.io •  Spring JIRA –  https://jira.spring.io •  Spring on GitHub –  https://github.com/spring-projects/spring-framework
  • 73. 73 Blogs •  Swiftmind Blog –  http://www.swiftmind.com/blog •  Spring Blog –  http://spring.io/blog
  • 74. 74 Q & A Sam Brannen twitter: @sam_brannen www.slideshare.net/sbrannen www.swiftmind.com