spring framework 4.0 to 4.1

74
Spring Framework 4.0 to 4.1 Sam Brannen @sam_brannen AJUG | Atlanta, GA, USA | April 22, 2014 Atlanta User Group

Upload: sam-brannen

Post on 27-Aug-2014

3.210 views

Category:

Software


14 download

DESCRIPTION

Spring Framework 4.0 is the latest generation of the popular open source framework for Enterprise Java developers, focusing on the future with support for Java SE 8 and Java EE 7. In this presentation core Spring committer Sam Brannen will provide attendees an overview of the new enterprise features in the framework as well as new programming models made possible with the adoption of JDK 8 language features and APIs. Specifically, this talk will cover support for lambda expressions and method references against Spring callback interfaces, JSR-310 Date-Time value types for Spring data binding and formatting, Spring's new @Conditional mechanism for activation of bean definitions, and a new WebSocket endpoint model. The presentation also provides an overview of Spring 4.0's updated support for enterprise APIs such as JMS 2.0, JPA 2.1, Bean Validation 1.1, Servlet 3.1, and JCache. Last but not least, Sam will highlight some of the major themes for the upcoming Spring Framework 4.1 release such as support for JCache 1.0 annotations, annotation-driven JMS listeners, and testing improvements.

TRANSCRIPT

Page 1: Spring Framework 4.0 to 4.1

Spring Framework 4.0 to 4.1 Sam Brannen @sam_brannen

AJUG | Atlanta, GA, USA | April 22, 2014

Atlanta User Group

Page 2: Spring Framework 4.0 to 4.1

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

Page 3: Spring Framework 4.0 to 4.1

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

Page 4: Spring Framework 4.0 to 4.1

4

A Show of Hands…

Page 5: Spring Framework 4.0 to 4.1

5

Agenda

•  Spring 3.x in Review

•  Themes in Spring 4.0

•  Java EE & SE

•  Spring 4 on Java 8

•  Spring 4.1

Page 6: Spring Framework 4.0 to 4.1

6

Spring 3.x in Review

Page 7: Spring Framework 4.0 to 4.1

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

Page 8: Spring Framework 4.0 to 4.1

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

Page 9: Spring Framework 4.0 to 4.1

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

Page 10: Spring Framework 4.0 to 4.1

10

Testing in Spring 3.x

•  Embedded databases via <jdbc /> namespace

•  @Configuration classes & @ActiveProfiles

•  @WebAppConfiguration

•  @ContextHierarchy

•  Spring MVC Test framework

Page 11: Spring Framework 4.0 to 4.1

11

Annotated Components

Page 12: Spring Framework 4.0 to 4.1

12

Configuration Classes

Page 13: Spring Framework 4.0 to 4.1

13

Composable Stereotypes

•  Combining meta-annotations on a custom stereotype •  Automatically detected: no configuration necessary!

Page 14: Spring Framework 4.0 to 4.1

14

Spring 4.0 Themes

Page 15: Spring Framework 4.0 to 4.1

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

Page 16: Spring Framework 4.0 to 4.1

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

Page 17: Spring Framework 4.0 to 4.1

17

Third Party Libraries

•  Minimum versions ~ mid 2010 now

•  For example –  Hibernate 3.6+ –  Quartz 1.8+ –  Ehcache 2.1+

Page 18: Spring Framework 4.0 to 4.1

18

Java 8 Language and API Features

•  Lambda expressions

•  Method references

•  JSR-310 Date and Time

•  Repeatable annotations

•  Parameter name discovery

Page 19: Spring Framework 4.0 to 4.1

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

Page 20: Spring Framework 4.0 to 4.1

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' }}

Page 21: Spring Framework 4.0 to 4.1

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

Page 22: Spring Framework 4.0 to 4.1

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

Page 23: Spring Framework 4.0 to 4.1

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

Page 24: Spring Framework 4.0 to 4.1

24

Ex: Annotation Attribute Overrides #1

