The spring 32 update final

992 views

Published on

0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
992
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
28
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

The spring 32 update final

  1. 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. 2. About Josh Long (龙之春) Spring Developer Advocate twitter: @starbuxman weibo: @springsource josh.long@springsource.com 2Thursday, January 24, 13
  3. 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 3Thursday, January 24, 13
  4. 4. Why Are We Here? 4Thursday, January 24, 13
  5. 5. Why Are We Here? “ Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. ” -Bob Martin 5Thursday, January 24, 13
  6. 6. Why Are We Here? do NOT reinvent the Wheel! 6Thursday, January 24, 13
  7. 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!) 7Thursday, January 24, 13
  8. 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 8Thursday, January 24, 13
  9. 9. 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 standardizationThursday, January 24, 13
  10. 10. 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 § JSFs 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 10Thursday, January 24, 13
  11. 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 11Thursday, January 24, 13
  12. 12. Spring 3.1 12Thursday, January 24, 13
  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 13Thursday, January 24, 13
  14. 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 14Thursday, January 24, 13
  15. 15. Environment Abstraction 15Thursday, January 24, 13
  16. 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 15Thursday, January 24, 13
  17. 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 15Thursday, January 24, 13
  18. 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 15Thursday, January 24, 13
  19. 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 15Thursday, January 24, 13
  20. 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> 16Thursday, January 24, 13
  21. 21. Environment Configuration 17Thursday, January 24, 13
  22. 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 17Thursday, January 24, 13
  23. 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 17Thursday, January 24, 13
  24. 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 17Thursday, January 24, 13
  25. 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 17Thursday, January 24, 13
  26. 26. Java-Based Application Configuration 18Thursday, January 24, 13
  27. 27. Java-Based Application Configuration § Application-specific container configuration • aligned with Spring 3.0s @Configuration style • focus on customizing the annotation-based processing parts of Spring 18Thursday, January 24, 13
  28. 28. Java-Based Application Configuration § Application-specific container configuration • aligned with Spring 3.0s @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 18Thursday, January 24, 13
  29. 29. Java-Based Application Configuration § Application-specific container configuration • aligned with Spring 3.0s @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 18Thursday, January 24, 13
  30. 30. Java-Based Application Configuration § Application-specific container configuration • aligned with Spring 3.0s @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 18Thursday, January 24, 13
  31. 31. So, What’s All of This Look Like in Code? Not confidential. Tell everyone. 19Thursday, January 24, 13
  32. 32. 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. 20Thursday, January 24, 13
  33. 33. 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. 21Thursday, January 24, 13
  34. 34. 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. 22Thursday, January 24, 13
  35. 35. 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. 23Thursday, January 24, 13
  36. 36. 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. 24Thursday, January 24, 13
  37. 37. ...But Where’d the SessionFactory come from? Not confidential. Tell everyone. 25Thursday, January 24, 13
  38. 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 26Thursday, January 24, 13
  39. 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) 27Thursday, January 24, 13
  40. 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"); } } 28Thursday, January 24, 13
  41. 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"); } } 28Thursday, January 24, 13
  42. 42. 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
  43. 43. 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
  44. 44. 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
  45. 45. 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
  46. 46. 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
  47. 47. 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
  48. 48. 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
  49. 49. 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
  50. 50. 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
  51. 51. 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
  52. 52. 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
  53. 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() { ... } } 40Thursday, January 24, 13
  54. 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 applications class files <bean class="…" c:age="10" c:name="myName"/> <bean class="…" c:name-ref="nameBean" c:spouse-ref="spouseBean"/> 41Thursday, January 24, 13
  55. 55. Cache Abstraction 42Thursday, January 24, 13
  56. 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 42Thursday, January 24, 13
  57. 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 42Thursday, January 24, 13
  58. 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 42Thursday, January 24, 13
  59. 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 42Thursday, January 24, 13
  60. 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 42Thursday, January 24, 13
  61. 61. Cache Abstraction 43Thursday, January 24, 13
  62. 62. Cache Abstraction @Cacheable ( name = “@(sessionKeyUtil).getCurrentSession() + owner”) public Owner loadOwner(int id); 43Thursday, January 24, 13
  63. 63. Cache Abstraction @Cacheable ( name = “@(sessionKeyUtil).getCurrentSession() + owner”) public Owner loadOwner(int id); @Cacheable(name = “owners”, condition="name.length < 10") 43Thursday, January 24, 13
  64. 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); 43Thursday, January 24, 13
  65. 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); 43Thursday, January 24, 13
  66. 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”) 43Thursday, January 24, 13
  67. 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); 43Thursday, January 24, 13
  68. 68. 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.0s ServletContainerInitializer mechanism • in combination with Spring 3.1s AnnotationConfigWebApplicationContext • plus Spring 3.1s environment abstraction § Exposure of native Servlet 3.0 functionality in Spring MVC • standard Servlet 3.0 file upload behind Springs MultipartResolver abstraction • support for asynchronous request processing coming in Spring 3.2 44Thursday, January 24, 13
  69. 69. WebApplicationInitializer Example /** * Automatically detected and invoked on startup by Springs 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)); ... } } 45Thursday, January 24, 13
  70. 70. @MVC Processing & Flash Attributes 46Thursday, January 24, 13
  71. 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 46Thursday, January 24, 13
  72. 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 users session l an incoming FlashMap for a request will automatically get exposed to the model 46Thursday, January 24, 13
  73. 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 Springs JpaTransactionManager and co. support setup by unit name as well − as an alternative to referring to EntityManagerFactory beans directly − 47Thursday, January 24, 13
  74. 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 48Thursday, January 24, 13
  75. 75. Java SE 7 49Thursday, January 24, 13
  76. 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 49Thursday, January 24, 13
  77. 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 § Oracles 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 49Thursday, January 24, 13
  78. 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 § Oracles 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 49Thursday, January 24, 13
  79. 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 § Oracles 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 49Thursday, January 24, 13
  80. 80. github.com/SpringSource 50Thursday, January 24, 13
  81. 81. Spring 3.2 51Thursday, January 24, 13
  82. 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 52Thursday, January 24, 13
  83. 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 53Thursday, January 24, 13
  84. 84. 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 54Thursday, January 24, 13
  85. 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 55Thursday, January 24, 13
  86. 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 56Thursday, January 24, 13
  87. 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. 57Thursday, January 24, 13
  88. 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 58Thursday, January 24, 13
  89. 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 59Thursday, January 24, 13
  90. 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 60Thursday, January 24, 13
  91. 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 61Thursday, January 24, 13
  92. 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 62Thursday, January 24, 13
  93. 93. 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 } 63Thursday, January 24, 13
  94. 94. 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] } 64Thursday, January 24, 13
  95. 95. 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 } 65Thursday, January 24, 13
  96. 96. Spring 3.3... 66Thursday, January 24, 13
  97. 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 67Thursday, January 24, 13
  98. 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 68Thursday, January 24, 13
  99. 99. 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... 69Thursday, January 24, 13
  100. 100. 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 70Thursday, January 24, 13
  101. 101. 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); 71Thursday, January 24, 13
  102. 102. WebSocket Support § WebSocket support in current servers isnt 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 72Thursday, January 24, 13
  103. 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 73Thursday, January 24, 13
  104. 104. @SpringSource @Starbuxman Questions? NOT CONFIDENTIAL -- TELL EVERYONEThursday, January 24, 13

×