SlideShare a Scribd company logo
Spring 3.1

© Zenika 2011       Spring 3.1   1
Speaker's qualifications


     • Arnaud Cogoluègnes
          •     Consultant with Zenika
          •     Has been using Spring since 2005
          •     SpringSource certified trainer
          •     Co-author:
                 • Spring par la pratique, 2nd edition
                 • Spring Dynamic Modules in Action
                 • Spring Batch in Action




© Zenika 2011                                  Spring 3.1   2
Agenda


     •   History
     •   Environment
     •   Java configuration
     •   Spring JPA
     •   Cache abstraction
     •   Spring MVC improvements




© Zenika 2011                      Spring 3.1   3
History


     •   v. 0.9 : june 2003 (foundations)
     •   v. 1.0 : march 2004
     •   v. 1.1 : september 2004
     •   v. 1.2 : may 2005
     •   v. 2.0 : october 2006 (XML namespaces)
     •   v. 2.5 : november 2007 (annotations)
     •   v. 3.0 : décember 2009 (Java config, SpEL, REST)




© Zenika 2011                      Spring 3.1               4
Environment


     • Inside the application context



                            Environment

                Property Source                  Profile
                 Property Source                  Profile




© Zenika 2011                       Spring 3.1              5
Environment / Property Source


     • Do you know this?

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

   <bean id="dataSource"
         class="org.apache.commons.dbcp.BasicDataSource">
     <property name="driverClassName" value="${db.driver}" />
     <property name="url" value="jdbc:${db.url}" />
     <property name="username" value="${db.user}" />
     <property name="password" value="${db.password}" />
   </bean>

                     database.properties
                     db.driver=org.h2.driver
                     db.url=jdbc:h2:mem:db1
                     db.user=sa
                     db.password=

© Zenika 2011                     Spring 3.1                        6
Environment / Property Source


     • Spring 3.1 introduces an abstraction for property sources
     • But what is a PropertySource anyway?


                                   db.driver=org.h2.driver
                                   db.url=jdbc:h2:mem:db1
      Property Source         =    db.user=sa
                                   db.password=




© Zenika 2011                      Spring 3.1                      7
Environment / PropertySource


     • Where do PropertySources come from?
                                              System and environment
                                                     variables
           Properties files                         Properties
                                                  PropertySource
               Resource
            PropertySource

                                  Servlet context and config
                    JNDI               ServletContext/Config
                                          PropertySource
                     Jndi
                PropertySource



© Zenika 2011                    Spring 3.1                            8
Environment / Property Source


     • How to refer to PropertySource?



       <bean id="dataSource"
             class="org.apache.commons.dbcp.BasicDataSource"
             destroy-method="close">
         <property name="driverClass" value="${db.driver}"/>
         <property name="jdbcUrl" value="${db.url}"/>
         <property name="username" value="${db.user}"/>
         <property name="password" value="${db.password}"/>
       </bean>




© Zenika 2011                      Spring 3.1                  9
Environment / Property Source


     • How to refer to PropertySource?

       @Configuration
       public class DatabaseConfiguration {

            @Value("${db.driver}") private String driver;
            @Value("${db.url}") private String url;
            @Value("${db.user}") private String user;
            @Value("${db.password}") private String password;

            @Bean public DataSource dataSource() {
              // creates DataSource
              return dataSource;
            }

       }



© Zenika 2011                         Spring 3.1                10
Environment / PropertySource


     • How to define a PropertySource ?




       <context:property-placeholder
               location="classpath:application.properties" />




© Zenika 2011                      Spring 3.1                   11
Environment / PropertySource


     • How to define a PropertySource ?



       <context:property-placeholder
               properties-ref="applicationProperties" />

       <util:properties id="applicationProperties">
         <prop key="db.driver">org.h2.Driver</prop>
         <prop key="db.url">jdbc:h2:mem:db1</prop>
         <prop key="db.user">sa</prop>
         <prop key="db.password"></prop>
       </util:properties>




© Zenika 2011                      Spring 3.1              12
Environment / PropertySource


     • How to define a PropertySource ?

      <context-param>
             <param-name>contextInitializerClasses</param-name>
             <param-value>com.zenika.SomeInitializer</param-value>
      </context-param>


      public class SomeInitializer
             implements ApplicationContextInitializer
                        <ConfigurableApplicationContext> {

           public void initialize(
                         ConfigurableApplicationContext ctx) {
             PropertySource ps = ...
             ctx.getEnvironment().getPropertySources().addFirst(ps);
           }

      }
© Zenika 2011                        Spring 3.1                        13
Environment / PropertySource


     • Unified way to deal with properties
     • More flexible than simple property placeholder
        • Configurable programmatically, useful for test configs
     • Part of the new Environment abstraction




© Zenika 2011                         Spring 3.1                   14
Environment / Profile




                           Environment

                Property Source                 Profile
                 Property Source                 Profile




© Zenika 2011                      Spring 3.1              15
Environment / Profile



                       Application Context

                    Service                  Repository


         "dev" profile                  "prod" profile

                Datasource                      Datasource




© Zenika 2011                   Spring 3.1                   16
Environment / Profile


     • Different beans for different environments


    <bean class="com.zenika.ContactDao">
      <constructor-arg ref="dataSource" />
    </bean>

    <beans profile="test">
      <jdbc:embedded-database id="dataSource" type="H2" />
    </beans>

    <beans profile="prod">
      <jee:jndi-lookup id="ds"
                       jndi-name="java:comp/env/jdbc/ds" />
    </beans>