@Scope("session")@Retention(RUNTIME)public @interface SessionScoped { ScopedProxyMode proxyMode() default ScopedProxyMode.NO;}@SessionScoped(proxyMode = TARGET_CLASS)public class MyScopedService { // ...}

Optional

Page 25: Spring Framework 4.0 to 4.1

25

Ex: Annotation Attribute Overrides #2

@Transactional(rollbackFor = Exception.class)@Service@Retention(RUNTIME)public @interface TransactionalService { boolean readOnly(); // No default!}@TransactionalService(readOnly = true)public class MyService { // ...}

Required

Page 26: Spring Framework 4.0 to 4.1

26

Lazy Bean Resolution Proxies

•  @Autowired @Lazy on injection point

•  Alternative to: –  Spring’s ObjectFactory–  JSR-330’s Provider<MyTargetType>

Page 27: Spring Framework 4.0 to 4.1

27

Ordered Injection of Lists & Arrays

•  Ordered / @Order on candidate beans

•  Relative order within specific injection result

Page 28: Spring Framework 4.0 to 4.1

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>

Page 29: Spring Framework 4.0 to 4.1

29

Generics-based Injection Matching

@Beanpublic MyRepository<Account> accountRepository() { return new MyAccountRepositoryImpl();}@Servicepublic class MyBookService implements BookService { @Autowired public MyBookService(MyRepository<Account> repo) { // ... }}

Page 30: Spring Framework 4.0 to 4.1

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

Page 31: Spring Framework 4.0 to 4.1

31

spring-messaging

•  New org.springframework.messaging module

•  Extracted from Spring Integration

•  Core message and channel abstractions

Page 32: Spring Framework 4.0 to 4.1

32

WebSockets

•  WebSocket endpoint model along the lines of Spring MVC

•  JSR-356 but also covering SockJS and STOMP

•  Endpoints using generic messaging patterns

Page 33: Spring Framework 4.0 to 4.1

33

STOMP over WebSocket

@Controllerpublic class MyStompController { @SubscribeMapping("/portfolios") public List<Portfolio> getPortfolios(Principal user) { // ... } @MessageMapping("/trade") public void executeTrade(Trade trade, Principal user) { // ... }}

Page 34: Spring Framework 4.0 to 4.1

34

AsyncRestTemplate

•  Analogous to existing RestTemplate

•  Based on ListenableFuture return values

•  Custom listeners implement ListenableFutureCallback

Page 35: Spring Framework 4.0 to 4.1

35

Spring + Java SE & Java EE

Page 36: Spring Framework 4.0 to 4.1

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

Page 37: Spring Framework 4.0 to 4.1

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

Page 38: Spring Framework 4.0 to 4.1

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

Page 39: Spring Framework 4.0 to 4.1

39

Java 8 Programming Model

Page 40: Spring Framework 4.0 to 4.1

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)

Page 41: Spring Framework 4.0 to 4.1

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

Page 42: Spring Framework 4.0 to 4.1

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

Page 43: Spring Framework 4.0 to 4.1

43

Lambda + Spring = Natural Fit

Many Spring APIs are candidates for lambdas

–  simply by following the lambda interface conventions

Page 44: Spring Framework 4.0 to 4.1

44

Lambdas with JmsTemplate

MessageCreator

Message createMessage(Session session)throws JMSException

Page 45: Spring Framework 4.0 to 4.1

45

Lambdas with TransactionTemplate

TransactionCallback

Object doInTransaction(TransactionStatus status)

Page 46: Spring Framework 4.0 to 4.1

46

Lambdas with JdbcTemplate

RowMapper

Object mapRow(ResultSet rs, int rowNum)throws SQLException

Page 47: Spring Framework 4.0 to 4.1

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)));

Page 48: Spring Framework 4.0 to 4.1

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)); });

Page 49: Spring Framework 4.0 to 4.1

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));}

Page 50: Spring Framework 4.0 to 4.1

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; // ...}

Page 51: Spring Framework 4.0 to 4.1

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

Page 52: Spring Framework 4.0 to 4.1

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)

Page 53: Spring Framework 4.0 to 4.1

53

Ex: Parameter Name Discovery

@Controllerpublic void BookController { @RequestMapping(value = "/books/{id}", method = GET) public Book findBook(@PathVariable long id) { return this.bookService.findBook(isbn); }}

Path Variable

Parameter Name

Page 54: Spring Framework 4.0 to 4.1

54

Spring Framework 4.1

Page 55: Spring Framework 4.0 to 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.

Page 56: Spring Framework 4.0 to 4.1

56

Spring MVC and Messaging

•  GroovyWebApplicationContext (SPR-11371) •  Static resource handling in Spring MVC (SPR-10933)

•  WebSocket scope (SPR-11305)

Page 57: Spring Framework 4.0 to 4.1

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

Page 58: Spring Framework 4.0 to 4.1

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

Page 59: Spring Framework 4.0 to 4.1

59

Ex: Registering Resource Resolvers

@Configurationpublic class WebConfig extends WebMvcConfigurationSupport { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { List<ResourceResolver> chain = new ArrayList<>(); chain.add(new FingerprintResourceResolver()); chain.add(new PathResourceResolver()); registry.addResourceHandler("/resources/**") .addResourceLocations("classpath:/web-resources/") .setResourceResolvers(chain); }} register

chain

Page 60: Spring Framework 4.0 to 4.1

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

Page 61: Spring Framework 4.0 to 4.1

61

Caching Annotation Comparison

Spring JCache @Cacheable @CacheResult@CachePut @CachePut@CacheEvict @CacheRemove@CacheEvict(allEntries=true) @CacheRemoveAll

Page 62: Spring Framework 4.0 to 4.1

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

Page 63: Spring Framework 4.0 to 4.1

63

Ex: @EnableJms and JavaConfig

@Configuration@EnableJmspublic class JmsConfig { @Bean public DefaultJmsListenerContainerFactory jmsListenerContainerFactory() { DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); factory.setConnectionFactory(connectionFactory()); factory.setDestinationResolver(destinationResolver()); factory.setConcurrency("5"); return factory; } // other @Bean definitions}

Page 64: Spring Framework 4.0 to 4.1

64

Ex: @JmsListener

@Servicepublic class MyService { @JmsListener(destination = "myQueue") public void process(String msg) { // process incoming message }}

Page 65: Spring Framework 4.0 to 4.1

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.

Page 66: Spring Framework 4.0 to 4.1

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

Page 67: Spring Framework 4.0 to 4.1

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();

Page 68: Spring Framework 4.0 to 4.1

68

Spring Framework 4.1 Roadmap

•  4.1 RC1: June 2014

•  4.1 RC2: July 2014

•  4.1 GA: September 2014

Page 69: Spring Framework 4.0 to 4.1

69

In Closing…

Page 70: Spring Framework 4.0 to 4.1

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

Page 71: Spring Framework 4.0 to 4.1

71

Acknowledgements

Thanks to Jürgen Höller and Stéphane Nicoll for permitting reuse of some of their content.

Page 72: Spring Framework 4.0 to 4.1

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

Page 73: Spring Framework 4.0 to 4.1

73

Blogs

•  Swiftmind Blog –  http://www.swiftmind.com/blog

•  Spring Blog –  http://spring.io/blog

Page 74: Spring Framework 4.0 to 4.1

74

Q & A

Sam Brannen twitter: @sam_brannen www.slideshare.net/sbrannen www.swiftmind.com