Spring 3.1 in a Nutshell
  Sam Brannen / Swiftmind
Speaker Profile


•    Spring & Java consultant @ Swiftmind
•    Developing Java for over 13 years
•    Spring Framework Core Developer
•    Spring Trainer
•    Lead author of “Spring in a Nutshell”
Agenda
•    Major Themes in 3.x
•    Environment and Profiles
•    Java-based Configuration
•    Testing
•    Caching
•    MVC and REST
•    Servlet 3.0
•    Odds & Ends
Major Themes in Spring 3.0
Java-based configuration
custom stereotypes
annotated factory methods
JSR-330 – DI for Java
Spring Expression Language
REST support in Spring MVC
Portlet API 2.0
JSR-303 – bean validation
Java EE 6 support: JPA 2.0, JSF 2.0
Major Themes in Spring 3.1

–  Environment abstraction
–  Java-based application configuration
–  @Configuration class test support
–  High-level cache API
–  Customizable @MVC processing
–  Flash maps and redirect attributes
–  Explicit support for Servlet 3.0
Environment and Profiles
Environment Abstraction
–  Injectable environment abstraction API
     •  org.springframework.core.env.Environment


–  Two core concepts
     •  Property Sources
     •  Bean Profiles

Property Source:                 Bean Profile:

A variety of sources: property   A logical group of bean
files, system properties,        definitions. Registered only if
servlet context, JNDI, etc.      the profile is active.
Property Source Abstraction

–  Property source

–  Property resolution

–  Placeholders
PropertySource(s)

–  PropertySource
  •  a single property source


–  PropertySources
  •  a hierarchy of PropertySource objects
  •  potentially varying across deployment environments
Property Resolution SPI

–  org.springframework.core.env.PropertyResolver

–  Environment extends PropertyResolver
Custom resolution of
          placeholders
–  dependent on the actual environment

–  PropertySourcesPlaceholderConfigurer
   supersedes PropertyPlaceholderConfigurer
Managing Property Sources

–  Stand-alone code




–  Web application
  •  Implement ApplicationContextInitializer
  •  Register via contextInitializerClasses context
     parameter in web.xml
Accessing Properties

–  By injecting the Environment
Bean Definition Profiles

–  Logical grouping of bean definitions
  •  for activation in specific environments
  •  e.g., dev, staging, prod
  •  possibly different deployment platforms


–  Configuration
  •  XML via <beans profile=“…”>
  •  Java-based configuration via @Profile
Configuring Profiles in XML
–  All bean definitions




–  Subset of bean definitions
Configuring Profiles in Java
           Config




                                               25


–  @Profile can also be used on components
  •  @Component, @Service, @Repository, etc.
Profile Activation Options

–  programmatically

–  system property

–  in web.xml

–  in tests via @ActiveProfiles
Activating Profiles…
 programmatically
Activating Profiles…
      via system properties

-Dspring.profiles.active=“dev”

-Dspring.profiles.default=“common”
Activating Profiles…
    in web apps
Activating Profiles…
 in integration tests
Java-based Configuration
Java Config ~= XML

–  XML namespaces à @Enable*
–  FactoryBeans à builders
–  GenericXmlContextLoader à
   AnnotationConfigContextLoader

–  Not a one-to-one mapping
  •  Make the most of what Java has to offer
  •  Intuitive annotation-oriented container configuration
Typical Infrastructure Setup

–  Transactions

–  Scheduling

–  MVC customization

–  AOP
@Enable* Annotations

–  Applied at the class-level on @Configuration
   classes

–  Roughly equivalent to their XML namespace
   counterparts
@Enable* in 3.1 RC1

–  @EnableTransactionManagement
–  @EnableAsync
–  @EnableScheduling
–  @EnableAspectJAutoProxy
–  @EnableLoadTimeWeaving
–  @EnableWebMvc
Hibernate and JPA

–  Hibernate LocalSessionFactoryBuilder API
  •  Hibernate 4 replacement for both
     LocalSessionFactoryBean and
     AnnotationSessionFactoryBean


