Your SlideShare is downloading. ×
0
Spring 3.1© Zenika 2011       Spring 3.1   1
Speakers qualifications     • Arnaud Cogoluègnes          •     Consultant with Zenika          •     Has been using Sprin...
Agenda     •   History     •   Environment     •   Java configuration     •   Spring JPA     •   Cache abstraction     •  ...
History     •   v. 0.9 : june 2003 (foundations)     •   v. 1.0 : march 2004     •   v. 1.1 : september 2004     •   v. 1....
Environment     • Inside the application context                            Environment                Property Source    ...
Environment / Property Source     • Do you know this?   <context:property-placeholder location="database.properties"/>   <...
Environment / Property Source     • Spring 3.1 introduces an abstraction for property sources     • But what is a Property...
Environment / PropertySource     • Where do PropertySources come from?                                              System...
Environment / Property Source     • How to refer to PropertySource?       <bean id="dataSource"             class="org.apa...
Environment / Property Source     • How to refer to PropertySource?       @Configuration       public class DatabaseConfig...
Environment / PropertySource     • How to define a PropertySource ?       <context:property-placeholder               loca...
Environment / PropertySource     • How to define a PropertySource ?       <context:property-placeholder               prop...
Environment / PropertySource     • How to define a PropertySource ?      <context-param>             <param-name>contextIn...
Environment / PropertySource     • Unified way to deal with properties     • More flexible than simple property placeholde...
Environment / Profile                           Environment                Property Source                 Profile        ...
Environment / Profile                       Application Context                    Service                  Repository    ...
Environment / Profile     • Different beans for different environments    <bean class="com.zenika.ContactDao">      <const...
Environment / Profile     • Lets reach the clouds!  <bean class="com.zenika.ContactDao">    <constructor-arg ref="dataSour...
Environment / Profile     • Creating the application context for the test profile    GenericXmlApplicationContext ctx =   ...
Environment / Profile     • Activating a profile declaratively    -Dspring.profiles.active="prod"© Zenika 2011            ...
Environment / Profile     • Bootstrapping with the TestContext framework    @RunWith(SpringJUnit4ClassRunner.class)    @Co...
Environment / Profile     • Just « prod » profile    <bean class="com.zenika.spring31.ContactDao">      <constructor-arg r...
Environment / Profile     • Override what you need in the test    @RunWith(SpringJUnit4ClassRunner.class)    @ContextConfi...
Java configuration     • Nothing equivalent to XML namespaces so far...    @Transactional    @Repository    public class H...
Java configuration     • Annotations equivalent to common XML shortcuts    @Transactional    @Repository    public class H...
Java configuration     • Annotations equivalent to common XML shortcuts    @Configuration    @EnableTransactionManagement ...
Spring JPA     • More support for persistence in Spring JPA    public interface ContactRepository           extends JpaRep...
Spring JPA     • Define your own method, following conventions    public interface ContactRepository                     e...
Spring JPA      • Define JPQL queries for methods  public interface ContactRepository                   extends JpaReposit...
Spring JPA     • Built-in support for pagination   Pageable request = new PageRequest(1,2,new Sort("lastname"));   Page<Co...
Quick note on Spring Data     • Spring JPA is part of the Spring Data project     • Spring Data is an umbrella project    ...
Cache support in Spring 3.1     • What about some transparent cache on method calls?   public interface ContactRepository ...
Cache support in Spring 3.1     • Lets combine Spring JPA and Spring 3.1s cache support !          • NB: the cache support...
Cache support in Spring 3.1     • This is how to configure the cache   <cache:annotation-driven />   <bean id="cacheManage...
Cache support in Spring 3.1     • The cache support is an abstraction     • The Spring Framework provides implementations ...
Cache support in Spring 3.1     • Can use expression for keys   public interface ContactRepository                    exte...
Cache support in Spring 3.1     • Method can do some housekeeping with @CacheEvict   @Transactional   public interface Con...
Cache support in Spring 3.1     • Springs cache support can be used          • on the data access layer             • repl...
Spring MVC enhancements     • Easier registration of HttpMessageConverters     • But what is a HttpMessageConverter anyway...
Spring MVC enhancements     • Easier registration with a dedicated XML tag          • Used to be directly at the HandlerAd...
Spring MVC enhancements      • Java-based configuration          • Same as <mvc:annotation-driven />  @Configuration  @Ena...
Spring MVC enhancements      • Big refactoring on the way to process annotations  @Controller  public class ContactControl...
Spring MVC enhancements     • Who used to process annotations like @RequestMapping,       @RequestParam, etc?     • Answer...
Spring MVC enhancements     • Consequences of the HandlerMethod abstraction          • Backward compatible (@RequestMappin...
Support for Servlet 3.0     • Servlet 3.0 allows for programmatic registration        • ServletContext.addServlet(String, ...
Support for Servlet 3.0     • SpringServletContainerInitializer triggers       WebApplicationInitializers     • WebApplica...
Support for Servlet 3.0      • No need of web.xml anymore  public class ZenContactInitializer         implements WebApplic...
Resources     • Summary          • http://blog.springsource.com/2011/02/11/spring-framework-3-1-m1-released/          • ht...
Questions ?© Zenika 2011        Spring 3.1   49
Upcoming SlideShare
Loading in...5
×

Spring 3.1

4,555

Published on

Published in: Technology
0 Comments
3 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
4,555
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
167
Comments
0
Likes
3
Embeds 0
No embeds

No notes for slide

Transcript of "Spring 3.1"

  1. 1. Spring 3.1© Zenika 2011 Spring 3.1 1
  2. 2. Speakers 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. 3. Agenda • History • Environment • Java configuration • Spring JPA • Cache abstraction • Spring MVC improvements© Zenika 2011 Spring 3.1 3
  4. 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. 5. Environment • Inside the application context Environment Property Source Profile Property Source Profile© Zenika 2011 Spring 3.1 5
  6. 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. 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. 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. 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. 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. 11. Environment / PropertySource • How to define a PropertySource ? <context:property-placeholder location="classpath:application.properties" />© Zenika 2011 Spring 3.1 11
  12. 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. 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. 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. 15. Environment / Profile Environment Property Source Profile Property Source Profile© Zenika 2011 Spring 3.1 15
  16. 16. Environment / Profile Application Context Service Repository "dev" profile "prod" profile Datasource Datasource© Zenika 2011 Spring 3.1 16
  17. 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. 18. Environment / Profile • Lets 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. 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. 20. Environment / Profile • Activating a profile declaratively -Dspring.profiles.active="prod"© Zenika 2011 Spring 3.1 20
  21. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 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 • Dont hesitate to check out Spring Data! • http://www.springsource.org/spring-data© Zenika 2011 Spring 3.1 31
  32. 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. 33. Cache support in Spring 3.1 • Lets combine Spring JPA and Spring 3.1s 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. 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. 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. 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. 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. 38. Cache support in Spring 3.1 • Springs 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. 39. Spring MVC enhancements • Easier registration of HttpMessageConverters • But what is a HttpMessageConverter anyway? • HttpMessageConverters are used in Springs 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. 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. 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. 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. 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. 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. 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. 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. 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. 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. 49. Questions ?© Zenika 2011 Spring 3.1 49
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×