Spring 3.1, 3.2, and 3.3 Update
                                                                                             Josh Long
                                                                                             Spring Developer Advocate, SpringSource, a Division of VMWare
                                                                                             http://www.joshlong.com || @starbuxman || josh.long@springsource.com




            © 2012 SpringOne 2GX 2012. All rights reserved. Do not distribute without permission.

Thursday, January 24, 13
About Josh Long (龙之春)
      Spring Developer Advocate
      twitter: @starbuxman
      weibo: @springsource
      josh.long@springsource.com




                                   2

Thursday, January 24, 13
About Josh Long
       Spring Developer Advocate
       twitter: @starbuxman
       josh.long@springsource.com

       Contributor To:

       •Spring Integration
       •Spring Batch
       •Spring Hadoop
       •Activiti Workflow Engine
       •Akka Actor engine




      3
Thursday, January 24, 13
Why Are We Here?




                           4

Thursday, January 24, 13
Why Are We Here?




                           “   Software entities (classes,
                               modules, functions, etc.) should
                               be open for extension, but closed
                               for modification.
                                                                   ”
                                                  -Bob Martin




      5
Thursday, January 24, 13
Why Are We Here?



                           do NOT reinvent
                           the Wheel!




                                             6

Thursday, January 24, 13
Spring’s aim:
       bring simplicity to java development

                                                                                          data
                             web tier
                                                           batch     integration &       access
                               &         service tier                                                mobile           Security
                                                        processing    messaging        / NoSQL /
                              RIA
                                                                                       Big Data



                                                          The Spring framework
                           the cloud:                         lightweight                          traditional

                                    CloudFoundry                           tc Server                       WebSphere
                                  Google App Engine                         Tomcat                          JBoss AS
                                  Amazon BeanStalk                            Jetty                        WebLogic
                                                                                                      (on legacy versions, too!)




                                                                                                                                   7

Thursday, January 24, 13
The Spring Framework


                                            Framework      Description

                                           Spring Core     The foundation

                                         Spring @MVC       the web leading framework (comes with the core framework)

                                         Spring Security   Extensible framework providing authentication, authorization

                                        Spring Webflow     An excellent web framework for building multi-page flows

                                   Spring Web Services     Contract-first, document–centric SOAP and XML web services

                                           Spring Batch    Powerful batch processing framework

                                      Spring Integration   Implements enterprise integration patterns

                                        Spring BlazeDS     Support for Adobe BlazeDS

                                          Spring AMQP      interface with AMQP message brokers, like RabbitMQ

                                            Spring Data    NoSQL options: MongoDB, Redis, Riak, CouchDB, Neo4J, etc.

                                           Spring Social   integrate Twitter, Facebook, Tripit, MySpace, LinkedIn, etc.
                                                           Provides a POJO-centric approach to building
                                         Spring Hadoop
                                                           Hadoop applications. Supports HBase, others
                                                           provides first-class support for service
                           Spring Mobile, Spring Android
                                                           creation and consumption for iPhone, Android
                                        Spring GemFire     Provides the easiest interface for the GemFire enterprise data grid technology




                                                                                                                                            8

Thursday, January 24, 13
Wide Variety of Data and Data Stores
      § Not all data resides in relational databases
             l   cloud environments often suggest alternatives for scalability reasons
             l   HBase, Redis, Mongo, etc


      § Distributed caches add challenges as well
             l   not least of it all in terms of application-level access patterns
             l   GemFire, Coherence, etc

      § Hardly any standardization available
             l   JSR-107 – for caching – did not make progress for a long, long time
             l   finally getting picked up in Java EE 7, but again only for caching
             l   alternative datastore space is too diverse for standardization




Thursday, January 24, 13
Wide Variety of Web Clients
      § More and more client-side web technologies
             l   HTML 5 as a next-generation browser standard


      § Server-side state to be minimized or even removed completely
             l   in particular: no server-side user interface state
             l   strictly controlled user session state

      § JSF's state-centric approach not a great fit anymore
             l   except for special kinds of applications (which it remains very useful for)
             l   web application backends and web services based on JAX-RS / MVC style
             l   nevertheless: JSF keeps evolving – JSF 2.2 coming up in 2012




                                                                                                10


Thursday, January 24, 13
Current and Upcoming: 3.1, 3.2, and 3.2

      § Spring Framework 3.1 (Dec 2011)
         • Environment profiles, Java-based configuration, declarative caching
         • Initial Java 7 support, Servlet 3.0 based deployment
      § Spring Framework 3.2 (Dec 2012)
         • Gradle-based build, GitHub-based contribution model
         • Fully Java 7 oriented, async MVC processing on Servlet 3.0
      § Spring Framework 3.3 (Q4 2013)
         • Comprehensive Java SE 8 support (including lambda expressions)
            • Single abstract method types in Spring are well positioned
         • Support for Java EE 7 API level and WebSockets




                                                                                 11

Thursday, January 24, 13
Spring 3.1




                           12

Thursday, January 24, 13
Current and Upcoming: 3.1, 3.2, and 3.2

      § Spring Framework 3.1 (Dec 2011)
         • Environment profiles, Java-based configuration, declarative caching
         • Initial Java 7 support, Servlet 3.0 based deployment
      § Spring Framework 3.2 (Dec 2012)
         • Gradle-based build, GitHub-based contribution model
         • Fully Java 7 oriented, async MVC processing on Servlet 3.0
      § Spring Framework 3.3 (Q4 2013)
         • Comprehensive Java SE 8 support (including lambda expressions)
            • Single abstract method types in Spring are well positioned
         • Support for Java EE 7 API level and WebSockets




                                                                                 13

Thursday, January 24, 13
Spring Framework 3.1: Selected Features
      § Environment abstraction and profiles
      § Java-based application configuration
      § Overhaul of the test context framework

      § Cache abstraction & declarative caching
      § Servlet 3.0 based web applications
      § @MVC processing & flash attributes

      § Refined JPA support
      § Hibernate 4.0 & Quartz 2.0
      § Support for Java SE 7




                                                   14


Thursday, January 24, 13
Environment Abstraction




                                15


Thursday, January 24, 13
Environment Abstraction
      § Grouping bean definitions for activation in specific environments
         • e.g. development, testing, production
         • possibly different deployment environments
      § Custom resolution of placeholders
         • dependent on the actual environment
         • hierarchy of property sources




                                                                             15


Thursday, January 24, 13
Environment Abstraction
      § Grouping bean definitions for activation in specific environments
         • e.g. development, testing, production
         • possibly different deployment environments
      § Custom resolution of placeholders
         • dependent on the actual environment
         • hierarchy of property sources




                                                                             15


Thursday, January 24, 13
Environment Abstraction
      § Grouping bean definitions for activation in specific environments
         • e.g. development, testing, production
         • possibly different deployment environments
      § Custom resolution of placeholders
         • dependent on the actual environment
         • hierarchy of property sources

      § Injectable environment abstraction API
         • org.springframework.core.env.Environment




                                                                             15


Thursday, January 24, 13
Environment Abstraction
      § Grouping bean definitions for activation in specific environments
         • e.g. development, testing, production
         • possibly different deployment environments
      § Custom resolution of placeholders
         • dependent on the actual environment
         • hierarchy of property sources

      § Injectable environment abstraction API
         • org.springframework.core.env.Environment
      § Unified property resolution SPI
         • org.springframework.core.env.PropertyResolver




                                                                             15


Thursday, January 24, 13
Bean Definition Profiles
      <beans profile="production">
        <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
           destroy-method="close">
        	 <property name="driverClass" value="${database.driver}"/>
        	 <property name="jdbcUrl" value="${database.url}"/>
        	 <property name="username" value="${database.username}"/>
        	 <property name="password" value="${database.password}"/>
        </bean>
      </beans>


      <beans profile="embedded">
        <jdbc:embedded-database id="dataSource" type="H2">
           <jdbc:script location="/WEB-INF/database/schema-member.sql"/>
           <jdbc:script location="/WEB-INF/database/schema-activity.sql"/>
           <jdbc:script location="/WEB-INF/database/schema-event.sql"/>
           <jdbc:script location="/WEB-INF/database/data.sql"/>
        </jdbc:embedded-database>
      </beans>




                                                                                16


Thursday, January 24, 13
Environment Configuration




                                  17


Thursday, January 24, 13
Environment Configuration
      § Associating specific bean definitions with specific environments
         • XML 'profile' attribute on <beans> element
         • @Profile annotation on configuration classes
         • @Profile annotation on individual component classes




                                                                            17


Thursday, January 24, 13
Environment Configuration
      § Associating specific bean definitions with specific environments
         • XML 'profile' attribute on <beans> element
         • @Profile annotation on configuration classes
         • @Profile annotation on individual component classes

      § Activating specific profiles by name
         • e.g. through a system property
            • -Dspring.profiles.active=development
         • or other means outside of the deployment unit
            • according to environment conventions




                                                                            17


Thursday, January 24, 13
Environment Configuration
      § Associating specific bean definitions with specific environments
         • XML 'profile' attribute on <beans> element
         • @Profile annotation on configuration classes
         • @Profile annotation on individual component classes

      § Activating specific profiles by name
         • e.g. through a system property
            • -Dspring.profiles.active=development
         • or other means outside of the deployment unit
            • according to environment conventions




                                                                            17


Thursday, January 24, 13
Environment Configuration
      § Associating specific bean definitions with specific environments
         • XML 'profile' attribute on <beans> element
         • @Profile annotation on configuration classes
         • @Profile annotation on individual component classes

      § Activating specific profiles by name
         • e.g. through a system property
            • -Dspring.profiles.active=development
         • or other means outside of the deployment unit
            • according to environment conventions


      § Ideally: no need to touch deployment unit across different stages/environments




                                                                                          17


Thursday, January 24, 13
Java-Based Application Configuration




                                             18


Thursday, January 24, 13
Java-Based Application Configuration
      § Application-specific container configuration
         • aligned with Spring 3.0's @Configuration style
         • focus on customizing the annotation-based processing parts of Spring




                                                                                  18


Thursday, January 24, 13
Java-Based Application Configuration
      § Application-specific container configuration
         • aligned with Spring 3.0's @Configuration style
         • focus on customizing the annotation-based processing parts of Spring

      § Equivalent to XML namespace functionality
         • but not a one-to-one mapping
         • 'natural' container configuration from an annotation-oriented perspective




                                                                                       18


Thursday, January 24, 13
Java-Based Application Configuration
      § Application-specific container configuration
         • aligned with Spring 3.0's @Configuration style
         • focus on customizing the annotation-based processing parts of Spring

      § Equivalent to XML namespace functionality
         • but not a one-to-one mapping
         • 'natural' container configuration from an annotation-oriented perspective




                                                                                       18