© Zenika 2011                      Spring 3.1                 17
Environment / Profile


     • Let's reach the clouds!


  <bean class="com.zenika.ContactDao">
    <constructor-arg ref="dataSource" />
  </bean>

  <beans profile="dev">
    <jdbc:embedded-database id="dataSource" type="H2" />
  </beans>

  <beans profile="cloud">
    <cloud:data-source id="dataSource" service-name="contactDs"/>
  </beans>




© Zenika 2011                    Spring 3.1                         18
Environment / Profile


     • Creating the application context for the test profile



    GenericXmlApplicationContext ctx =
      new GenericXmlApplicationContext();
    ctx.getEnvironment().setActiveProfiles("test");
    ctx.load("classpath:/application-context.xml");
    ctx.refresh();




© Zenika 2011                        Spring 3.1                19
Environment / Profile


     • Activating a profile declaratively




    -Dspring.profiles.active="prod"




© Zenika 2011                        Spring 3.1   20
Environment / Profile


     • Bootstrapping with the TestContext framework

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration("classpath:/application-context.xml")
    @ActiveProfiles("test")
    public class ProfileTest {

        @Autowired private ContactDao contactDao;


        @Test public void getContact() throws Exception {
          ...
        }

    }




© Zenika 2011                      Spring 3.1                     21
Environment / Profile


     • Just « prod » profile



    <bean class="com.zenika.spring31.ContactDao">
      <constructor-arg ref="dataSource" />
    </bean>

    <beans profile="prod">
      <jee:jndi-lookup id="ds"
                       jndi-name="java:comp/env/jdbc/ds" />
    </beans>




© Zenika 2011                    Spring 3.1                   22
Environment / Profile


     • Override what you need in the test
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(
      loader=AnnotationConfigContextLoader.class
    )
    public class SpecialProfileTest {

        @Autowired private ContactDao contactDao;

        @Test public void getContact() throws Exception {
          ...
        }

        @Configuration
        @ImportResource("classpath:/application-context.xml")
        static class ContextConfiguration {
          @Bean public DataSource dataSource() {
            return new EmbeddedDatabaseBuilder().build();
          }
        }
    }

© Zenika 2011                          Spring 3.1               23
Java configuration


     • Nothing equivalent to XML namespaces so far...



    @Transactional
    @Repository
    public class HibernateContactRepo { ... }

    <context:component-scan base-package="com.zenika" />

    <tx:annotation-driven />




© Zenika 2011                    Spring 3.1                24
Java configuration


     • Annotations equivalent to common XML shortcuts



    @Transactional
    @Repository
    public class HibernateContactRepo { ... }

    @Configuration
    @EnableTransactionManagement
    @ComponentScan(basePackageClasses=HibernateContactRepo.class)
    public class ContextConfiguration { ... }




© Zenika 2011                    Spring 3.1                         25
Java configuration


     • Annotations equivalent to common XML shortcuts
    @Configuration
    @EnableTransactionManagement
    @ComponentScan(basePackageClasses=HibernateContactRepo.class)
    public class ContextConfiguration {

        @Bean public SessionFactory sf() throws Exception {
          return new AnnotationSessionFactoryBuilder()
            .setDataSource(dataSource())
            .setPackagesToScan(Contact.class.getPackage().getName())
            .buildSessionFactory();
        }

        @Bean public PlatformTransactionManager tm() throws Exception {
          return new HibernateTransactionManager(sf());
        }

        @Bean public DataSource dataSource() {
          return new EmbeddedDatabaseBuilder()
            .setType(EmbeddedDatabaseType.H2).build();
        }

    }
© Zenika 2011                          Spring 3.1                         26
Spring JPA


     • More support for persistence in Spring JPA

    public interface ContactRepository
           extends JpaRepository<Contact, Long> { }

    <jpa:repositories base-package="com.zenika.jpa" />


    long initialCount = contactRepo.count();
    Contact contact = new Contact();
    contact.setFirstname("Arnaud");
    contact.setLastname("Cogoluègnes");
    contactRepo.save(contact);
    Assert.assertEquals(initialCount+1, contactRepo.count());




© Zenika 2011                     Spring 3.1                    27
Spring JPA


     • Define your own method, following conventions



    public interface ContactRepository
                     extends JpaRepository<Contact, Long> {

        List<Contact> findByFirstname(String firstname);

    }
  List<Contact> contacts = contactRepo.findByFirstname("Arnaud");




© Zenika 2011                      Spring 3.1                   28
Spring JPA


      • Define JPQL queries for methods


  public interface ContactRepository
                   extends JpaRepository<Contact, Long> {

      @Query("from Contact c where lower(c.firstname) = lower(?1)")
      List<Contact> find(String search);

  }
   List<Contact> contacts = contactRepo.find("arnaud");




© Zenika 2011                     Spring 3.1                          29
Spring JPA


     • Built-in support for pagination



   Pageable request = new PageRequest(1,2,new Sort("lastname"));
   Page<Contact> page = contactRepo.findAll(request);

   List<Contact> contacts = page.getContent();
   long total = page.getTotalElements();
   long number = page.getNumberOfElements();