–  XML-free JPA configuration
  •  LocalContainerEntityManagerFactoryBean has a
     new property
  •  packagesToScan: analogous to
     AnnotationSessionFactoryBean
Java Configuration Example


                 Actually:
                 LocalSessionFactoryBuilder
New Testing Features in 3.1

–  @Configuration class support
–  Environment profile support
–  SmartContextLoader
–  AnnotationConfigContextLoader
–  DelegatingSmartContextLoader
–  Updated context cache key generation
SmartContextLoader SPI

–  Supersedes ContextLoader
–  Strategy for loading application contexts
–  From @Configuration classes or resource
   locations
–  Supports environment profiles
@ContextConfiguration

accepts a new `classes` attribute...
Ex: @Configuration Test #1
Ex: @Configuration Test #2
Caching
Caching Abstraction

–  Declarative caching for Spring applications
  •  Minimal impact on code
  •  Plug in various caching solutions

–  Key annotations @Cacheable and
   @CacheEvict
Cache Key

–  All method arguments used by default




–  Use SpEL to select more specifically (use class,
   method, or argument name)
Conditional Caching
Cache Providers (1/2)

–  Cache and CacheManager SPI
  •  org.springframework.cache


–  Cache Implementations
  •  EhCacheCache
  •  ConcurrentMapCache and
     ConcurrentMapCacheFactoryBean
Cache Providers (2/2)

–  CacheManager Implementations
  •  EhCacheCacheManager
  •  ConcurrentMapCacheManager
  •  SimpleCacheManager
  •  NoOpCacheManager


–  Any other implementation can be plugged in
  •  GemFire, Coherence, etc.
Cache Configuration

–  Cache namespace
  •  <cache:annotation-driven />
  •  “cacheManager” bean
MVC and REST
@MVC 3.0 Config
–  Built-in defaults
   •  Based on DispatcherServlet.properties

–  Spring MVC namespace
   •  <mvc:annotation:driven>, <mvc:interceptors>, …
Java-based @MVC 3.1 Config

–  Most Spring MVC configuration is in Java
   already
  •  @Controller, @RequestMapping, etc.

–  Servlet 3.0 enhancements will further reduce
   the need for web.xml

–  XML namespace is convenient but …
  •  Not transparent
  •  Not easy to offer the right degree of customization
@EnableWebMvc

–  Enables Spring MVC default configuration
  •  Registers components expected by the
     DispatcherServlet




–  Allows for configuration similar to the
   Spring MVC namespace
  •  … and the DispatcherServlet.properties combined
A More Complete Example …
–  Add component scanning for @Controllers
   and other beans
Q: Where is the “Enabled”
      Configuration ?!
–  A: a framework-provided @Configuration class
   (actually DelegatingWebMvcConfiguration)
How Do I Customize All This?
–  Simply implement the WebMvcConfigurer
   interface
                               Allows selective overriding
HandlerMethod Abstraction
–  HandlerMethod
    •  A proper abstraction for the selected “handler” in Spring
       MVC

–  Not just for @RequestMapping methods
    •  Also @InitBinder, @ModelAttribute, @ExceptionHandler
       methods

–  “HandlerMethod” support classes
    •  RequestMappingHandlerMapping
    •  RequestMappingHandlerAdapter
    •  ExceptionHandlerExceptionResolver
Path Variables in the Model

–  @PathVariable arguments automatically
   added to the model




                             These can be deleted
URI Templates in Redirect
          Strings
–  URL templates supported in “redirect:”
   strings




                 Expanded from model attributes,
                which now include @PathVariables
URI Template Variables in
        Data Binding
–  URI template variables used in data binding
Matching MediaTypes < @MVC 3.1

  –  Using the 'headers' condition
Matching MediaTypes in @MVC 3.1

  –  The 'consumes' and 'produces' conditions



                   If not matched, results in:
                   UNSUPPORTED_MEDIA_TYPE (415)




                          If not matched, results in:
                          NOT_ACCEPTABLE (406)
