Spring Framework 4.0 to 4.1

11,844 views

Published on

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.

Published in: Software, Technology, Education

Spring Framework 4.0 to 4.1

  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. 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. 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. 4 A Show of Hands…
  5. 5. 5 Agenda •  Spring 3.x in Review •  Themes in Spring 4.0 •  Java EE & SE •  Spring 4 on Java 8 •  Spring 4.1
  6. 6. 6 Spring 3.x in Review
  7. 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. 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. 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. 10 Testing in Spring 3.x •  Embedded databases via <jdbc /> namespace •  @Configuration classes & @ActiveProfiles •  @WebAppConfiguration •  @ContextHierarchy •  Spring MVC Test framework
  11. 11. 11 Annotated Components
  12. 12. 12 Configuration Classes
  13. 13. 13 Composable Stereotypes •  Combining meta-annotations on a custom stereotype •  Automatically detected: no configuration necessary!
  14. 14. 14 Spring 4.0 Themes
  15. 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. 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. 17 Third Party Libraries •  Minimum versions ~ mid 2010 now •  For example –  Hibernate 3.6+ –  Quartz 1.8+ –  Ehcache 2.1+
  18. 18. 18 Java 8 Language and API Features •  Lambda expressions •  Method references •  JSR-310 Date and Time •  Repeatable annotations •  Parameter name discovery
  19. 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. 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. 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. 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. 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. 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. 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. 26 Lazy Bean Resolution Proxies •  @Autowired @Lazy on injection point •  Alternative to: –  Spring’s ObjectFactory –  JSR-330’s Provider<MyTargetType>
  27. 27. 27 Ordered Injection of Lists & Arrays •  Ordered / @Order on candidate beans •  Relative order within specific injection result
  28. 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. 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. 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. 31 spring-messaging •  New org.springframework.messaging module •  Extracted from Spring Integration •  Core message and channel abstractions
  32. 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. 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. 34 AsyncRestTemplate •  Analogous to existing RestTemplate •  Based on ListenableFuture return values •  Custom listeners implement ListenableFutureCallback
  35. 35. 35 Spring + Java SE & Java EE
  36. 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. 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. 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. 39. 39 Java 8 Programming Model
  40. 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. 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. 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. 43 Lambda + Spring = Natural Fit Many Spring APIs are candidates for lambdas –  simply by following the lambda interface conventions
  44. 44. 44 Lambdas with JmsTemplate MessageCreator Message createMessage(Session session) throws JMSException
  45. 45. 45 Lambdas with TransactionTemplate TransactionCallback Object doInTransaction(TransactionStatus status)
  46. 46. 46 Lambdas with JdbcTemplate RowMapper Object mapRow(ResultSet rs, int rowNum) throws SQLException
  47. 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. 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. 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. 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. 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. 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. 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. 54. 54 Spring Framework 4.1
  55. 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. 56 Spring MVC and Messaging •  GroovyWebApplicationContext (SPR-11371) •  Static resource handling in Spring MVC (SPR-10933) •  WebSocket scope (SPR-11305)
  57. 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. 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. 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. 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. 61 Caching Annotation Comparison Spring JCache @Cacheable @CacheResult @CachePut @CachePut @CacheEvict @CacheRemove @CacheEvict(allEntries=true) @CacheRemoveAll
  62. 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. 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. 64 Ex: @JmsListener @Service public class MyService { @JmsListener(destination = "myQueue") public void process(String msg) { // process incoming message } }
  65. 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. 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. 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. 68 Spring Framework 4.1 Roadmap •  4.1 RC1: June 2014 •  4.1 RC2: July 2014 •  4.1 GA: September 2014
  69. 69. 69 In Closing…
  70. 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. 71 Acknowledgements Thanks to Jürgen Höller and Stéphane Nicoll for permitting reuse of some of their content.
  72. 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. 73 Blogs •  Swiftmind Blog –  http://www.swiftmind.com/blog •  Spring Blog –  http://spring.io/blog
  74. 74. 74 Q & A Sam Brannen twitter: @sam_brannen www.slideshare.net/sbrannen www.swiftmind.com

×