© Zenika 2011                       Spring 3.1                     30
Quick note on Spring Data


     • Spring JPA is part of the Spring Data project
     • Spring Data is an umbrella project
     • Spring Data provides Spring support for « new » data
       access technologies
        • MongoDB, Neo4j, Riak, Redis, Hadoop
     • Support planned for additional NoSQL technologies
        • HBase, Cassandra, CouchDB
     • Don't hesitate to check out Spring Data!
        • http://www.springsource.org/spring-data




© Zenika 2011                     Spring 3.1                  31
Cache support in Spring 3.1


     • What about some transparent cache on method calls?

   public interface ContactRepository
                    extends JpaRepository<Contact, Long> {

       Contact findOne(Long id);

   }

   Contact contact = contactRepo.findOne(contact.getId());
   contact = contactRepo.findOne(contact.getId());

   Hibernate: select contact0_.id as id0_0_, ...
   Hibernate: select contact0_.id as id0_0_, ...




© Zenika 2011                      Spring 3.1                32
Cache support in Spring 3.1


     • Let's combine Spring JPA and Spring 3.1's cache support !
          • NB: the cache support works on any kinds of beans
   public interface ContactRepository
                    extends JpaRepository<Contact, Long> {

       @Cacheable("contacts")
       Contact findOne(Long id);

   }

   Contact contact = contactRepo.findOne(contact.getId());
   contact         = contactRepo.findOne(contact.getId());

   Hibernate: select contact0_.id as id0_0_, ...



© Zenika 2011                         Spring 3.1                   33
Cache support in Spring 3.1


     • This is how to configure the cache


   <cache:annotation-driven />

   <bean id="cacheManager"
         class="o.s.cache.support.SimpleCacheManager">
     <property name="caches">
       <set>
         <bean class="o.s.cache.concurrent.ConcurrentMapCache"
               c:name="contacts" />
       </set>
     </property>
   </bean>




© Zenika 2011                      Spring 3.1                    34
Cache support in Spring 3.1


     • The cache support is an abstraction
     • The Spring Framework provides implementations
          • SimpleCacheManager
             • Uses collections of caches
             • Useful for testing or small, non-distributed environments
          • EhCacheCacheManager
             • Backed up by Ehcache
     • The Spring Gemfire project ships with an implementation




© Zenika 2011                              Spring 3.1                      35
Cache support in Spring 3.1


     • Can use expression for keys
   public interface ContactRepository
                    extends JpaRepository<Contact, Long> {

       @Cacheable(value="contacts",key="#p0+'.'+#p1")
       Contact findByLastnameAndFirstname(String lastname,
                                          String firstname);

   }
   Contact contact = contactRepo.findByLastnameAndFirstname(
     "Cogoluègnes", "Arnaud");
   contact         = contactRepo.findByLastnameAndFirstname(
     "Cogoluègnes", "Arnaud");

   Hibernate: select contact0_.id as id0_, ...



© Zenika 2011                      Spring 3.1                  36
Cache support in Spring 3.1


     • Method can do some housekeeping with @CacheEvict


   @Transactional
   public interface ContactRepository
                    extends JpaRepository<Contact, Long> {

       @Cacheable("contacts")
       Contact findOne(Long id);

       @CacheEvict(value="contacts",key="#p0.id")
       Contact save(Contact contact);

   }




© Zenika 2011                      Spring 3.1                37
Cache support in Spring 3.1


     • Spring's cache support can be used
          • on the data access layer
             • replaces 2nd level cache or provides cache for a JDBC-based
                layer
          • at the web tier level
             • caches business services calls or web services calls




© Zenika 2011                            Spring 3.1                          38
Spring MVC enhancements


     • Easier registration of HttpMessageConverters
     • But what is a HttpMessageConverter anyway?
     • HttpMessageConverters are used in Spring's REST
       support
          • Java object to HTTP response conversion
             • From Java to XML, JSON, etc.
          • HTTP request to Java object conversion
             • From XML, JSON to Java
     • On the server but on the client side as well...




© Zenika 2011                         Spring 3.1         39
Spring MVC enhancements


     • Easier registration with a dedicated XML tag
          • Used to be directly at the HandlerAdapter level



  <mvc:annotation-driven>
    <mvc:message-converters register-defaults="false">
      <bean class="com.zenika.web.ContactHttpMessageConverter" />
    </mvc:message-converters>
  </mvc:annotation-driven>




© Zenika 2011                         Spring 3.1                    40
Spring MVC enhancements


      • Java-based configuration
          • Same as <mvc:annotation-driven />

  @Configuration
  @EnableWebMvc
  public class WebConfig extends WebMvcConfigurerAdapter {

       @Override
       public void configureMessageConverters(
                     List<HttpMessageConverter<?>> converters) {
         converters.add(new ContactHttpMessageConverter());
       }

  }




© Zenika 2011                         Spring 3.1                   41
Spring MVC enhancements


      • Big refactoring on the way to process annotations


  @Controller
  public class ContactController {

       @Autowired private ContactRepository repo;

       @RequestMapping(value="/contacts/{id}",
                       method=RequestMethod.GET
       )
       @ResponseBody
       public Contact get(@PathVariable Long id) {
         return repo.findOne(id);
       }

  }