Thursday, January 24, 13
Java-Based Application Configuration
      § Application-specific container configuration
         • aligned with Spring 3.0's @Configuration style
         • focus on customizing the annotation-based processing parts of Spring

      § Equivalent to XML namespace functionality
         • but not a one-to-one mapping
         • 'natural' container configuration from an annotation-oriented perspective

      § Typical infrastructure setup
         • transactions
         • scheduling
         • MVC customization




                                                                                       18


Thursday, January 24, 13
So, What’s All of This Look Like in Code?




                                        Not confidential. Tell everyone.   19


Thursday, January 24, 13
I want Database Access ... with Hibernate 4 Support

          @Service
          public class CustomerService {

              public Customer getCustomerById( long customerId)          {
                ...
              }

               public Customer createCustomer( String firstName, String lastName, Date date){
                 ...
              }

          }




                                                    Not confidential. Tell everyone.           20


Thursday, January 24, 13
I want Database Access ... with Hibernate 4 Support

          @Service
          public class CustomerService {

              @Inject
              private SessionFactory sessionFactory;

              public Customer createCustomer(String firstName,
                                            String lastName,
                                            Date signupDate) {
                Customer customer = new Customer();
                customer.setFirstName(firstName);
                customer.setLastName(lastName);
                customer.setSignupDate(signupDate);

                  sessionFactory.getCurrentSession().save(customer);
                  return customer;
              }

          }




                                                  Not confidential. Tell everyone.   21


Thursday, January 24, 13
I want Database Access ... with Hibernate 4 Support

          @Service
          public class CustomerService {

              @Inject
              private SessionFactory sessionFactory;

              @Transactional
              public Customer createCustomer(String firstName,
                                            String lastName,
                                            Date signupDate) {
                Customer customer = new Customer();
                customer.setFirstName(firstName);
                customer.setLastName(lastName);
                customer.setSignupDate(signupDate);

                  sessionFactory.getCurrentSession().save(customer);
                  return customer;
              }

          }




                                                       Not confidential. Tell everyone.   22


Thursday, January 24, 13
I want Declarative Cache Management...

          @Service
          public class CustomerService {

              @Inject
              private SessionFactory sessionFactory;

              @Transactional(readOnly = true)
              @Cacheable(“customers”)
              public Customer getCustomerById( long customerId)             {
                ...
              }

              ...

          }




                                                       Not confidential. Tell everyone.   23


Thursday, January 24, 13
I want a RESTful Endpoint...

          package org.springsource.examples.spring31.web;
          ..

          @Controller
          public class CustomerController {

              @Inject
              private CustomerService customerService;

              @RequestMapping(value = "/customer/{id}" )
              @ResponseBody
              public Customer customerById( @PathVariable("id") Integer id ) {
                  return customerService.getCustomerById(id);
              }
               ...
          }




                                                    Not confidential. Tell everyone.   24


Thursday, January 24, 13
...But Where’d the SessionFactory come from?




                                     Not confidential. Tell everyone.   25


Thursday, January 24, 13
The Spring ApplicationContext

      § Spring Manages the beans you tell it to manage (Implicitly, Explicitly)
         • use annotations (JSR 250, JSR 330, native)
         • XML
         • Java configuration
         • component scanning


      § You can of course use all of them! Mix ‘n match

      § All configuration styles tell the ApplicationContext how to manage your beans




                                                                                         26

Thursday, January 24, 13
The Spring ApplicationContext

      § Annotations (component-scanning)
         • best when you want Spring to sort it all out in the wash, no need for explicit configuration
      § Java Configuration
         • type-safe, and explicit - all configuration is centralized. Provides a good birds-eye view of your application
      § XML
         • explicit - namespaces still provide the most punch in a lot of cases
      § All together
         • use Java configuration for your regular third party beans (like a DataSource)
         • XML namespaces for DSLs and higher level functionality (Spring Integration, Batch, etc.)
         • annotations for your components (a @Service, or a Spring MVC @Controller)




                                                                                                                            27

Thursday, January 24, 13
The Spring ApplicationContext


                           From XML:
                           public class Main {
                             public static void main(String [] args) throws Throwable {
                               ApplicationContext ctx =
                                new ClassPathXmlApplication( “my-config.xml” );
                               CustomerService serviceReference = ctx.getBean( CustomerService.class );
                               Customer customer = serviceReference.createCustomer( "Juergen", "Hoeller");
                             }
                           }




                                                                                                             28

Thursday, January 24, 13
The Spring ApplicationContext


                           From XML:
                           public class Main {
                             public static void main(String [] args) throws Throwable {
                               ApplicationContext ctx =
                                new ClassPathXmlApplication( “my-config.xml” );
                               CustomerService serviceReference = ctx.getBean( CustomerService.class );
                               Customer customer = serviceReference.createCustomer( "Juergen", "Hoeller");
                             }
                           }



                           From Java Configuration
                           public class Main {
                             public static void main(String [] args) throws Throwable {
                               ApplicationContext ctx =
                                new AnnotationConfigApplicationContext( ServicesConfiguration.class );
                               CustomerService serviceReference = ctx.getBean( CustomerService.class );
                               Customer customer = serviceReference.createCustomer( "Juergen", "Hoeller");
                             }
                           }



                                                                                                             28

Thursday, January 24, 13
A Quick Primer on Configuration in Spring 3.1

      ....
     <beans>

      <tx:annotation-driven transaction-manager = "txManager" />

      <context:component-scan base-package = "org.springsource.examples.spring31.services" />

      <context:property-placeholder properties = "config.properties" />

      <bean id = "txManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager">
         <property name = "sessionFactory" ref = "sessionFactory" />
      </bean>

       <bean id = "sessionFactory" class = "org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        ...
       </bean>

       <bean id = "dataSource" class = "..SimpleDriverDataSource">
         <property name= "userName" value = "${ds.user}"/>
          ...
       </bean>

     </beans>




             ApplicationContext ctx =
              new ClassPathXmlApplication( “service-config.xml” );

                                                            Not confidential. Tell everyone.

Thursday, January 24, 13
A Quick Primer on Configuration in Spring 3.1

      ....
     <beans>

      <tx:annotation-driven transaction-manager = "txManager" />

      <context:component-scan base-package = "org.springsource.examples.spring31.services" />

      <context:property-placeholder properties = "config.properties" />

      <bean id = "txManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager">
         <property name = "sessionFactory" ref = "sessionFactory" />
      </bean>

       <bean id = "sessionFactory" class = "org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        ...
       </bean>

       <bean id = "dataSource" class = "..SimpleDriverDataSource">
         <property name= "userName" value = "${ds.user}"/>
          ...
       </bean>

     </beans>




             ApplicationContext ctx =
              new ClassPathXmlApplication( “service-config.xml” );

                                                            Not confidential. Tell everyone.

Thursday, January 24, 13
A Quick Primer on Configuration in Spring 3.1


     @Configuration
     @PropertySource("/config.properties")
     @EnableTransactionManagement
     @ComponentScan(basePackageClasses = {CustomerService.class})
     public class ServicesConfiguration {

         @Inject private Environment environment;

         @Bean
         public PlatformTransactionManager txManager() throws Exception {
           return new HibernateTransactionManager(this.sessionFactory());
         }

         @Bean
         public SessionFactory sessionFactory() { ... }

          @Bean
          public DataSource dataSource(){
            SimpleDriverDataSource sds = new SimpleDriverDataSource();
            sds.setUserName( this.environment.getProperty( “ds.user”));
            // ...
            return sds;
         }

     }




               ApplicationContext ctx =
                new AnnotationConfigApplicationContext( ServicesConfiguration.class );

                                                                   Not confidential. Tell everyone.

Thursday, January 24, 13
A Quick Primer on Configuration in Spring 3.1

      ....
     <beans>

      <tx:annotation-driven transaction-manager = "txManager" />

      <context:component-scan base-package = "org.springsource.examples.spring31.services" />

      <context:property-placeholder properties = "config.properties" />

      <bean id = "txManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager">
         <property name = "sessionFactory" ref = "sessionFactory" />
      </bean>

       <bean id = "sessionFactory" class = "org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        ...
       </bean>

       <bean id = "dataSource" class = "..SimpleDriverDataSource">
         <property name= "userName" value = "${ds.user}"/>
          ...
       </bean>

     </beans>




             ApplicationContext ctx =
              new ClassPathXmlApplication( “service-config.xml” );

                                                            Not confidential. Tell everyone.

Thursday, January 24, 13
A Quick Primer on Configuration in Spring 3.1


     @Configuration
     @PropertySource("/config.properties")
     @EnableTransactionManagement
     @ComponentScan(basePackageClasses = {CustomerService.class})
     public class ServicesConfiguration {

         @Inject private Environment environment;

         @Bean
         public PlatformTransactionManager txManager() throws Exception {
           return new HibernateTransactionManager(this.sessionFactory());
         }

         @Bean
         public SessionFactory sessionFactory() { ... }

          @Bean
          public DataSource dataSource(){
            SimpleDriverDataSource sds = new SimpleDriverDataSource();
            sds.setUserName( this.environment.getProperty( “ds.user”));
            // ...
            return sds;
         }

     }




             ApplicationContext ctx =
              new AnnotationConfigApplicationContext( ServicesConfiguration.class );

                                                                   Not confidential. Tell everyone.

Thursday, January 24, 13
A Quick Primer on Configuration in Spring 3.1

      ....
     <beans>

      <tx:annotation-driven transaction-manager = "txManager" />

      <context:component-scan base-package = "org.springsource.examples.spring31.services" />

      <context:property-placeholder properties = "config.properties" />

      <bean id = "txManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager">
         <property name = "sessionFactory" ref = "sessionFactory" />
      </bean>

       <bean id = "sessionFactory" class = "org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        ...
       </bean>

       <bean id = "dataSource" class = "..SimpleDriverDataSource">
         <property name= "userName" value = "${ds.user}"/>
          ...
       </bean>

     </beans>




             ApplicationContext ctx =
              new ClassPathXmlApplication( “service-config.xml” );

                                                            Not confidential. Tell everyone.

Thursday, January 24, 13
A Quick Primer on Configuration in Spring 3.1


     @Configuration
     @PropertySource("/config.properties")
     @EnableTransactionManagement
     @ComponentScan(basePackageClasses = {CustomerService.class})
     public class ServicesConfiguration {

         @Inject private Environment environment;

         @Bean
         public PlatformTransactionManager txManager() throws Exception {
           return new HibernateTransactionManager(this.sessionFactory());
         }

         @Bean
         public SessionFactory sessionFactory() { ... }

          @Bean
          public DataSource dataSource(){
            SimpleDriverDataSource sds = new SimpleDriverDataSource();
            sds.setUserName( this.environment.getProperty( “ds.user”));
            // ...
            return sds;
         }

     }




             ApplicationContext ctx =
              new AnnotationConfigApplicationContext( ServicesConfiguration.class );

                                                                   Not confidential. Tell everyone.