Servlet 3.0
Servlet 3.0 Containers

•  Tomcat 7 and GlassFish 3
  –  Explicitly supported

•  While preserving compatibility with Servlet
   2.4+
XML-free Web-app Config

•  Support for XML-free web application setup
  –  no web.xml


•  Made possible via:
  –  Servlet 3.0's ServletContainerInitializer
  –  Spring 3.1's
     AnnotationConfigWebApplicationContext
  –  Spring 3.1’s environment abstraction
Native Servlet 3.0 in @MVC

•  Asynchronous request processing

•  Standard Servlet 3.0 file upload
  –  behind Spring's MultipartResolver abstraction
Odds & Ends
"c:" Namespace

–  Shortcut for <constructor-arg>
  •  inline argument values
  •  analogous to existing "p:" namespace
–  Use of constructor argument names
  •  recommended for readability
  •  debug symbols have to be available in the
     application's class files
The Spring Roadmap

•  Spring 3.1 RC2: mid November

•  Spring 3.1 GA:     Before end of 2011

•  Spring 3.2:        Planned for early 2012
  –  Java EE: JSF 2.2, JPA 2.1, etc.
Spring 3.1 in a Nutshell

•    Environment and Profiles
•    Java-based Configuration and @Enable*
•    Testing with @Configuration and Profiles
•    Cache Abstraction
•    MVC and REST Improvements
•    Servlet 3.0
•    c: Namespace
Further Resources

•  Spring Framework
  –  http://springframework.org
  –  Spring Reference Manual
  –  JavaDoc
•  Spring Forums
  –  http://forum.springframework.org
•  Spring JIRA
  –  http://jira.springframework.org
Blogs

•  SpringSource Team Blog – category 3.1
  –  http://blog.springsource.com/category/spring/31/


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


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



“Spring in a Nutshell”
http://oreilly.com/catalog/9780596801946
available from O’Reilly in 2012