© Zenika 2011                      Spring 3.1               42
Spring MVC enhancements


     • Who used to process annotations like @RequestMapping,
       @RequestParam, etc?
     • Answer: the AnnotationMethodHandlerAdapter.
     • Processing was hard-coded in the class
     • Spring 3.1 introduced the HandlerMethod abstraction
          • RequestMappingHandlerMapping
          • RequestMappingHandlerAdapter




© Zenika 2011                   Spring 3.1                     43
Spring MVC enhancements


     • Consequences of the HandlerMethod abstraction
          • Backward compatible (@RequestMapping, @RequestParam
            & co).
          • More fine-grained control over controller method execution
          • Possible interception around the invocation of the controller
          • Pluggable mechanism on method argument
                • You can create your own @RequestParam-like annotations!
                • Check the HandlerMethodArgumentResolver and
                  HandlerMethodReturnValueHandler interfaces




© Zenika 2011                              Spring 3.1                       44
Support for Servlet 3.0


     • Servlet 3.0 allows for programmatic registration
        • ServletContext.addServlet(String, Servlet)
        • ServletContext.addFilter(String, Filter)
     • Hook for frameworks
        • ServletContainerInitializer
        • Implementations listed in META-INF/services
     • In Spring: SpringServletContainerInitializer




© Zenika 2011                      Spring 3.1             45
Support for Servlet 3.0


     • SpringServletContainerInitializer triggers
       WebApplicationInitializers
     • WebApplicationInitializer
          • The API to use
          • Detected and called by Spring (through the web container)
          • Used for initialization
                • Registering a DispatcherServlet
                • Bootstrapping the Spring ApplicationContext




© Zenika 2011                            Spring 3.1                     46
Support for Servlet 3.0


      • No need of web.xml anymore
  public class ZenContactInitializer
         implements WebApplicationInitializer {

      @Override
      public void onStartup(ServletContext sc) throws ServletException {
        AnnotationConfigWebApplicationContext rootContext =
          new AnnotationConfigWebApplicationContext();
        rootContext.register(WebConfig.class);
        sc.addListener(new ContextLoaderListener(rootContext));

          AnnotationConfigWebApplicationContext dispatcherContext =
            new AnnotationConfigWebApplicationContext();
          dispatcherContext.register(DispatcherConfig.class);

          ServletRegistration.Dynamic dispatcher = sc.addServlet(
            "dispatcher", new DispatcherServlet(dispatcherContext));
          dispatcher.setLoadOnStartup(1);
          dispatcher.addMapping("/main");
      }
  }

© Zenika 2011                           Spring 3.1                         47
Resources

     • Summary
          • http://blog.springsource.com/2011/02/11/spring-framework-3-1-m1-released/
          • http://blog.springsource.com/2011/06/09/spring-framework-3-1-m2-released/
     • Environment
          • http://blog.springsource.com/2011/02/14/spring-3-1-m1-introducing-profile/
          • http://blog.springsource.com/2011/06/21/spring-3-1-m2-testing-with-configuration-
            classes-and-profiles/
          • http://blog.springsource.com/2011/02/15/spring-3-1-m1-unified-property-management/
     • Cache abstraction
          • http://blog.springsource.com/2011/02/23/spring-3-1-m1-caching/
     • Spring JPA
          • http://blog.springsource.com/2011/02/10/getting-started-with-spring-data-jpa/
          • http://blog.springsource.com/2011/07/27/fine-tuning-spring-data-repositories/
     • Spring MVC
          • http://blog.springsource.com/2011/02/21/spring-3-1-m1-mvc-namespace-
            enhancements-and-configuration/
          • http://blog.springsource.com/2011/06/13/spring-3-1-m2-spring-mvc-enhancements-2/
© Zenika 2011                                      Spring 3.1                                    48
Questions ?




© Zenika 2011        Spring 3.1   49

More Related Content

PPTX
Spring dependency injection
ODP
Dependency Injection in Spring in 10min
PPTX
A first Draft to Java Configuration
ODP
Java EE and Glassfish
PPTX
Architecting virtualized infrastructure for big data presentation
PDF
PDF
Big data: current technology scope.
PDF
Owner - Java properties reinvented.
Spring dependency injection
Dependency Injection in Spring in 10min
A first Draft to Java Configuration
Java EE and Glassfish
Architecting virtualized infrastructure for big data presentation
Big data: current technology scope.
Owner - Java properties reinvented.

What's hot (19)

PDF
5050 dev nation
PDF
Hadoop 101
PDF
Java Web Programming Using Cloud Platform: Module 3
DOC
Sel study notes
PPTX
Advance java session 5
PDF
Understanding
PPTX
Connection Pooling
PDF
Effiziente Datenpersistierung mit JPA 2.1 und Hibernate
PPSX
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
ODP
Spring 4 final xtr_presentation
PDF
Configure Your Projects with Apache Tamaya
PDF
the Spring 4 update
PPTX
Java database connectivity
PPTX
Entity Framework Database and Code First
PPTX
DataBase Connectivity
PPS
Java Hibernate Programming with Architecture Diagram and Example
PDF
Lecture 5 JSTL, custom tags, maven
PDF
Weblogic Administration Managed Server migration
PPT
Spring Core
5050 dev nation
Hadoop 101
Java Web Programming Using Cloud Platform: Module 3
Sel study notes
Advance java session 5
Understanding
Connection Pooling
Effiziente Datenpersistierung mit JPA 2.1 und Hibernate
Spring - Part 2 - Autowiring, Annotations, Java based Configuration - slides
Spring 4 final xtr_presentation
Configure Your Projects with Apache Tamaya
the Spring 4 update
Java database connectivity
Entity Framework Database and Code First
DataBase Connectivity
Java Hibernate Programming with Architecture Diagram and Example
Lecture 5 JSTL, custom tags, maven
Weblogic Administration Managed Server migration
Spring Core
Ad