Thursday, January 24, 13
A Quick Primer on Configuration in Spring 3.1

      ....
     <beans>

      <tx:annotation-driven transaction-manager = "txManager" />

      <context:component-scan base-package = "org.springsource.examples.spring31.services" />

      <context:property-placeholder properties = "config.properties" />

      <bean id = "txManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager">
         <property name = "sessionFactory" ref = "sessionFactory" />
      </bean>

       <bean id = "sessionFactory" class = "org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        ...
       </bean>

       <bean id = "dataSource" class = "..SimpleDriverDataSource">
         <property name= "userName" value = "${ds.user}"/>
          ...
       </bean>

     </beans>




             ApplicationContext ctx =
              new ClassPathXmlApplication( “service-config.xml” );

                                                            Not confidential. Tell everyone.

Thursday, January 24, 13
A Quick Primer on Configuration in Spring 3.1


     @Configuration
     @PropertySource("/config.properties")
     @EnableTransactionManagement
     @ComponentScan(basePackageClasses = {CustomerService.class})
     public class ServicesConfiguration {

         @Inject private Environment environment;

         @Bean
         public PlatformTransactionManager txManager() throws Exception {
           return new HibernateTransactionManager(this.sessionFactory());
         }

         @Bean
         public SessionFactory sessionFactory() { ... }

          @Bean
          public DataSource dataSource(){
            SimpleDriverDataSource sds = new SimpleDriverDataSource();
            sds.setUserName( this.environment.getProperty( “ds.user”));
            // ...
            return sds;
         }

     }




             ApplicationContext ctx =
              new AnnotationConfigApplicationContext( ServicesConfiguration.class );

                                                                 Not confidential. Tell everyone.

Thursday, January 24, 13
A Quick Primer on Configuration in Spring 3.1

      ....
     <beans>

      <tx:annotation-driven transaction-manager = "txManager" />

      <context:component-scan base-package = "org.springsource.examples.spring31.services" />

      <context:property-placeholder properties = "config.properties" />

      <bean id = "txManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager">
         <property name = "sessionFactory" ref = "sessionFactory" />
      </bean>

       <bean id = "sessionFactory" class = "org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        ...
       </bean>

       <bean id = "dataSource" class = "..SimpleDriverDataSource">
         <property name= "userName" value = "${ds.user}"/>
          ...
       </bean>

     </beans>




             ApplicationContext ctx =
              new ClassPathXmlApplication( “service-config.xml” );

                                                            Not confidential. Tell everyone.

Thursday, January 24, 13
A Quick Primer on Configuration in Spring 3.1


     @Configuration
     @PropertySource("/config.properties")
     @EnableTransactionManagement
     @ComponentScan(basePackageClasses = {CustomerService.class})
     public class ServicesConfiguration {

         @Inject private Environment environment;

         @Bean
         public PlatformTransactionManager txManager() throws Exception {
           return new HibernateTransactionManager(this.sessionFactory());
         }

         @Bean
         public SessionFactory sessionFactory() { ... }

          @Bean
          public DataSource dataSource(){
            SimpleDriverDataSource sds = new SimpleDriverDataSource();
            sds.setUserName( this.environment.getProperty( “ds.user”));
            // ...
            return sds;
         }

     }




             ApplicationContext ctx =
              new AnnotationConfigApplicationContext( ServicesConfiguration.class );

                                                                   Not confidential. Tell everyone.

Thursday, January 24, 13
Test Context Framework
      @RunWith(SpringJUnit4ClassRunner.class)
      @ContextConfiguration(
          loader=AnnotationConfigContextLoader.class,
          classes={TransferServiceConfig.class, DataConfig.class})
      @ActiveProfiles("dev")
      public class TransferServiceTest {


          @Autowired
          private TransferService transferService;


          @Test
          public void testTransferService() {
              ...
          }
      }




                                                                   40


Thursday, January 24, 13
"c:" Namespace
      § New XML namespace for use with bean configuration
         • 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


         <bean class="…" c:age="10" c:name="myName"/>

         <bean class="…" c:name-ref="nameBean" c:spouse-ref="spouseBean"/>




                                                                                    41


Thursday, January 24, 13
Cache Abstraction




                           42


Thursday, January 24, 13
Cache Abstraction
      § CacheManager and Cache abstraction
         • in org.springframework.cache
            • which up until 3.0 just contained EhCache support
         • particularly important with the rise of distributed caching
            • not least of it all: in cloud environments




                                                                         42


Thursday, January 24, 13
Cache Abstraction
      § CacheManager and Cache abstraction
         • in org.springframework.cache
            • which up until 3.0 just contained EhCache support
         • particularly important with the rise of distributed caching
            • not least of it all: in cloud environments




                                                                         42


Thursday, January 24, 13
Cache Abstraction
      § CacheManager and Cache abstraction
         • in org.springframework.cache
            • which up until 3.0 just contained EhCache support
         • particularly important with the rise of distributed caching
            • not least of it all: in cloud environments


      § Backend adapters for EhCache, GemFire, Coherence, etc
         • EhCache adapter shipping with Spring core




                                                                         42


Thursday, January 24, 13
Cache Abstraction
      § CacheManager and Cache abstraction
         • in org.springframework.cache
            • which up until 3.0 just contained EhCache support
         • particularly important with the rise of distributed caching
            • not least of it all: in cloud environments


      § Backend adapters for EhCache, GemFire, Coherence, etc
         • EhCache adapter shipping with Spring core




                                                                         42


Thursday, January 24, 13
Cache Abstraction
      § CacheManager and Cache abstraction
         • in org.springframework.cache
            • which up until 3.0 just contained EhCache support
         • particularly important with the rise of distributed caching
            • not least of it all: in cloud environments


      § Backend adapters for EhCache, GemFire, Coherence, etc
         • EhCache adapter shipping with Spring core

      § Specific cache setup per environment – through profiles?
         • potentially even adapting to a runtime-provided service




                                                                         42


Thursday, January 24, 13
Cache Abstraction




                           43


Thursday, January 24, 13
Cache Abstraction
      @Cacheable ( name = “@(sessionKeyUtil).getCurrentSession() + owner”)
      public Owner loadOwner(int id);




                                                                             43


Thursday, January 24, 13
Cache Abstraction
      @Cacheable ( name = “@(sessionKeyUtil).getCurrentSession() + owner”)
      public Owner loadOwner(int id);

      @Cacheable(name = “owners”, condition="name.length < 10")




                                                                             43


Thursday, January 24, 13
Cache Abstraction
      @Cacheable ( name = “@(sessionKeyUtil).getCurrentSession() + owner”)
      public Owner loadOwner(int id);

      @Cacheable(name = “owners”, condition="name.length < 10")
      public Owner loadOwner(String name);




                                                                             43


Thursday, January 24, 13
Cache Abstraction
      @Cacheable ( name = “@(sessionKeyUtil).getCurrentSession() + owner”)
      public Owner loadOwner(int id);

      @Cacheable(name = “owners”, condition="name.length < 10")
      public Owner loadOwner(String name);




                                                                             43


Thursday, January 24, 13
Cache Abstraction
      @Cacheable ( name = “@(sessionKeyUtil).getCurrentSession() + owner”)
      public Owner loadOwner(int id);

      @Cacheable(name = “owners”, condition="name.length < 10")
      public Owner loadOwner(String name);

      @CacheEvict (name = “owners”)




                                                                             43


Thursday, January 24, 13
Cache Abstraction
      @Cacheable ( name = “@(sessionKeyUtil).getCurrentSession() + owner”)
      public Owner loadOwner(int id);

      @Cacheable(name = “owners”, condition="name.length < 10")
      public Owner loadOwner(String name);

      @CacheEvict (name = “owners”)
      public void deleteOwner(int id);




                                                                             43


Thursday, January 24, 13
Servlet 3.0 Based Web Applications
      § Explicit support for Servlet 3.0 containers
         • such as Tomcat 7 and GlassFish 3
         • while at the same time preserving compatibility with Servlet 2.4+

      § Support for XML-free web application setup (no web.xml)
         • Servlet 3.0's ServletContainerInitializer mechanism
         • in combination with Spring 3.1's AnnotationConfigWebApplicationContext
         • plus Spring 3.1's environment abstraction

      § Exposure of native Servlet 3.0 functionality in Spring MVC
         • standard Servlet 3.0 file upload behind Spring's MultipartResolver abstraction
         • support for asynchronous request processing coming in Spring 3.2




                                                                                            44


Thursday, January 24, 13
WebApplicationInitializer Example
      /**
       * Automatically detected and invoked on startup by Spring's
         ServletContainerInitializer. May register listeners, filters,
         servlets etc against the given Servlet 3.0 ServletContext.
       */
      public class MyWebAppInitializer implements WebApplicationInitializer {

          public void onStartup(ServletContext sc) throws ServletException {
            // Create the 'root' Spring application context
            AnnotationConfigWebApplicationContext root =
                  new AnnotationConfigWebApplicationContext();
              root.scan("com.mycompany.myapp");
              root.register(FurtherConfig.class);


              // Manages the lifecycle of the root application context
              sc.addListener(new ContextLoaderListener(root));
              ...
          }
      }
                                                                                45


Thursday, January 24, 13
@MVC Processing & Flash Attributes




                                           46


Thursday, January 24, 13
@MVC Processing & Flash Attributes
      § RequestMethodHandlerAdapter
             l   arbitrary mappings to handler methods across multiple controllers
             l   better customization of handler method arguments
                   −   HandlerMethodArgumentResolver
                   −   HandlerMethodReturnValueHandler
                   −   etc




                                                                                      46


Thursday, January 24, 13
@MVC Processing & Flash Attributes
      § RequestMethodHandlerAdapter
             l   arbitrary mappings to handler methods across multiple controllers
             l   better customization of handler method arguments
                   −   HandlerMethodArgumentResolver
                   −   HandlerMethodReturnValueHandler
                   −   etc


      § FlashMap support and FlashMapManager abstraction
             l   with RedirectAttributes as a new @MVC handler method argument type
                   −   explicitly calling addFlashAttribute to add values to the output FlashMap
             l   an outgoing FlashMap will temporarily get added to the user's session
             l   an incoming FlashMap for a request will automatically get exposed to the model




                                                                                                   46


Thursday, January 24, 13
Refined JPA Support
      § Package scanning without persistence.xml
             l   'packagesToScan' feature on LocalContainerEntityManagerFactoryBean
                   −   building a persistence unit from @Entity classes within specific application packages
             l   similar to AnnotationSessionFactoryBean for Hibernate 3
                   −   rolled into core LocalSessionFactoryBean for Hibernate 4
             l   ideal for applications with a single default persistence unit


      § Consistent JPA setup by persistence unit name
             l   JPA specification quite strongly based on the notion of persistence unit names
                   −   @PersistenceContext / @PersistenceUnit referring to persistence unit names
             l   now Spring's JpaTransactionManager and co. support setup by unit name as well
                   −   as an alternative to referring to EntityManagerFactory beans directly
                   −




                                                                                                               47