Spring 3.1 in a Nutshell - JAX London 2011

  • 1.
    Spring 3.1 ina Nutshell Sam Brannen / Swiftmind
  • 2.
    Speaker Profile •  Spring & Java consultant @ Swiftmind •  Developing Java for over 13 years •  Spring Framework Core Developer •  Spring Trainer •  Lead author of “Spring in a Nutshell”
  • 3.
    Agenda •  Major Themes in 3.x •  Environment and Profiles •  Java-based Configuration •  Testing •  Caching •  MVC and REST •  Servlet 3.0 •  Odds & Ends
  • 4.
    Major Themes inSpring 3.0
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
    REST support inSpring MVC
  • 11.
  • 12.
    JSR-303 – beanvalidation
  • 13.
    Java EE 6support: JPA 2.0, JSF 2.0
  • 14.
    Major Themes inSpring 3.1 –  Environment abstraction –  Java-based application configuration –  @Configuration class test support –  High-level cache API –  Customizable @MVC processing –  Flash maps and redirect attributes –  Explicit support for Servlet 3.0
  • 15.
  • 16.
    Environment Abstraction –  Injectableenvironment abstraction API •  org.springframework.core.env.Environment –  Two core concepts •  Property Sources •  Bean Profiles Property Source: Bean Profile: A variety of sources: property A logical group of bean files, system properties, definitions. Registered only if servlet context, JNDI, etc. the profile is active.
  • 17.
    Property Source Abstraction – Property source –  Property resolution –  Placeholders
  • 18.
    PropertySource(s) –  PropertySource •  a single property source –  PropertySources •  a hierarchy of PropertySource objects •  potentially varying across deployment environments
  • 19.
    Property Resolution SPI – org.springframework.core.env.PropertyResolver –  Environment extends PropertyResolver
  • 20.
    Custom resolution of placeholders –  dependent on the actual environment –  PropertySourcesPlaceholderConfigurer supersedes PropertyPlaceholderConfigurer
  • 21.
    Managing Property Sources – Stand-alone code –  Web application •  Implement ApplicationContextInitializer •  Register via contextInitializerClasses context parameter in web.xml
  • 22.
    Accessing Properties –  Byinjecting the Environment
  • 23.
    Bean Definition Profiles – Logical grouping of bean definitions •  for activation in specific environments •  e.g., dev, staging, prod •  possibly different deployment platforms –  Configuration •  XML via <beans profile=“…”> •  Java-based configuration via @Profile
  • 24.
    Configuring Profiles inXML –  All bean definitions –  Subset of bean definitions
  • 25.
    Configuring Profiles inJava Config 25 –  @Profile can also be used on components •  @Component, @Service, @Repository, etc.
  • 26.
    Profile Activation Options – programmatically –  system property –  in web.xml –  in tests via @ActiveProfiles
  • 27.
  • 28.
    Activating Profiles… via system properties -Dspring.profiles.active=“dev” -Dspring.profiles.default=“common”
  • 29.
  • 30.
    Activating Profiles… inintegration tests
  • 31.
  • 32.
    Java Config ~=XML –  XML namespaces à @Enable* –  FactoryBeans à builders –  GenericXmlContextLoader à AnnotationConfigContextLoader –  Not a one-to-one mapping •  Make the most of what Java has to offer •  Intuitive annotation-oriented container configuration
  • 33.
    Typical Infrastructure Setup – Transactions –  Scheduling –  MVC customization –  AOP
  • 34.
    @Enable* Annotations –  Appliedat the class-level on @Configuration classes –  Roughly equivalent to their XML namespace counterparts
  • 35.
    @Enable* in 3.1RC1 –  @EnableTransactionManagement –  @EnableAsync –  @EnableScheduling –  @EnableAspectJAutoProxy –  @EnableLoadTimeWeaving –  @EnableWebMvc
  • 36.
    Hibernate and JPA – Hibernate LocalSessionFactoryBuilder API •  Hibernate 4 replacement for both LocalSessionFactoryBean and AnnotationSessionFactoryBean –  XML-free JPA configuration •  LocalContainerEntityManagerFactoryBean has a new property •  packagesToScan: analogous to AnnotationSessionFactoryBean
  • 37.
    Java Configuration Example Actually: LocalSessionFactoryBuilder
  • 38.
    New Testing Featuresin 3.1 –  @Configuration class support –  Environment profile support –  SmartContextLoader –  AnnotationConfigContextLoader –  DelegatingSmartContextLoader –  Updated context cache key generation
  • 39.
    SmartContextLoader SPI –  SupersedesContextLoader –  Strategy for loading application contexts –  From @Configuration classes or resource locations –  Supports environment profiles
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
    Caching Abstraction –  Declarativecaching for Spring applications •  Minimal impact on code •  Plug in various caching solutions –  Key annotations @Cacheable and @CacheEvict
  • 45.
    Cache Key –  Allmethod arguments used by default –  Use SpEL to select more specifically (use class, method, or argument name)
  • 46.
  • 47.
    Cache Providers (1/2) – Cache and CacheManager SPI •  org.springframework.cache –  Cache Implementations •  EhCacheCache •  ConcurrentMapCache and ConcurrentMapCacheFactoryBean
  • 48.
    Cache Providers (2/2) – CacheManager Implementations •  EhCacheCacheManager •  ConcurrentMapCacheManager •  SimpleCacheManager •  NoOpCacheManager –  Any other implementation can be plugged in •  GemFire, Coherence, etc.
  • 49.
    Cache Configuration –  Cachenamespace •  <cache:annotation-driven /> •  “cacheManager” bean
  • 50.
  • 51.
    @MVC 3.0 Config – Built-in defaults •  Based on DispatcherServlet.properties –  Spring MVC namespace •  <mvc:annotation:driven>, <mvc:interceptors>, …
  • 52.
    Java-based @MVC 3.1Config –  Most Spring MVC configuration is in Java already •  @Controller, @RequestMapping, etc. –  Servlet 3.0 enhancements will further reduce the need for web.xml –  XML namespace is convenient but … •  Not transparent •  Not easy to offer the right degree of customization
  • 53.
    @EnableWebMvc –  Enables SpringMVC default configuration •  Registers components expected by the DispatcherServlet –  Allows for configuration similar to the Spring MVC namespace •  … and the DispatcherServlet.properties combined
  • 54.
    A More CompleteExample … –  Add component scanning for @Controllers and other beans
  • 55.
    Q: Where isthe “Enabled” Configuration ?! –  A: a framework-provided @Configuration class (actually DelegatingWebMvcConfiguration)
  • 56.
    How Do ICustomize All This? –  Simply implement the WebMvcConfigurer interface Allows selective overriding
  • 57.
    HandlerMethod Abstraction –  HandlerMethod •  A proper abstraction for the selected “handler” in Spring MVC –  Not just for @RequestMapping methods •  Also @InitBinder, @ModelAttribute, @ExceptionHandler methods –  “HandlerMethod” support classes •  RequestMappingHandlerMapping •  RequestMappingHandlerAdapter •  ExceptionHandlerExceptionResolver
  • 58.
    Path Variables inthe Model –  @PathVariable arguments automatically added to the model These can be deleted
  • 59.
    URI Templates inRedirect Strings –  URL templates supported in “redirect:” strings Expanded from model attributes, which now include @PathVariables
  • 60.
    URI Template Variablesin Data Binding –  URI template variables used in data binding
  • 61.
    Matching MediaTypes <@MVC 3.1 –  Using the 'headers' condition
  • 62.
    Matching MediaTypes in@MVC 3.1 –  The 'consumes' and 'produces' conditions If not matched, results in: UNSUPPORTED_MEDIA_TYPE (415) If not matched, results in: NOT_ACCEPTABLE (406)
  • 63.
  • 64.
    Servlet 3.0 Containers • Tomcat 7 and GlassFish 3 –  Explicitly supported •  While preserving compatibility with Servlet 2.4+
  • 65.
    XML-free Web-app Config • Support for XML-free web application setup –  no web.xml •  Made possible via: –  Servlet 3.0's ServletContainerInitializer –  Spring 3.1's AnnotationConfigWebApplicationContext –  Spring 3.1’s environment abstraction
  • 66.
    Native Servlet 3.0in @MVC •  Asynchronous request processing •  Standard Servlet 3.0 file upload –  behind Spring's MultipartResolver abstraction
  • 67.
  • 68.
    "c:" Namespace –  Shortcutfor <constructor-arg> •  inline argument values •  analogous to existing "p:" namespace –  Use of constructor argument names •  recommended for readability •  debug symbols have to be available in the application's class files
  • 69.
    The Spring Roadmap • Spring 3.1 RC2: mid November •  Spring 3.1 GA: Before end of 2011 •  Spring 3.2: Planned for early 2012 –  Java EE: JSF 2.2, JPA 2.1, etc.
  • 70.
    Spring 3.1 ina Nutshell •  Environment and Profiles •  Java-based Configuration and @Enable* •  Testing with @Configuration and Profiles •  Cache Abstraction •  MVC and REST Improvements •  Servlet 3.0 •  c: Namespace
  • 71.
    Further Resources •  SpringFramework –  http://springframework.org –  Spring Reference Manual –  JavaDoc •  Spring Forums –  http://forum.springframework.org •  Spring JIRA –  http://jira.springframework.org
  • 72.
    Blogs •  SpringSource TeamBlog – category 3.1 –  http://blog.springsource.com/category/spring/31/ •  Swiftmind Blog –  http://www.swiftmind.com/blog/
  • 73.
    Q&A Sam Brannen twitter: @sam_brannen Swiftmind www.slideshare.net/sbrannen www.swiftmind.com “Spring in a Nutshell” http://oreilly.com/catalog/9780596801946 available from O’Reilly in 2012