Viewers also liked (9)

PDF
Chti Jug Octo 16032010 Réduisons le ticket d’entrée de nos projets
PDF
Adobe flash platform java
PPTX
Bonita Open Solution
PDF
MC3SI Chti Jug Soiree Agilite
PDF
Agile Day Tunisia 2012 - Agile entre opportunités et résistance
PDF
Java 8 : Un ch'ti peu de lambda
PPTX
Retrospectives agiles - fiches pratiques
PDF
Jolocom contribution to the AGILE-IoT project
PDF
Fundamentals of Agile Methodologies - Part I
Chti Jug Octo 16032010 Réduisons le ticket d’entrée de nos projets
Adobe flash platform java
Bonita Open Solution
MC3SI Chti Jug Soiree Agilite
Agile Day Tunisia 2012 - Agile entre opportunités et résistance
Java 8 : Un ch'ti peu de lambda
Retrospectives agiles - fiches pratiques
Jolocom contribution to the AGILE-IoT project
Fundamentals of Agile Methodologies - Part I
Ad

Similar to Spring 3.1 (20)

PPTX
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012
PDF
Spring Day | Spring 3.1 in a Nutshell | Sam Brannen
PDF
Spring 3.1 in a Nutshell - JAX London 2011
PPT
Spring 3.1: a Walking Tour
PDF
Spring 3.1 in a Nutshell
PDF
Lo nuevo en Spring 3.0
PDF
The Spring 4 Update - Josh Long
PDF
Spring 3.1 Features Worth Knowing About
PDF
Spring ME JavaOne
PDF
Spring 3 - An Introduction
PDF
Spring design-juergen-qcon
KEY
A Walking Tour of (almost) all of Springdom
PPT
Spring talk111204
PDF
MongoDB for Java Devs with Spring Data - MongoPhilly 2011
PPT
Spring Basics
PPTX
Lightweight J2EE development with Spring (special for UADEV)
PPTX
Spring framework
PDF
Spring
PDF
Spring
PDF
Spring
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012
Spring Day | Spring 3.1 in a Nutshell | Sam Brannen
Spring 3.1 in a Nutshell - JAX London 2011
Spring 3.1: a Walking Tour
Spring 3.1 in a Nutshell
Lo nuevo en Spring 3.0
The Spring 4 Update - Josh Long
Spring 3.1 Features Worth Knowing About
Spring ME JavaOne
Spring 3 - An Introduction
Spring design-juergen-qcon
A Walking Tour of (almost) all of Springdom
Spring talk111204
MongoDB for Java Devs with Spring Data - MongoPhilly 2011
Spring Basics
Lightweight J2EE development with Spring (special for UADEV)
Spring framework
Spring
Spring
Spring

Recently uploaded (20)

PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
cuic standard and advanced reporting.pdf
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
Network Security Unit 5.pdf for BCA BBA.
PPTX
A Presentation on Artificial Intelligence
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Review of recent advances in non-invasive hemoglobin estimation
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPTX
MYSQL Presentation for SQL database connectivity
Spectral efficient network and resource selection model in 5G networks
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Advanced methodologies resolving dimensionality complications for autism neur...
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Chapter 3 Spatial Domain Image Processing.pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
cuic standard and advanced reporting.pdf
The Rise and Fall of 3GPP – Time for a Sabbatical?
NewMind AI Weekly Chronicles - August'25 Week I
Agricultural_Statistics_at_a_Glance_2022_0.pdf
NewMind AI Monthly Chronicles - July 2025
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
Network Security Unit 5.pdf for BCA BBA.
A Presentation on Artificial Intelligence
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Review of recent advances in non-invasive hemoglobin estimation
“AI and Expert System Decision Support & Business Intelligence Systems”
MYSQL Presentation for SQL database connectivity