Thursday, January 24, 13
Third-Party Support Updates
   § Hibernate 4.0
           l   natively and through JPA
           l   native support in a dedicated org.springframework.orm.hibernate4 package
                 −   dealing with package rearrangements in the Hibernate API
           l   preserving compatibility with Hibernate 3.2+ in o.sf.orm.hibernate3


   § Quartz 2.0
           l   JobDetail and Trigger are now interfaces in the Quartz 2.0 API
                 −   whereas they traditionally were base classes in Quartz 1.x
           l   SchedulerFactoryBean now auto-adapts to Quartz 2.0 if present
                 −   JobDetail/CronTrigger/SimpleTriggerFactoryBean variants for Quartz 2.0
           l   preserving compatibility with Quartz 1.5+ in the same support package




                                                                                              48


Thursday, January 24, 13
Java SE 7




                           49


Thursday, January 24, 13
Java SE 7
      § Spring 3.1 introduces Java SE 7 support
             l   making best use of JRE 7 at runtime
             l   support for JDBC 4.1
             l   support for fork-join framework




                                                        49


Thursday, January 24, 13
Java SE 7
      § Spring 3.1 introduces Java SE 7 support
             l   making best use of JRE 7 at runtime
             l   support for JDBC 4.1
             l   support for fork-join framework


      § Oracle's OpenJDK 7 released in summer 2011
             l   IBM JDK 7 following not much later
             l   Java 7 could be the norm for new Java based projects soon




                                                                              49


Thursday, January 24, 13
Java SE 7
      § Spring 3.1 introduces Java SE 7 support
             l   making best use of JRE 7 at runtime
             l   support for JDBC 4.1
             l   support for fork-join framework


      § Oracle's OpenJDK 7 released in summer 2011
             l   IBM JDK 7 following not much later
             l   Java 7 could be the norm for new Java based projects soon




                                                                              49


Thursday, January 24, 13
Java SE 7
      § Spring 3.1 introduces Java SE 7 support
             l   making best use of JRE 7 at runtime
             l   support for JDBC 4.1
             l   support for fork-join framework


      § Oracle's OpenJDK 7 released in summer 2011
             l   IBM JDK 7 following not much later
             l   Java 7 could be the norm for new Java based projects soon


      § Spring Framework not being built against Java 7 yet
             l   build upgrade coming in Spring 3.3




                                                                              49


Thursday, January 24, 13
github.com/SpringSource




                                50

Thursday, January 24, 13
Spring 3.2




                           51

Thursday, January 24, 13
Current and Upcoming: 3.1, 3.2, and 3.2

      § Spring Framework 3.1 (Dec 2011)
         • Environment profiles, Java-based configuration, declarative caching
         • Initial Java 7 support, Servlet 3.0 based deployment
      § Spring Framework 3.2 (Dec 2012)
         • Gradle-based build, GitHub-based contribution model
         • Fully Java 7 oriented, async MVC processing on Servlet 3.0
      § Spring Framework 3.3 (Q4 2013)
         • Comprehensive Java SE 8 support (including lambda expressions)
            • Single abstract method types in Spring are well positioned
         • Support for Java EE 7 API level and WebSockets




                                                                                 52

Thursday, January 24, 13
Change of Plans

      § We originally meant to have Java SE 8 and Java EE 7 themes in Spring 3.2
      § However, Java EE 7 got pushed out further and further: Q2 2013
         • eventually descoped and delayed (no cloud focus anymore)
      § And Java SE 8 (OpenJDK 8) got rescheduled as well: September 2013
         • once again, descoped and delayed (no module system anymore)
         • feature-complete developer preview expected for February 2013
      § Our solution: Spring 3.2 ships in Q4 2012 with core framework refinements
         • Spring 3.3 will ship in Q4 2013 with Java SE 8 and Java EE 7 support




                                                                                     53

Thursday, January 24, 13
So what’s in 3.2?

      § Gradle-based build
      § Binaries built against Java 7
      § Inlined ASM 4.0 and CGLIB 3.0
      § Async MVC processing on Servlet 3.0
      § Spring MVC test support
      § MVC configuration refinements
      § SpEL refinements
      § Also including many runtime refinements
         • partially back-ported to 3.1.2/3.1.3
      § General Spring MVC niceties
         • Servlet 3 async support
         • error reporting in REST scenarios
         • content negotiation strategies
         • matrix variables




                                                   54

Thursday, January 24, 13
Spring 3.2

      § Spring 3.1 came with early support for Java 7
         • JDBC 4.1, ForkJoinPool, etc
         • framework itself still compiled on Java 6
      § Spring 3.2 is now being built on Java 7
         • CI builds running against Java 5, 6 and 7
      § enabled through our new Gradle build
      § Spring 3.2 comes with ASM 4.0 and CGLIB 3.0
         • fully supporting the Java 7 byte code format
         • ASM and CGLIB inlined into Spring module jars now




                                                               55

Thursday, January 24, 13
Async MVC Processing: Callable


        @RequestMapping(name =“/upload”,
                            method=RequestMethod.POST)
         public Callable<String> processUpload(MultipartFile file) {

              return new Callable<String>() {
                public String call() throws Exception {
                  // ...
                  return "someView";
                }
            };

        }

                      - thread managed by Spring MVC
                      - good for long running database jobs, 3rd party REST API calls, etc




                                                                                             56

Thursday, January 24, 13
Async MVC Processing: DeferredResult



       @RequestMapping("/quotes")
       @ResponseBody
       public DeferredResult quotes() {
         DeferredResult deferredResult = new DeferredResult();
         // Add deferredResult to a Queue or a Map...
         return deferredResult;
    }

    // In some other thread:
    // Set the return value on the DeferredResult deferredResult.set(data);


                      - thread managed outside of Spring MVC
                      - JMS or AMQP message listener, another HTTP request, etc.




                                                                                   57

Thursday, January 24, 13
Async MVC Processing: AsyncTask


        @RequestMapping(name =“/upload”, method=RequestMethod.POST)
         public AsyncTask<Foo> processUpload(MultipartFile file) {

               TaskExecutor asyncTaskExecutor = new AsyncTaskExecutor(...);

               return new AsyncTask<Foo>(
                   1000L,                   // timeout
                   asyncTaskExecutor,       // thread pool
                   new Callable<Foo>(){ ..} // thread
                );

        }

                      - same as Callable, with extra features
                      - override timeout value for async processing
                      - lets you specify a specific AsyncTaskExecutor


                                                                              58

Thursday, January 24, 13
Content Negotiation Strategies




        ContentNegotiationStrategy
        • By 'Accept' Header
        • By URL extension (.xml, .json, etc)
        • By Request parameter, i.e. /accounts/1?format=json
        • Fixed content type, i.e. a fallback option

        ContentNegotiationManager
        • has one or more ContentNegotiationStrategy instances
        • works with:
           RequestMappingHandlerMapping,
           RequestMappingHandlerAdapter,
           ExceptionHandlerExceptionResolver
           ContentNegotiatingViewResolver




                                                                 59

Thursday, January 24, 13
Matrix Variables



      "Each path segment may include a
      sequence of parameters, indicated by the
      semicolon ";" character. The parameters
      are not significant to the parsing of
      relativeb references.

      RFC 2396, section 3.3




                                                 60

Thursday, January 24, 13
Matrix Variables



        "The semicolon (";") and equals ("=") reserved characters
        are often used to delimit parameters and
        parameter values applicable to that segment. The
        comma (",") reserved character is often used for
        similar purposes."


        RFC 3986, section 3.3




                                                                    61

Thursday, January 24, 13
Matrix Variables

      § Two Types of Usages
      § Path Segment Name-Value Pairs
          /qa-releases;buildNumber=135;revision=3.2


      § As delimited list path segment
          /answers/id1;id2;id3;id4/comments




                                                      62

Thursday, January 24, 13
Matrix Variables: the common case



        // GET /pets/42;q=11;r=22

        @RequestMapping(value = "/pets/{petId}")
        public void findPet(
            @PathVariable String petId, @MatrixVariable int q) {

               // petId == 42
               // q == 11

        }




                                                                   63

Thursday, January 24, 13
Matrix Variables: obtain all matrix variables




              // GET /owners/42;q=11;r=12/pets/21;q=22;s=23

              @RequestMapping(value = "/owners/{ownerId}/pets/{petId}")
              public void findPet(
                  @MatrixVariable Map<String, String> matrixVars) {

                           // matrixVars: ["q" : [11,22], "r" : 12, "s" : 23]

              }




                                                                                64

Thursday, January 24, 13
Matrix Variables: qualify path segment



                 // GET /owners/42;q=11/pets/21;q=22

                 @RequestMapping(value = "/owners/{ownerId}/pets/{petId}")
                 public void findPet(
                     @MatrixVariable(value="q", pathVar="ownerId") int q1,
                     @MatrixVariable(value="q", pathVar="petId") int q2) {

                           // q1 == 11
                           // q2 == 22

                 }




                                                                             65

Thursday, January 24, 13
Spring 3.3...




                           66

Thursday, January 24, 13
Current and Upcoming: 3.1, 3.2, and 3.2

      § Spring Framework 3.1 (Dec 2011)
         • Environment profiles, Java-based configuration, declarative caching
         • Initial Java 7 support, Servlet 3.0 based deployment
      § Spring Framework 3.2 (Dec 2012)
         • Gradle-based build, GitHub-based contribution model
         • Fully Java 7 oriented, async MVC processing on Servlet 3.0
      § Spring Framework 3.3 (Q4 2013)
         • Comprehensive Java SE 8 support (including lambda expressions)
            • Single abstract method types in Spring are well positioned
         • Support for Java EE 7 API level and WebSockets




                                                                                 67

Thursday, January 24, 13
Spring Framework 3.3 (Q4 2013)

      § Comprehensive Java 8 support
         • Support for Java EE 7 API levels
         • Focus on message-oriented architectures
         • annotation-driven JMS endpoint model
      § revised application event mechanism
      § WebSocket support in Spring MVC
      § Next-generation Groovy support
      § Grails bean builder finally making it into Spring proper

      § PROBABLY (but can’t say for sure): this will be Spring 4.0




                                                                      68

Thursday, January 24, 13
The Java SE 8 Story

      § Comprehensive Java 8 support
         • lambda expressions a.k.a. closures
         • Date and Time API (JSR-310)
         • NIO-based HTTP client APIs
         • parameter name discovery
         • java.util.concurrent enhancements
      § Retaining support for Java 5 and higher
         • with Java 6 and 7 as common levels
         • Java 8 potentially becoming popular rather quickly...




                                                                   69

Thursday, January 24, 13
The Java EE 7 Story

      § Support for Java EE 7 API levels
         • JCache 1.0
         • JMS 2.0
         • JPA2.1
         • JTA 1.2 (@Transactional)
         • Bean Validation 1.1
         • Servlet3.1
         • JSF 2.2
      § Retaining support for Java EE 5 and higher




                                                      70

Thursday, January 24, 13
Annotation Driven JMS Endpoints



    @JmsListener(destination="myQueue")
    public void handleMessage(TextMessage payload);

    @JmsListener(destination="myQueue", selector="...")
    public void handleMessage(String payload);

    @JmsListener(destination="myQueue")
    public String handleMessage(String payload);




                                                          71

Thursday, January 24, 13
WebSocket Support

      § WebSocket support in current servers isn't fully standardized yet
      § JSR-356 upcoming within the Java EE 7 timeframe
      § Jetty 9 and co. to adopt it rather quickly
      § Spring Framework 3.3 to research all options for WebSocket support
         • primarily in Spring MVC
         • but also generally for message-oriented architectures




                                                                              72

Thursday, January 24, 13
Current and Upcoming: 3.1, 3.2, and 3.2

      § Spring Framework 3.1 (Dec 2011)
         • Environment profiles, Java-based configuration, declarative caching
         • Initial Java 7 support, Servlet 3.0 based deployment
      § Spring Framework 3.2 (Dec 2012)
         • Gradle-based build, GitHub-based contribution model
         • Fully Java 7 oriented, async MVC processing on Servlet 3.0
      § Spring Framework 3.3 (Q4 2013)
         • Comprehensive Java SE 8 support (including lambda expressions)
         • Support for Java EE 7 API level and WebSockets




                                                                                 73

Thursday, January 24, 13
@SpringSource @Starbuxman




                            Questions?
                                  NOT CONFIDENTIAL -- TELL EVERYONE


Thursday, January 24, 13