Spring 3.1

  • 1. Spring 3.1 © Zenika 2011 Spring 3.1 1
  • 2. Speaker's qualifications • Arnaud Cogoluègnes • Consultant with Zenika • Has been using Spring since 2005 • SpringSource certified trainer • Co-author: • Spring par la pratique, 2nd edition • Spring Dynamic Modules in Action • Spring Batch in Action © Zenika 2011 Spring 3.1 2
  • 3. Agenda • History • Environment • Java configuration • Spring JPA • Cache abstraction • Spring MVC improvements © Zenika 2011 Spring 3.1 3
  • 4. History • v. 0.9 : june 2003 (foundations) • v. 1.0 : march 2004 • v. 1.1 : september 2004 • v. 1.2 : may 2005 • v. 2.0 : october 2006 (XML namespaces) • v. 2.5 : november 2007 (annotations) • v. 3.0 : décember 2009 (Java config, SpEL, REST) © Zenika 2011 Spring 3.1 4
  • 5. Environment • Inside the application context Environment Property Source Profile Property Source Profile © Zenika 2011 Spring 3.1 5
  • 6. Environment / Property Source • Do you know this? <context:property-placeholder location="database.properties"/> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="${db.driver}" /> <property name="url" value="jdbc:${db.url}" /> <property name="username" value="${db.user}" /> <property name="password" value="${db.password}" /> </bean> database.properties db.driver=org.h2.driver db.url=jdbc:h2:mem:db1 db.user=sa db.password= © Zenika 2011 Spring 3.1 6
  • 7. Environment / Property Source • Spring 3.1 introduces an abstraction for property sources • But what is a PropertySource anyway? db.driver=org.h2.driver db.url=jdbc:h2:mem:db1 Property Source = db.user=sa db.password= © Zenika 2011 Spring 3.1 7
  • 8. Environment / PropertySource • Where do PropertySources come from? System and environment variables Properties files Properties PropertySource Resource PropertySource Servlet context and config JNDI ServletContext/Config PropertySource Jndi PropertySource © Zenika 2011 Spring 3.1 8
  • 9. Environment / Property Source • How to refer to PropertySource? <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClass" value="${db.driver}"/> <property name="jdbcUrl" value="${db.url}"/> <property name="username" value="${db.user}"/> <property name="password" value="${db.password}"/> </bean> © Zenika 2011 Spring 3.1 9
  • 10. Environment / Property Source • How to refer to PropertySource? @Configuration public class DatabaseConfiguration { @Value("${db.driver}") private String driver; @Value("${db.url}") private String url; @Value("${db.user}") private String user; @Value("${db.password}") private String password; @Bean public DataSource dataSource() { // creates DataSource return dataSource; } } © Zenika 2011 Spring 3.1 10
  • 11. Environment / PropertySource • How to define a PropertySource ? <context:property-placeholder location="classpath:application.properties" /> © Zenika 2011 Spring 3.1 11
  • 12. Environment / PropertySource • How to define a PropertySource ? <context:property-placeholder properties-ref="applicationProperties" /> <util:properties id="applicationProperties"> <prop key="db.driver">org.h2.Driver</prop> <prop key="db.url">jdbc:h2:mem:db1</prop> <prop key="db.user">sa</prop> <prop key="db.password"></prop> </util:properties> © Zenika 2011 Spring 3.1 12
  • 13. Environment / PropertySource • How to define a PropertySource ? <context-param> <param-name>contextInitializerClasses</param-name> <param-value>com.zenika.SomeInitializer</param-value> </context-param> public class SomeInitializer implements ApplicationContextInitializer <ConfigurableApplicationContext> { public void initialize( ConfigurableApplicationContext ctx) { PropertySource ps = ... ctx.getEnvironment().getPropertySources().addFirst(ps); } } © Zenika 2011 Spring 3.1 13
  • 14. Environment / PropertySource • Unified way to deal with properties • More flexible than simple property placeholder • Configurable programmatically, useful for test configs • Part of the new Environment abstraction © Zenika 2011 Spring 3.1 14
  • 15. Environment / Profile Environment Property Source Profile Property Source Profile © Zenika 2011 Spring 3.1 15
  • 16. Environment / Profile Application Context Service Repository "dev" profile "prod" profile Datasource Datasource © Zenika 2011 Spring 3.1 16
  • 17. Environment / Profile • Different beans for different environments <bean class="com.zenika.ContactDao"> <constructor-arg ref="dataSource" /> </bean> <beans profile="test"> <jdbc:embedded-database id="dataSource" type="H2" /> </beans> <beans profile="prod"> <jee:jndi-lookup id="ds" jndi-name="java:comp/env/jdbc/ds" /> </beans> © Zenika 2011 Spring 3.1 17
  • 18. Environment / Profile • Let's reach the clouds! <bean class="com.zenika.ContactDao"> <constructor-arg ref="dataSource" /> </bean> <beans profile="dev"> <jdbc:embedded-database id="dataSource" type="H2" /> </beans> <beans profile="cloud"> <cloud:data-source id="dataSource" service-name="contactDs"/> </beans> © Zenika 2011 Spring 3.1 18
  • 19. Environment / Profile • Creating the application context for the test profile GenericXmlApplicationContext ctx = new GenericXmlApplicationContext(); ctx.getEnvironment().setActiveProfiles("test"); ctx.load("classpath:/application-context.xml"); ctx.refresh(); © Zenika 2011 Spring 3.1 19
  • 20. Environment / Profile • Activating a profile declaratively -Dspring.profiles.active="prod" © Zenika 2011 Spring 3.1 20
  • 21. Environment / Profile • Bootstrapping with the TestContext framework @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:/application-context.xml") @ActiveProfiles("test") public class ProfileTest { @Autowired private ContactDao contactDao; @Test public void getContact() throws Exception { ... } } © Zenika 2011 Spring 3.1 21
  • 22. Environment / Profile • Just « prod » profile <bean class="com.zenika.spring31.ContactDao"> <constructor-arg ref="dataSource" /> </bean> <beans profile="prod"> <jee:jndi-lookup id="ds" jndi-name="java:comp/env/jdbc/ds" /> </beans> © Zenika 2011 Spring 3.1 22
  • 23. Environment / Profile • Override what you need in the test @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration( loader=AnnotationConfigContextLoader.class ) public class SpecialProfileTest { @Autowired private ContactDao contactDao; @Test public void getContact() throws Exception { ... } @Configuration @ImportResource("classpath:/application-context.xml") static class ContextConfiguration { @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder().build(); } } } © Zenika 2011 Spring 3.1 23
  • 24. Java configuration • Nothing equivalent to XML namespaces so far... @Transactional @Repository public class HibernateContactRepo { ... } <context:component-scan base-package="com.zenika" /> <tx:annotation-driven /> © Zenika 2011 Spring 3.1 24
  • 25. Java configuration • Annotations equivalent to common XML shortcuts @Transactional @Repository public class HibernateContactRepo { ... } @Configuration @EnableTransactionManagement @ComponentScan(basePackageClasses=HibernateContactRepo.class) public class ContextConfiguration { ... } © Zenika 2011 Spring 3.1 25
  • 26. Java configuration • Annotations equivalent to common XML shortcuts @Configuration @EnableTransactionManagement @ComponentScan(basePackageClasses=HibernateContactRepo.class) public class ContextConfiguration { @Bean public SessionFactory sf() throws Exception { return new AnnotationSessionFactoryBuilder() .setDataSource(dataSource()) .setPackagesToScan(Contact.class.getPackage().getName()) .buildSessionFactory(); } @Bean public PlatformTransactionManager tm() throws Exception { return new HibernateTransactionManager(sf()); } @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2).build(); } } © Zenika 2011 Spring 3.1 26
  • 27. Spring JPA • More support for persistence in Spring JPA public interface ContactRepository extends JpaRepository<Contact, Long> { } <jpa:repositories base-package="com.zenika.jpa" /> long initialCount = contactRepo.count(); Contact contact = new Contact(); contact.setFirstname("Arnaud"); contact.setLastname("Cogoluègnes"); contactRepo.save(contact); Assert.assertEquals(initialCount+1, contactRepo.count()); © Zenika 2011 Spring 3.1 27
  • 28. Spring JPA • Define your own method, following conventions public interface ContactRepository extends JpaRepository<Contact, Long> { List<Contact> findByFirstname(String firstname); } List<Contact> contacts = contactRepo.findByFirstname("Arnaud"); © Zenika 2011 Spring 3.1 28
  • 29. Spring JPA • Define JPQL queries for methods public interface ContactRepository extends JpaRepository<Contact, Long> { @Query("from Contact c where lower(c.firstname) = lower(?1)") List<Contact> find(String search); } List<Contact> contacts = contactRepo.find("arnaud"); © Zenika 2011 Spring 3.1 29
  • 30. Spring JPA • Built-in support for pagination Pageable request = new PageRequest(1,2,new Sort("lastname")); Page<Contact> page = contactRepo.findAll(request); List<Contact> contacts = page.getContent(); long total = page.getTotalElements(); long number = page.getNumberOfElements(); © Zenika 2011 Spring 3.1 30
  • 31. Quick note on Spring Data • Spring JPA is part of the Spring Data project • Spring Data is an umbrella project • Spring Data provides Spring support for « new » data access technologies • MongoDB, Neo4j, Riak, Redis, Hadoop • Support planned for additional NoSQL technologies • HBase, Cassandra, CouchDB • Don't hesitate to check out Spring Data! • http://www.springsource.org/spring-data © Zenika 2011 Spring 3.1 31
  • 32. Cache support in Spring 3.1 • What about some transparent cache on method calls? public interface ContactRepository extends JpaRepository<Contact, Long> { Contact findOne(Long id); } Contact contact = contactRepo.findOne(contact.getId()); contact = contactRepo.findOne(contact.getId()); Hibernate: select contact0_.id as id0_0_, ... Hibernate: select contact0_.id as id0_0_, ... © Zenika 2011 Spring 3.1 32
  • 33. Cache support in Spring 3.1 • Let's combine Spring JPA and Spring 3.1's cache support ! • NB: the cache support works on any kinds of beans public interface ContactRepository extends JpaRepository<Contact, Long> { @Cacheable("contacts") Contact findOne(Long id); } Contact contact = contactRepo.findOne(contact.getId()); contact = contactRepo.findOne(contact.getId()); Hibernate: select contact0_.id as id0_0_, ... © Zenika 2011 Spring 3.1 33
  • 34. Cache support in Spring 3.1 • This is how to configure the cache <cache:annotation-driven /> <bean id="cacheManager" class="o.s.cache.support.SimpleCacheManager"> <property name="caches"> <set> <bean class="o.s.cache.concurrent.ConcurrentMapCache" c:name="contacts" /> </set> </property> </bean> © Zenika 2011 Spring 3.1 34
  • 35. Cache support in Spring 3.1 • The cache support is an abstraction • The Spring Framework provides implementations • SimpleCacheManager • Uses collections of caches • Useful for testing or small, non-distributed environments • EhCacheCacheManager • Backed up by Ehcache • The Spring Gemfire project ships with an implementation © Zenika 2011 Spring 3.1 35
  • 36. Cache support in Spring 3.1 • Can use expression for keys public interface ContactRepository extends JpaRepository<Contact, Long> { @Cacheable(value="contacts",key="#p0+'.'+#p1") Contact findByLastnameAndFirstname(String lastname, String firstname); } Contact contact = contactRepo.findByLastnameAndFirstname( "Cogoluègnes", "Arnaud"); contact = contactRepo.findByLastnameAndFirstname( "Cogoluègnes", "Arnaud"); Hibernate: select contact0_.id as id0_, ... © Zenika 2011 Spring 3.1 36
  • 37. Cache support in Spring 3.1 • Method can do some housekeeping with @CacheEvict @Transactional public interface ContactRepository extends JpaRepository<Contact, Long> { @Cacheable("contacts") Contact findOne(Long id); @CacheEvict(value="contacts",key="#p0.id") Contact save(Contact contact); } © Zenika 2011 Spring 3.1 37
  • 38. Cache support in Spring 3.1 • Spring's cache support can be used • on the data access layer • replaces 2nd level cache or provides cache for a JDBC-based layer • at the web tier level • caches business services calls or web services calls © Zenika 2011 Spring 3.1 38
  • 39. Spring MVC enhancements • Easier registration of HttpMessageConverters • But what is a HttpMessageConverter anyway? • HttpMessageConverters are used in Spring's REST support • Java object to HTTP response conversion • From Java to XML, JSON, etc. • HTTP request to Java object conversion • From XML, JSON to Java • On the server but on the client side as well... © Zenika 2011 Spring 3.1 39
  • 40. Spring MVC enhancements • Easier registration with a dedicated XML tag • Used to be directly at the HandlerAdapter level <mvc:annotation-driven> <mvc:message-converters register-defaults="false"> <bean class="com.zenika.web.ContactHttpMessageConverter" /> </mvc:message-converters> </mvc:annotation-driven> © Zenika 2011 Spring 3.1 40
  • 41. Spring MVC enhancements • Java-based configuration • Same as <mvc:annotation-driven /> @Configuration @EnableWebMvc public class WebConfig extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters( List<HttpMessageConverter<?>> converters) { converters.add(new ContactHttpMessageConverter()); } } © Zenika 2011 Spring 3.1 41
  • 42. Spring MVC enhancements • Big refactoring on the way to process annotations @Controller public class ContactController { @Autowired private ContactRepository repo; @RequestMapping(value="/contacts/{id}", method=RequestMethod.GET ) @ResponseBody public Contact get(@PathVariable Long id) { return repo.findOne(id); } } © Zenika 2011 Spring 3.1 42
  • 43. Spring MVC enhancements • Who used to process annotations like @RequestMapping, @RequestParam, etc? • Answer: the AnnotationMethodHandlerAdapter. • Processing was hard-coded in the class • Spring 3.1 introduced the HandlerMethod abstraction • RequestMappingHandlerMapping • RequestMappingHandlerAdapter © Zenika 2011 Spring 3.1 43
  • 44. Spring MVC enhancements • Consequences of the HandlerMethod abstraction • Backward compatible (@RequestMapping, @RequestParam & co). • More fine-grained control over controller method execution • Possible interception around the invocation of the controller • Pluggable mechanism on method argument • You can create your own @RequestParam-like annotations! • Check the HandlerMethodArgumentResolver and HandlerMethodReturnValueHandler interfaces © Zenika 2011 Spring 3.1 44
  • 45. Support for Servlet 3.0 • Servlet 3.0 allows for programmatic registration • ServletContext.addServlet(String, Servlet) • ServletContext.addFilter(String, Filter) • Hook for frameworks • ServletContainerInitializer • Implementations listed in META-INF/services • In Spring: SpringServletContainerInitializer © Zenika 2011 Spring 3.1 45
  • 46. Support for Servlet 3.0 • SpringServletContainerInitializer triggers WebApplicationInitializers • WebApplicationInitializer • The API to use • Detected and called by Spring (through the web container) • Used for initialization • Registering a DispatcherServlet • Bootstrapping the Spring ApplicationContext © Zenika 2011 Spring 3.1 46
  • 47. Support for Servlet 3.0 • No need of web.xml anymore public class ZenContactInitializer implements WebApplicationInitializer { @Override public void onStartup(ServletContext sc) throws ServletException { AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.register(WebConfig.class); sc.addListener(new ContextLoaderListener(rootContext)); AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext(); dispatcherContext.register(DispatcherConfig.class); ServletRegistration.Dynamic dispatcher = sc.addServlet( "dispatcher", new DispatcherServlet(dispatcherContext)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/main"); } } © Zenika 2011 Spring 3.1 47
  • 48. Resources • Summary • http://blog.springsource.com/2011/02/11/spring-framework-3-1-m1-released/ • http://blog.springsource.com/2011/06/09/spring-framework-3-1-m2-released/ • Environment • http://blog.springsource.com/2011/02/14/spring-3-1-m1-introducing-profile/ • http://blog.springsource.com/2011/06/21/spring-3-1-m2-testing-with-configuration- classes-and-profiles/ • http://blog.springsource.com/2011/02/15/spring-3-1-m1-unified-property-management/ • Cache abstraction • http://blog.springsource.com/2011/02/23/spring-3-1-m1-caching/ • Spring JPA • http://blog.springsource.com/2011/02/10/getting-started-with-spring-data-jpa/ • http://blog.springsource.com/2011/07/27/fine-tuning-spring-data-repositories/ • Spring MVC • http://blog.springsource.com/2011/02/21/spring-3-1-m1-mvc-namespace- enhancements-and-configuration/ • http://blog.springsource.com/2011/06/13/spring-3-1-m2-spring-mvc-enhancements-2/ © Zenika 2011 Spring 3.1 48
  • 49. Questions ? © Zenika 2011 Spring 3.1 49