The spring 32 update final

  • 1.
    Spring 3.1, 3.2,and 3.3 Update Josh Long Spring Developer Advocate, SpringSource, a Division of VMWare http://www.joshlong.com || @starbuxman || josh.long@springsource.com © 2012 SpringOne 2GX 2012. All rights reserved. Do not distribute without permission. Thursday, January 24, 13
  • 2.
    About Josh Long(龙之春) Spring Developer Advocate twitter: @starbuxman weibo: @springsource josh.long@springsource.com 2 Thursday, January 24, 13
  • 3.
    About Josh Long Spring Developer Advocate twitter: @starbuxman josh.long@springsource.com Contributor To: •Spring Integration •Spring Batch •Spring Hadoop •Activiti Workflow Engine •Akka Actor engine 3 Thursday, January 24, 13
  • 4.
    Why Are WeHere? 4 Thursday, January 24, 13
  • 5.
    Why Are WeHere? “ Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. ” -Bob Martin 5 Thursday, January 24, 13
  • 6.
    Why Are WeHere? do NOT reinvent the Wheel! 6 Thursday, January 24, 13
  • 7.
    Spring’s aim: bring simplicity to java development data web tier batch integration & access & service tier mobile Security processing messaging / NoSQL / RIA Big Data The Spring framework the cloud: lightweight traditional CloudFoundry tc Server WebSphere Google App Engine Tomcat JBoss AS Amazon BeanStalk Jetty WebLogic (on legacy versions, too!) 7 Thursday, January 24, 13
  • 8.
    The Spring Framework Framework Description Spring Core The foundation Spring @MVC the web leading framework (comes with the core framework) Spring Security Extensible framework providing authentication, authorization Spring Webflow An excellent web framework for building multi-page flows Spring Web Services Contract-first, document–centric SOAP and XML web services Spring Batch Powerful batch processing framework Spring Integration Implements enterprise integration patterns Spring BlazeDS Support for Adobe BlazeDS Spring AMQP interface with AMQP message brokers, like RabbitMQ Spring Data NoSQL options: MongoDB, Redis, Riak, CouchDB, Neo4J, etc. Spring Social integrate Twitter, Facebook, Tripit, MySpace, LinkedIn, etc. Provides a POJO-centric approach to building Spring Hadoop Hadoop applications. Supports HBase, others provides first-class support for service Spring Mobile, Spring Android creation and consumption for iPhone, Android Spring GemFire Provides the easiest interface for the GemFire enterprise data grid technology 8 Thursday, January 24, 13
  • 9.
    Wide Variety ofData and Data Stores § Not all data resides in relational databases l cloud environments often suggest alternatives for scalability reasons l HBase, Redis, Mongo, etc § Distributed caches add challenges as well l not least of it all in terms of application-level access patterns l GemFire, Coherence, etc § Hardly any standardization available l JSR-107 – for caching – did not make progress for a long, long time l finally getting picked up in Java EE 7, but again only for caching l alternative datastore space is too diverse for standardization Thursday, January 24, 13
  • 10.
    Wide Variety ofWeb Clients § More and more client-side web technologies l HTML 5 as a next-generation browser standard § Server-side state to be minimized or even removed completely l in particular: no server-side user interface state l strictly controlled user session state § JSF's state-centric approach not a great fit anymore l except for special kinds of applications (which it remains very useful for) l web application backends and web services based on JAX-RS / MVC style l nevertheless: JSF keeps evolving – JSF 2.2 coming up in 2012 10 Thursday, January 24, 13
  • 11.
    Current and Upcoming:3.1, 3.2, and 3.2 § Spring Framework 3.1 (Dec 2011) • Environment profiles, Java-based configuration, declarative caching • Initial Java 7 support, Servlet 3.0 based deployment § Spring Framework 3.2 (Dec 2012) • Gradle-based build, GitHub-based contribution model • Fully Java 7 oriented, async MVC processing on Servlet 3.0 § Spring Framework 3.3 (Q4 2013) • Comprehensive Java SE 8 support (including lambda expressions) • Single abstract method types in Spring are well positioned • Support for Java EE 7 API level and WebSockets 11 Thursday, January 24, 13
  • 12.
    Spring 3.1 12 Thursday, January 24, 13
  • 13.
    Current and Upcoming:3.1, 3.2, and 3.2 § Spring Framework 3.1 (Dec 2011) • Environment profiles, Java-based configuration, declarative caching • Initial Java 7 support, Servlet 3.0 based deployment § Spring Framework 3.2 (Dec 2012) • Gradle-based build, GitHub-based contribution model • Fully Java 7 oriented, async MVC processing on Servlet 3.0 § Spring Framework 3.3 (Q4 2013) • Comprehensive Java SE 8 support (including lambda expressions) • Single abstract method types in Spring are well positioned • Support for Java EE 7 API level and WebSockets 13 Thursday, January 24, 13
  • 14.
    Spring Framework 3.1:Selected Features § Environment abstraction and profiles § Java-based application configuration § Overhaul of the test context framework § Cache abstraction & declarative caching § Servlet 3.0 based web applications § @MVC processing & flash attributes § Refined JPA support § Hibernate 4.0 & Quartz 2.0 § Support for Java SE 7 14 Thursday, January 24, 13
  • 15.
    Environment Abstraction 15 Thursday, January 24, 13
  • 16.
    Environment Abstraction § Grouping bean definitions for activation in specific environments • e.g. development, testing, production • possibly different deployment environments § Custom resolution of placeholders • dependent on the actual environment • hierarchy of property sources 15 Thursday, January 24, 13
  • 17.
    Environment Abstraction § Grouping bean definitions for activation in specific environments • e.g. development, testing, production • possibly different deployment environments § Custom resolution of placeholders • dependent on the actual environment • hierarchy of property sources 15 Thursday, January 24, 13
  • 18.
    Environment Abstraction § Grouping bean definitions for activation in specific environments • e.g. development, testing, production • possibly different deployment environments § Custom resolution of placeholders • dependent on the actual environment • hierarchy of property sources § Injectable environment abstraction API • org.springframework.core.env.Environment 15 Thursday, January 24, 13
  • 19.
    Environment Abstraction § Grouping bean definitions for activation in specific environments • e.g. development, testing, production • possibly different deployment environments § Custom resolution of placeholders • dependent on the actual environment • hierarchy of property sources § Injectable environment abstraction API • org.springframework.core.env.Environment § Unified property resolution SPI • org.springframework.core.env.PropertyResolver 15 Thursday, January 24, 13
  • 20.
    Bean Definition Profiles <beans profile="production"> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClass" value="${database.driver}"/> <property name="jdbcUrl" value="${database.url}"/> <property name="username" value="${database.username}"/> <property name="password" value="${database.password}"/> </bean> </beans> <beans profile="embedded"> <jdbc:embedded-database id="dataSource" type="H2"> <jdbc:script location="/WEB-INF/database/schema-member.sql"/> <jdbc:script location="/WEB-INF/database/schema-activity.sql"/> <jdbc:script location="/WEB-INF/database/schema-event.sql"/> <jdbc:script location="/WEB-INF/database/data.sql"/> </jdbc:embedded-database> </beans> 16 Thursday, January 24, 13
  • 21.
    Environment Configuration 17 Thursday, January 24, 13
  • 22.
    Environment Configuration § Associating specific bean definitions with specific environments • XML 'profile' attribute on <beans> element • @Profile annotation on configuration classes • @Profile annotation on individual component classes 17 Thursday, January 24, 13
  • 23.
    Environment Configuration § Associating specific bean definitions with specific environments • XML 'profile' attribute on <beans> element • @Profile annotation on configuration classes • @Profile annotation on individual component classes § Activating specific profiles by name • e.g. through a system property • -Dspring.profiles.active=development • or other means outside of the deployment unit • according to environment conventions 17 Thursday, January 24, 13
  • 24.
    Environment Configuration § Associating specific bean definitions with specific environments • XML 'profile' attribute on <beans> element • @Profile annotation on configuration classes • @Profile annotation on individual component classes § Activating specific profiles by name • e.g. through a system property • -Dspring.profiles.active=development • or other means outside of the deployment unit • according to environment conventions 17 Thursday, January 24, 13
  • 25.
    Environment Configuration § Associating specific bean definitions with specific environments • XML 'profile' attribute on <beans> element • @Profile annotation on configuration classes • @Profile annotation on individual component classes § Activating specific profiles by name • e.g. through a system property • -Dspring.profiles.active=development • or other means outside of the deployment unit • according to environment conventions § Ideally: no need to touch deployment unit across different stages/environments 17 Thursday, January 24, 13
  • 26.
    Java-Based Application Configuration 18 Thursday, January 24, 13
  • 27.
    Java-Based Application Configuration § Application-specific container configuration • aligned with Spring 3.0's @Configuration style • focus on customizing the annotation-based processing parts of Spring 18 Thursday, January 24, 13
  • 28.
    Java-Based Application Configuration § Application-specific container configuration • aligned with Spring 3.0's @Configuration style • focus on customizing the annotation-based processing parts of Spring § Equivalent to XML namespace functionality • but not a one-to-one mapping • 'natural' container configuration from an annotation-oriented perspective 18 Thursday, January 24, 13
  • 29.
    Java-Based Application Configuration § Application-specific container configuration • aligned with Spring 3.0's @Configuration style • focus on customizing the annotation-based processing parts of Spring § Equivalent to XML namespace functionality • but not a one-to-one mapping • 'natural' container configuration from an annotation-oriented perspective 18 Thursday, January 24, 13
  • 30.
    Java-Based Application Configuration § Application-specific container configuration • aligned with Spring 3.0's @Configuration style • focus on customizing the annotation-based processing parts of Spring § Equivalent to XML namespace functionality • but not a one-to-one mapping • 'natural' container configuration from an annotation-oriented perspective § Typical infrastructure setup • transactions • scheduling • MVC customization 18 Thursday, January 24, 13
  • 31.
    So, What’s Allof This Look Like in Code? Not confidential. Tell everyone. 19 Thursday, January 24, 13
  • 32.
    I want DatabaseAccess ... with Hibernate 4 Support @Service public class CustomerService { public Customer getCustomerById( long customerId) { ... } public Customer createCustomer( String firstName, String lastName, Date date){ ... } } Not confidential. Tell everyone. 20 Thursday, January 24, 13
  • 33.
    I want DatabaseAccess ... with Hibernate 4 Support @Service public class CustomerService { @Inject private SessionFactory sessionFactory; public Customer createCustomer(String firstName, String lastName, Date signupDate) { Customer customer = new Customer(); customer.setFirstName(firstName); customer.setLastName(lastName); customer.setSignupDate(signupDate); sessionFactory.getCurrentSession().save(customer); return customer; } } Not confidential. Tell everyone. 21 Thursday, January 24, 13
  • 34.
    I want DatabaseAccess ... with Hibernate 4 Support @Service public class CustomerService { @Inject private SessionFactory sessionFactory; @Transactional public Customer createCustomer(String firstName, String lastName, Date signupDate) { Customer customer = new Customer(); customer.setFirstName(firstName); customer.setLastName(lastName); customer.setSignupDate(signupDate); sessionFactory.getCurrentSession().save(customer); return customer; } } Not confidential. Tell everyone. 22 Thursday, January 24, 13
  • 35.
    I want DeclarativeCache Management... @Service public class CustomerService { @Inject private SessionFactory sessionFactory; @Transactional(readOnly = true) @Cacheable(“customers”) public Customer getCustomerById( long customerId) { ... } ... } Not confidential. Tell everyone. 23 Thursday, January 24, 13
  • 36.
    I want aRESTful Endpoint... package org.springsource.examples.spring31.web; .. @Controller public class CustomerController { @Inject private CustomerService customerService; @RequestMapping(value = "/customer/{id}" ) @ResponseBody public Customer customerById( @PathVariable("id") Integer id ) { return customerService.getCustomerById(id); } ... } Not confidential. Tell everyone. 24 Thursday, January 24, 13
  • 37.
    ...But Where’d theSessionFactory come from? Not confidential. Tell everyone. 25 Thursday, January 24, 13
  • 38.
    The Spring ApplicationContext § Spring Manages the beans you tell it to manage (Implicitly, Explicitly) • use annotations (JSR 250, JSR 330, native) • XML • Java configuration • component scanning § You can of course use all of them! Mix ‘n match § All configuration styles tell the ApplicationContext how to manage your beans 26 Thursday, January 24, 13
  • 39.
    The Spring ApplicationContext § Annotations (component-scanning) • best when you want Spring to sort it all out in the wash, no need for explicit configuration § Java Configuration • type-safe, and explicit - all configuration is centralized. Provides a good birds-eye view of your application § XML • explicit - namespaces still provide the most punch in a lot of cases § All together • use Java configuration for your regular third party beans (like a DataSource) • XML namespaces for DSLs and higher level functionality (Spring Integration, Batch, etc.) • annotations for your components (a @Service, or a Spring MVC @Controller) 27 Thursday, January 24, 13
  • 40.
    The Spring ApplicationContext From XML: public class Main { public static void main(String [] args) throws Throwable { ApplicationContext ctx = new ClassPathXmlApplication( “my-config.xml” ); CustomerService serviceReference = ctx.getBean( CustomerService.class ); Customer customer = serviceReference.createCustomer( "Juergen", "Hoeller"); } } 28 Thursday, January 24, 13
  • 41.
    The Spring ApplicationContext From XML: public class Main { public static void main(String [] args) throws Throwable { ApplicationContext ctx = new ClassPathXmlApplication( “my-config.xml” ); CustomerService serviceReference = ctx.getBean( CustomerService.class ); Customer customer = serviceReference.createCustomer( "Juergen", "Hoeller"); } } From Java Configuration public class Main { public static void main(String [] args) throws Throwable { ApplicationContext ctx = new AnnotationConfigApplicationContext( ServicesConfiguration.class ); CustomerService serviceReference = ctx.getBean( CustomerService.class ); Customer customer = serviceReference.createCustomer( "Juergen", "Hoeller"); } } 28 Thursday, January 24, 13
  • 42.
    A Quick Primeron Configuration in Spring 3.1 .... <beans> <tx:annotation-driven transaction-manager = "txManager" /> <context:component-scan base-package = "org.springsource.examples.spring31.services" /> <context:property-placeholder properties = "config.properties" /> <bean id = "txManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name = "sessionFactory" ref = "sessionFactory" /> </bean> <bean id = "sessionFactory" class = "org.springframework.orm.hibernate4.LocalSessionFactoryBean"> ... </bean> <bean id = "dataSource" class = "..SimpleDriverDataSource"> <property name= "userName" value = "${ds.user}"/> ... </bean> </beans> ApplicationContext ctx = new ClassPathXmlApplication( “service-config.xml” ); Not confidential. Tell everyone. Thursday, January 24, 13
  • 43.
    A Quick Primeron Configuration in Spring 3.1 .... <beans> <tx:annotation-driven transaction-manager = "txManager" /> <context:component-scan base-package = "org.springsource.examples.spring31.services" /> <context:property-placeholder properties = "config.properties" /> <bean id = "txManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name = "sessionFactory" ref = "sessionFactory" /> </bean> <bean id = "sessionFactory" class = "org.springframework.orm.hibernate4.LocalSessionFactoryBean"> ... </bean> <bean id = "dataSource" class = "..SimpleDriverDataSource"> <property name= "userName" value = "${ds.user}"/> ... </bean> </beans> ApplicationContext ctx = new ClassPathXmlApplication( “service-config.xml” ); Not confidential. Tell everyone. Thursday, January 24, 13
  • 44.
    A Quick Primeron Configuration in Spring 3.1 @Configuration @PropertySource("/config.properties") @EnableTransactionManagement @ComponentScan(basePackageClasses = {CustomerService.class}) public class ServicesConfiguration { @Inject private Environment environment; @Bean public PlatformTransactionManager txManager() throws Exception { return new HibernateTransactionManager(this.sessionFactory()); } @Bean public SessionFactory sessionFactory() { ... } @Bean public DataSource dataSource(){ SimpleDriverDataSource sds = new SimpleDriverDataSource(); sds.setUserName( this.environment.getProperty( “ds.user”)); // ... return sds; } } ApplicationContext ctx = new AnnotationConfigApplicationContext( ServicesConfiguration.class ); Not confidential. Tell everyone. Thursday, January 24, 13
  • 45.
    A Quick Primeron Configuration in Spring 3.1 .... <beans> <tx:annotation-driven transaction-manager = "txManager" /> <context:component-scan base-package = "org.springsource.examples.spring31.services" /> <context:property-placeholder properties = "config.properties" /> <bean id = "txManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name = "sessionFactory" ref = "sessionFactory" /> </bean> <bean id = "sessionFactory" class = "org.springframework.orm.hibernate4.LocalSessionFactoryBean"> ... </bean> <bean id = "dataSource" class = "..SimpleDriverDataSource"> <property name= "userName" value = "${ds.user}"/> ... </bean> </beans> ApplicationContext ctx = new ClassPathXmlApplication( “service-config.xml” ); Not confidential. Tell everyone. Thursday, January 24, 13
  • 46.
    A Quick Primeron Configuration in Spring 3.1 @Configuration @PropertySource("/config.properties") @EnableTransactionManagement @ComponentScan(basePackageClasses = {CustomerService.class}) public class ServicesConfiguration { @Inject private Environment environment; @Bean public PlatformTransactionManager txManager() throws Exception { return new HibernateTransactionManager(this.sessionFactory()); } @Bean public SessionFactory sessionFactory() { ... } @Bean public DataSource dataSource(){ SimpleDriverDataSource sds = new SimpleDriverDataSource(); sds.setUserName( this.environment.getProperty( “ds.user”)); // ... return sds; } } ApplicationContext ctx = new AnnotationConfigApplicationContext( ServicesConfiguration.class ); Not confidential. Tell everyone. Thursday, January 24, 13
  • 47.
    A Quick Primeron Configuration in Spring 3.1 .... <beans> <tx:annotation-driven transaction-manager = "txManager" /> <context:component-scan base-package = "org.springsource.examples.spring31.services" /> <context:property-placeholder properties = "config.properties" /> <bean id = "txManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name = "sessionFactory" ref = "sessionFactory" /> </bean> <bean id = "sessionFactory" class = "org.springframework.orm.hibernate4.LocalSessionFactoryBean"> ... </bean> <bean id = "dataSource" class = "..SimpleDriverDataSource"> <property name= "userName" value = "${ds.user}"/> ... </bean> </beans> ApplicationContext ctx = new ClassPathXmlApplication( “service-config.xml” ); Not confidential. Tell everyone. Thursday, January 24, 13
  • 48.
    A Quick Primeron Configuration in Spring 3.1 @Configuration @PropertySource("/config.properties") @EnableTransactionManagement @ComponentScan(basePackageClasses = {CustomerService.class}) public class ServicesConfiguration { @Inject private Environment environment; @Bean public PlatformTransactionManager txManager() throws Exception { return new HibernateTransactionManager(this.sessionFactory()); } @Bean public SessionFactory sessionFactory() { ... } @Bean public DataSource dataSource(){ SimpleDriverDataSource sds = new SimpleDriverDataSource(); sds.setUserName( this.environment.getProperty( “ds.user”)); // ... return sds; } } ApplicationContext ctx = new AnnotationConfigApplicationContext( ServicesConfiguration.class ); Not confidential. Tell everyone. Thursday, January 24, 13
  • 49.
    A Quick Primeron Configuration in Spring 3.1 .... <beans> <tx:annotation-driven transaction-manager = "txManager" /> <context:component-scan base-package = "org.springsource.examples.spring31.services" /> <context:property-placeholder properties = "config.properties" /> <bean id = "txManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name = "sessionFactory" ref = "sessionFactory" /> </bean> <bean id = "sessionFactory" class = "org.springframework.orm.hibernate4.LocalSessionFactoryBean"> ... </bean> <bean id = "dataSource" class = "..SimpleDriverDataSource"> <property name= "userName" value = "${ds.user}"/> ... </bean> </beans> ApplicationContext ctx = new ClassPathXmlApplication( “service-config.xml” ); Not confidential. Tell everyone. Thursday, January 24, 13
  • 50.
    A Quick Primeron Configuration in Spring 3.1 @Configuration @PropertySource("/config.properties") @EnableTransactionManagement @ComponentScan(basePackageClasses = {CustomerService.class}) public class ServicesConfiguration { @Inject private Environment environment; @Bean public PlatformTransactionManager txManager() throws Exception { return new HibernateTransactionManager(this.sessionFactory()); } @Bean public SessionFactory sessionFactory() { ... } @Bean public DataSource dataSource(){ SimpleDriverDataSource sds = new SimpleDriverDataSource(); sds.setUserName( this.environment.getProperty( “ds.user”)); // ... return sds; } } ApplicationContext ctx = new AnnotationConfigApplicationContext( ServicesConfiguration.class ); Not confidential. Tell everyone. Thursday, January 24, 13
  • 51.
    A Quick Primeron Configuration in Spring 3.1 .... <beans> <tx:annotation-driven transaction-manager = "txManager" /> <context:component-scan base-package = "org.springsource.examples.spring31.services" /> <context:property-placeholder properties = "config.properties" /> <bean id = "txManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager"> <property name = "sessionFactory" ref = "sessionFactory" /> </bean> <bean id = "sessionFactory" class = "org.springframework.orm.hibernate4.LocalSessionFactoryBean"> ... </bean> <bean id = "dataSource" class = "..SimpleDriverDataSource"> <property name= "userName" value = "${ds.user}"/> ... </bean> </beans> ApplicationContext ctx = new ClassPathXmlApplication( “service-config.xml” ); Not confidential. Tell everyone. Thursday, January 24, 13
  • 52.
    A Quick Primeron Configuration in Spring 3.1 @Configuration @PropertySource("/config.properties") @EnableTransactionManagement @ComponentScan(basePackageClasses = {CustomerService.class}) public class ServicesConfiguration { @Inject private Environment environment; @Bean public PlatformTransactionManager txManager() throws Exception { return new HibernateTransactionManager(this.sessionFactory()); } @Bean public SessionFactory sessionFactory() { ... } @Bean public DataSource dataSource(){ SimpleDriverDataSource sds = new SimpleDriverDataSource(); sds.setUserName( this.environment.getProperty( “ds.user”)); // ... return sds; } } ApplicationContext ctx = new AnnotationConfigApplicationContext( ServicesConfiguration.class ); Not confidential. Tell everyone. Thursday, January 24, 13
  • 53.
    Test Context Framework @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration( loader=AnnotationConfigContextLoader.class, classes={TransferServiceConfig.class, DataConfig.class}) @ActiveProfiles("dev") public class TransferServiceTest { @Autowired private TransferService transferService; @Test public void testTransferService() { ... } } 40 Thursday, January 24, 13
  • 54.
    "c:" Namespace § New XML namespace for use with bean configuration • 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 <bean class="…" c:age="10" c:name="myName"/> <bean class="…" c:name-ref="nameBean" c:spouse-ref="spouseBean"/> 41 Thursday, January 24, 13
  • 55.
    Cache Abstraction 42 Thursday, January 24, 13
  • 56.
    Cache Abstraction § CacheManager and Cache abstraction • in org.springframework.cache • which up until 3.0 just contained EhCache support • particularly important with the rise of distributed caching • not least of it all: in cloud environments 42 Thursday, January 24, 13
  • 57.
    Cache Abstraction § CacheManager and Cache abstraction • in org.springframework.cache • which up until 3.0 just contained EhCache support • particularly important with the rise of distributed caching • not least of it all: in cloud environments 42 Thursday, January 24, 13
  • 58.
    Cache Abstraction § CacheManager and Cache abstraction • in org.springframework.cache • which up until 3.0 just contained EhCache support • particularly important with the rise of distributed caching • not least of it all: in cloud environments § Backend adapters for EhCache, GemFire, Coherence, etc • EhCache adapter shipping with Spring core 42 Thursday, January 24, 13
  • 59.
    Cache Abstraction § CacheManager and Cache abstraction • in org.springframework.cache • which up until 3.0 just contained EhCache support • particularly important with the rise of distributed caching • not least of it all: in cloud environments § Backend adapters for EhCache, GemFire, Coherence, etc • EhCache adapter shipping with Spring core 42 Thursday, January 24, 13
  • 60.
    Cache Abstraction § CacheManager and Cache abstraction • in org.springframework.cache • which up until 3.0 just contained EhCache support • particularly important with the rise of distributed caching • not least of it all: in cloud environments § Backend adapters for EhCache, GemFire, Coherence, etc • EhCache adapter shipping with Spring core § Specific cache setup per environment – through profiles? • potentially even adapting to a runtime-provided service 42 Thursday, January 24, 13
  • 61.
    Cache Abstraction 43 Thursday, January 24, 13
  • 62.
    Cache Abstraction @Cacheable ( name = “@(sessionKeyUtil).getCurrentSession() + owner”) public Owner loadOwner(int id); 43 Thursday, January 24, 13
  • 63.
    Cache Abstraction @Cacheable ( name = “@(sessionKeyUtil).getCurrentSession() + owner”) public Owner loadOwner(int id); @Cacheable(name = “owners”, condition="name.length < 10") 43 Thursday, January 24, 13
  • 64.
    Cache Abstraction @Cacheable ( name = “@(sessionKeyUtil).getCurrentSession() + owner”) public Owner loadOwner(int id); @Cacheable(name = “owners”, condition="name.length < 10") public Owner loadOwner(String name); 43 Thursday, January 24, 13
  • 65.
    Cache Abstraction @Cacheable ( name = “@(sessionKeyUtil).getCurrentSession() + owner”) public Owner loadOwner(int id); @Cacheable(name = “owners”, condition="name.length < 10") public Owner loadOwner(String name); 43 Thursday, January 24, 13
  • 66.
    Cache Abstraction @Cacheable ( name = “@(sessionKeyUtil).getCurrentSession() + owner”) public Owner loadOwner(int id); @Cacheable(name = “owners”, condition="name.length < 10") public Owner loadOwner(String name); @CacheEvict (name = “owners”) 43 Thursday, January 24, 13
  • 67.
    Cache Abstraction @Cacheable ( name = “@(sessionKeyUtil).getCurrentSession() + owner”) public Owner loadOwner(int id); @Cacheable(name = “owners”, condition="name.length < 10") public Owner loadOwner(String name); @CacheEvict (name = “owners”) public void deleteOwner(int id); 43 Thursday, January 24, 13
  • 68.
    Servlet 3.0 BasedWeb Applications § Explicit support for Servlet 3.0 containers • such as Tomcat 7 and GlassFish 3 • while at the same time preserving compatibility with Servlet 2.4+ § Support for XML-free web application setup (no web.xml) • Servlet 3.0's ServletContainerInitializer mechanism • in combination with Spring 3.1's AnnotationConfigWebApplicationContext • plus Spring 3.1's environment abstraction § Exposure of native Servlet 3.0 functionality in Spring MVC • standard Servlet 3.0 file upload behind Spring's MultipartResolver abstraction • support for asynchronous request processing coming in Spring 3.2 44 Thursday, January 24, 13
  • 69.
    WebApplicationInitializer Example /** * Automatically detected and invoked on startup by Spring's ServletContainerInitializer. May register listeners, filters, servlets etc against the given Servlet 3.0 ServletContext. */ public class MyWebAppInitializer implements WebApplicationInitializer { public void onStartup(ServletContext sc) throws ServletException { // Create the 'root' Spring application context AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); root.scan("com.mycompany.myapp"); root.register(FurtherConfig.class); // Manages the lifecycle of the root application context sc.addListener(new ContextLoaderListener(root)); ... } } 45 Thursday, January 24, 13
  • 70.
    @MVC Processing &Flash Attributes 46 Thursday, January 24, 13
  • 71.
    @MVC Processing &Flash Attributes § RequestMethodHandlerAdapter l arbitrary mappings to handler methods across multiple controllers l better customization of handler method arguments − HandlerMethodArgumentResolver − HandlerMethodReturnValueHandler − etc 46 Thursday, January 24, 13
  • 72.
    @MVC Processing &Flash Attributes § RequestMethodHandlerAdapter l arbitrary mappings to handler methods across multiple controllers l better customization of handler method arguments − HandlerMethodArgumentResolver − HandlerMethodReturnValueHandler − etc § FlashMap support and FlashMapManager abstraction l with RedirectAttributes as a new @MVC handler method argument type − explicitly calling addFlashAttribute to add values to the output FlashMap l an outgoing FlashMap will temporarily get added to the user's session l an incoming FlashMap for a request will automatically get exposed to the model 46 Thursday, January 24, 13
  • 73.
    Refined JPA Support § Package scanning without persistence.xml l 'packagesToScan' feature on LocalContainerEntityManagerFactoryBean − building a persistence unit from @Entity classes within specific application packages l similar to AnnotationSessionFactoryBean for Hibernate 3 − rolled into core LocalSessionFactoryBean for Hibernate 4 l ideal for applications with a single default persistence unit § Consistent JPA setup by persistence unit name l JPA specification quite strongly based on the notion of persistence unit names − @PersistenceContext / @PersistenceUnit referring to persistence unit names l now Spring's JpaTransactionManager and co. support setup by unit name as well − as an alternative to referring to EntityManagerFactory beans directly − 47 Thursday, January 24, 13
  • 74.
    Third-Party Support Updates § Hibernate 4.0 l natively and through JPA l native support in a dedicated org.springframework.orm.hibernate4 package − dealing with package rearrangements in the Hibernate API l preserving compatibility with Hibernate 3.2+ in o.sf.orm.hibernate3 § Quartz 2.0 l JobDetail and Trigger are now interfaces in the Quartz 2.0 API − whereas they traditionally were base classes in Quartz 1.x l SchedulerFactoryBean now auto-adapts to Quartz 2.0 if present − JobDetail/CronTrigger/SimpleTriggerFactoryBean variants for Quartz 2.0 l preserving compatibility with Quartz 1.5+ in the same support package 48 Thursday, January 24, 13
  • 75.
    Java SE 7 49 Thursday, January 24, 13
  • 76.
    Java SE 7 § Spring 3.1 introduces Java SE 7 support l making best use of JRE 7 at runtime l support for JDBC 4.1 l support for fork-join framework 49 Thursday, January 24, 13
  • 77.
    Java SE 7 § Spring 3.1 introduces Java SE 7 support l making best use of JRE 7 at runtime l support for JDBC 4.1 l support for fork-join framework § Oracle's OpenJDK 7 released in summer 2011 l IBM JDK 7 following not much later l Java 7 could be the norm for new Java based projects soon 49 Thursday, January 24, 13
  • 78.
    Java SE 7 § Spring 3.1 introduces Java SE 7 support l making best use of JRE 7 at runtime l support for JDBC 4.1 l support for fork-join framework § Oracle's OpenJDK 7 released in summer 2011 l IBM JDK 7 following not much later l Java 7 could be the norm for new Java based projects soon 49 Thursday, January 24, 13
  • 79.
    Java SE 7 § Spring 3.1 introduces Java SE 7 support l making best use of JRE 7 at runtime l support for JDBC 4.1 l support for fork-join framework § Oracle's OpenJDK 7 released in summer 2011 l IBM JDK 7 following not much later l Java 7 could be the norm for new Java based projects soon § Spring Framework not being built against Java 7 yet l build upgrade coming in Spring 3.3 49 Thursday, January 24, 13
  • 80.
    github.com/SpringSource 50 Thursday, January 24, 13
  • 81.
    Spring 3.2 51 Thursday, January 24, 13
  • 82.
    Current and Upcoming:3.1, 3.2, and 3.2 § Spring Framework 3.1 (Dec 2011) • Environment profiles, Java-based configuration, declarative caching • Initial Java 7 support, Servlet 3.0 based deployment § Spring Framework 3.2 (Dec 2012) • Gradle-based build, GitHub-based contribution model • Fully Java 7 oriented, async MVC processing on Servlet 3.0 § Spring Framework 3.3 (Q4 2013) • Comprehensive Java SE 8 support (including lambda expressions) • Single abstract method types in Spring are well positioned • Support for Java EE 7 API level and WebSockets 52 Thursday, January 24, 13
  • 83.
    Change of Plans § We originally meant to have Java SE 8 and Java EE 7 themes in Spring 3.2 § However, Java EE 7 got pushed out further and further: Q2 2013 • eventually descoped and delayed (no cloud focus anymore) § And Java SE 8 (OpenJDK 8) got rescheduled as well: September 2013 • once again, descoped and delayed (no module system anymore) • feature-complete developer preview expected for February 2013 § Our solution: Spring 3.2 ships in Q4 2012 with core framework refinements • Spring 3.3 will ship in Q4 2013 with Java SE 8 and Java EE 7 support 53 Thursday, January 24, 13
  • 84.
    So what’s in3.2? § Gradle-based build § Binaries built against Java 7 § Inlined ASM 4.0 and CGLIB 3.0 § Async MVC processing on Servlet 3.0 § Spring MVC test support § MVC configuration refinements § SpEL refinements § Also including many runtime refinements • partially back-ported to 3.1.2/3.1.3 § General Spring MVC niceties • Servlet 3 async support • error reporting in REST scenarios • content negotiation strategies • matrix variables 54 Thursday, January 24, 13
  • 85.
    Spring 3.2 § Spring 3.1 came with early support for Java 7 • JDBC 4.1, ForkJoinPool, etc • framework itself still compiled on Java 6 § Spring 3.2 is now being built on Java 7 • CI builds running against Java 5, 6 and 7 § enabled through our new Gradle build § Spring 3.2 comes with ASM 4.0 and CGLIB 3.0 • fully supporting the Java 7 byte code format • ASM and CGLIB inlined into Spring module jars now 55 Thursday, January 24, 13
  • 86.
    Async MVC Processing:Callable @RequestMapping(name =“/upload”, method=RequestMethod.POST) public Callable<String> processUpload(MultipartFile file) { return new Callable<String>() { public String call() throws Exception { // ... return "someView"; } }; } - thread managed by Spring MVC - good for long running database jobs, 3rd party REST API calls, etc 56 Thursday, January 24, 13
  • 87.
    Async MVC Processing:DeferredResult @RequestMapping("/quotes") @ResponseBody public DeferredResult quotes() { DeferredResult deferredResult = new DeferredResult(); // Add deferredResult to a Queue or a Map... return deferredResult; } // In some other thread: // Set the return value on the DeferredResult deferredResult.set(data); - thread managed outside of Spring MVC - JMS or AMQP message listener, another HTTP request, etc. 57 Thursday, January 24, 13
  • 88.
    Async MVC Processing:AsyncTask @RequestMapping(name =“/upload”, method=RequestMethod.POST) public AsyncTask<Foo> processUpload(MultipartFile file) { TaskExecutor asyncTaskExecutor = new AsyncTaskExecutor(...); return new AsyncTask<Foo>( 1000L, // timeout asyncTaskExecutor, // thread pool new Callable<Foo>(){ ..} // thread ); } - same as Callable, with extra features - override timeout value for async processing - lets you specify a specific AsyncTaskExecutor 58 Thursday, January 24, 13
  • 89.
    Content Negotiation Strategies ContentNegotiationStrategy • By 'Accept' Header • By URL extension (.xml, .json, etc) • By Request parameter, i.e. /accounts/1?format=json • Fixed content type, i.e. a fallback option ContentNegotiationManager • has one or more ContentNegotiationStrategy instances • works with: RequestMappingHandlerMapping, RequestMappingHandlerAdapter, ExceptionHandlerExceptionResolver ContentNegotiatingViewResolver 59 Thursday, January 24, 13
  • 90.
    Matrix Variables "Each path segment may include a sequence of parameters, indicated by the semicolon ";" character. The parameters are not significant to the parsing of relativeb references. RFC 2396, section 3.3 60 Thursday, January 24, 13
  • 91.
    Matrix Variables "The semicolon (";") and equals ("=") reserved characters are often used to delimit parameters and parameter values applicable to that segment. The comma (",") reserved character is often used for similar purposes." RFC 3986, section 3.3 61 Thursday, January 24, 13
  • 92.
    Matrix Variables § Two Types of Usages § Path Segment Name-Value Pairs /qa-releases;buildNumber=135;revision=3.2 § As delimited list path segment /answers/id1;id2;id3;id4/comments 62 Thursday, January 24, 13
  • 93.
    Matrix Variables: thecommon case // GET /pets/42;q=11;r=22 @RequestMapping(value = "/pets/{petId}") public void findPet( @PathVariable String petId, @MatrixVariable int q) { // petId == 42 // q == 11 } 63 Thursday, January 24, 13
  • 94.
    Matrix Variables: obtainall matrix variables // GET /owners/42;q=11;r=12/pets/21;q=22;s=23 @RequestMapping(value = "/owners/{ownerId}/pets/{petId}") public void findPet( @MatrixVariable Map<String, String> matrixVars) { // matrixVars: ["q" : [11,22], "r" : 12, "s" : 23] } 64 Thursday, January 24, 13
  • 95.
    Matrix Variables: qualifypath segment // GET /owners/42;q=11/pets/21;q=22 @RequestMapping(value = "/owners/{ownerId}/pets/{petId}") public void findPet( @MatrixVariable(value="q", pathVar="ownerId") int q1, @MatrixVariable(value="q", pathVar="petId") int q2) { // q1 == 11 // q2 == 22 } 65 Thursday, January 24, 13
  • 96.
    Spring 3.3... 66 Thursday, January 24, 13
  • 97.
    Current and Upcoming:3.1, 3.2, and 3.2 § Spring Framework 3.1 (Dec 2011) • Environment profiles, Java-based configuration, declarative caching • Initial Java 7 support, Servlet 3.0 based deployment § Spring Framework 3.2 (Dec 2012) • Gradle-based build, GitHub-based contribution model • Fully Java 7 oriented, async MVC processing on Servlet 3.0 § Spring Framework 3.3 (Q4 2013) • Comprehensive Java SE 8 support (including lambda expressions) • Single abstract method types in Spring are well positioned • Support for Java EE 7 API level and WebSockets 67 Thursday, January 24, 13
  • 98.
    Spring Framework 3.3(Q4 2013) § Comprehensive Java 8 support • Support for Java EE 7 API levels • Focus on message-oriented architectures • annotation-driven JMS endpoint model § revised application event mechanism § WebSocket support in Spring MVC § Next-generation Groovy support § Grails bean builder finally making it into Spring proper § PROBABLY (but can’t say for sure): this will be Spring 4.0 68 Thursday, January 24, 13
  • 99.
    The Java SE8 Story § Comprehensive Java 8 support • lambda expressions a.k.a. closures • Date and Time API (JSR-310) • NIO-based HTTP client APIs • parameter name discovery • java.util.concurrent enhancements § Retaining support for Java 5 and higher • with Java 6 and 7 as common levels • Java 8 potentially becoming popular rather quickly... 69 Thursday, January 24, 13
  • 100.
    The Java EE7 Story § Support for Java EE 7 API levels • JCache 1.0 • JMS 2.0 • JPA2.1 • JTA 1.2 (@Transactional) • Bean Validation 1.1 • Servlet3.1 • JSF 2.2 § Retaining support for Java EE 5 and higher 70 Thursday, January 24, 13
  • 101.
    Annotation Driven JMSEndpoints @JmsListener(destination="myQueue") public void handleMessage(TextMessage payload); @JmsListener(destination="myQueue", selector="...") public void handleMessage(String payload); @JmsListener(destination="myQueue") public String handleMessage(String payload); 71 Thursday, January 24, 13
  • 102.
    WebSocket Support § WebSocket support in current servers isn't fully standardized yet § JSR-356 upcoming within the Java EE 7 timeframe § Jetty 9 and co. to adopt it rather quickly § Spring Framework 3.3 to research all options for WebSocket support • primarily in Spring MVC • but also generally for message-oriented architectures 72 Thursday, January 24, 13
  • 103.
    Current and Upcoming:3.1, 3.2, and 3.2 § Spring Framework 3.1 (Dec 2011) • Environment profiles, Java-based configuration, declarative caching • Initial Java 7 support, Servlet 3.0 based deployment § Spring Framework 3.2 (Dec 2012) • Gradle-based build, GitHub-based contribution model • Fully Java 7 oriented, async MVC processing on Servlet 3.0 § Spring Framework 3.3 (Q4 2013) • Comprehensive Java SE 8 support (including lambda expressions) • Support for Java EE 7 API level and WebSockets 73 Thursday, January 24, 13
  • 104.
    @SpringSource @Starbuxman Questions? NOT CONFIDENTIAL -- TELL EVERYONE Thursday, January 24, 13