the spring 32 update final

104
© 2012 SpringOne 2GX 2012. All rights reserved. Do not distribute without permission. Spring 3.1, 3.2, and 3.3 Update Josh Long Spring Developer Advocate, SpringSource, a Division of VMWare http://www.joshlong.com || @starbuxman || [email protected] Thursday, January 24, 13

Upload: josh-long

Post on 25-Jan-2015

593 views

Category:

Documents


5 download

DESCRIPTION

 

TRANSCRIPT

Page 1: The spring 32 update final

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

Spring 3.1, 3.2, and 3.3 UpdateJosh Long Spring Developer Advocate, SpringSource, a Division of VMWarehttp://www.joshlong.com || @starbuxman || [email protected]

Thursday, January 24, 13

Page 2: The spring 32 update final

Spring Developer Advocatetwitter: @starbuxmanweibo: @springsource [email protected]

2

About Josh Long (龙之春)

Thursday, January 24, 13

Page 3: The spring 32 update final

About Josh LongSpring Developer Advocatetwitter: @[email protected]

Contributor To:

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

3Thursday, January 24, 13

Page 4: The spring 32 update final

Why Are We Here?

4

Thursday, January 24, 13

Page 5: The spring 32 update final

5

Why Are We Here?

Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.

-Bob Martin

”“

Thursday, January 24, 13

Page 6: The spring 32 update final

6

do NOT reinvent the Wheel!

Why Are We Here?

Thursday, January 24, 13

Page 7: The spring 32 update final

Spring’s aim:

bring simplicity to java development

7

tc ServerTomcat

Jetty

lightweight

CloudFoundryGoogle App EngineAmazon BeanStalk

the cloud:

WebSphereJBoss ASWebLogic

(on legacy versions, too!)

traditional

The Spring framework

web tier &

RIAservice tier batch

processingintegration & messaging

data access

/ NoSQL / Big Data

mobile Security

Thursday, January 24, 13

Page 8: The spring 32 update final

The Spring Framework

8

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.

Spring Hadoop Provides a POJO-centric approach to building Hadoop applications. Supports HBase, others

Spring Mobile, Spring Android provides first-class support for service creation and consumption for iPhone, Android

Spring GemFire Provides the easiest interface for the GemFire enterprise data grid technology

Thursday, January 24, 13

Page 9: The spring 32 update final

Wide Variety of Data and Data Stores

§ Not all data resides in relational databasesl cloud environments often suggest alternatives for scalability reasonsl HBase, Redis, Mongo, etc

§ Distributed caches add challenges as welll not least of it all in terms of application-level access patternsl GemFire, Coherence, etc

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

Thursday, January 24, 13

Page 10: The spring 32 update final

10

Wide Variety of Web Clients

§ More and more client-side web technologiesl 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 statel strictly controlled user session state

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

Thursday, January 24, 13

Page 11: The spring 32 update final

Current and Upcoming: 3.1, 3.2, and 3.2

§ Spring Framework 3.1 (Dec 2011)• Environment profiles, Java-based configuration, declarative caching

• Initial Java 7 support, Servlet 3.0 based deployment

§ Spring Framework 3.2 (Dec 2012)• Gradle-based build, GitHub-based contribution model

• Fully Java 7 oriented, async MVC processing on Servlet 3.0

§ Spring Framework 3.3 (Q4 2013)• Comprehensive Java SE 8 support (including lambda expressions)• Single abstract method types in Spring are well positioned

• Support for Java EE 7 API level and WebSockets

11

Thursday, January 24, 13

Page 12: The spring 32 update final

Spring 3.1

12

Thursday, January 24, 13

Page 13: The spring 32 update final

Current and Upcoming: 3.1, 3.2, and 3.2

§ Spring Framework 3.1 (Dec 2011)• Environment profiles, Java-based configuration, declarative caching

• Initial Java 7 support, Servlet 3.0 based deployment

§ Spring Framework 3.2 (Dec 2012)• Gradle-based build, GitHub-based contribution model

• Fully Java 7 oriented, async MVC processing on Servlet 3.0

§ Spring Framework 3.3 (Q4 2013)• Comprehensive Java SE 8 support (including lambda expressions)• Single abstract method types in Spring are well positioned

• Support for Java EE 7 API level and WebSockets

13

Thursday, January 24, 13

Page 14: The spring 32 update final

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

Thursday, January 24, 13

Page 15: The spring 32 update final

15

Environment Abstraction

Thursday, January 24, 13

Page 16: The spring 32 update final

15

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

Thursday, January 24, 13

Page 17: The spring 32 update final

15

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

Thursday, January 24, 13

Page 18: The spring 32 update final

15

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

Thursday, January 24, 13

Page 19: The spring 32 update final

15

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

Thursday, January 24, 13

Page 20: The spring 32 update final

16

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>

Thursday, January 24, 13

Page 21: The spring 32 update final

17

Environment Configuration

Thursday, January 24, 13

Page 22: The spring 32 update final

17

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

Thursday, January 24, 13

Page 23: The spring 32 update final

17

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

Thursday, January 24, 13

Page 24: The spring 32 update final

17

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

Thursday, January 24, 13

Page 25: The spring 32 update final

17

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

Thursday, January 24, 13

Page 26: The spring 32 update final

18

Java-Based Application Configuration

Thursday, January 24, 13

Page 27: The spring 32 update final

18

Java-Based Application Configuration

§ Application-specific container configuration• aligned with Spring 3.0's @Configuration style• focus on customizing the annotation-based processing parts of Spring

Thursday, January 24, 13

Page 28: The spring 32 update final

18

Java-Based Application Configuration

§ Application-specific container configuration• aligned with Spring 3.0's @Configuration style• focus on customizing the annotation-based processing parts of Spring

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

Thursday, January 24, 13

Page 29: The spring 32 update final

18

Java-Based Application Configuration

§ Application-specific container configuration• aligned with Spring 3.0's @Configuration style• focus on customizing the annotation-based processing parts of Spring

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

Thursday, January 24, 13

Page 30: The spring 32 update final

18

Java-Based Application Configuration

§ Application-specific container configuration• aligned with Spring 3.0's @Configuration style• focus on customizing the annotation-based processing parts of Spring

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

§ Typical infrastructure setup• transactions• scheduling•MVC customization

Thursday, January 24, 13

Page 31: The spring 32 update final

Not confidential. Tell everyone.

So, What’s All of This Look Like in Code?

19

Thursday, January 24, 13

Page 32: The spring 32 update final

Not confidential. Tell everyone.

I want Database Access ... with Hibernate 4 Support

20

@Servicepublic class CustomerService {

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

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

}

Thursday, January 24, 13

Page 33: The spring 32 update final

Not confidential. Tell everyone.

I want Database Access ... with Hibernate 4 Support

21

@Servicepublic 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; }

}

Thursday, January 24, 13

Page 34: The spring 32 update final

Not confidential. Tell everyone.

I want Database Access ... with Hibernate 4 Support

22

@Servicepublic 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; }

}

Thursday, January 24, 13

Page 35: The spring 32 update final

Not confidential. Tell everyone.

I want Declarative Cache Management...

23

@Servicepublic class CustomerService {

@Inject private SessionFactory sessionFactory;

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

...

}

Thursday, January 24, 13

Page 36: The spring 32 update final

Not confidential. Tell everyone.

I want a RESTful Endpoint...

24

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

@Controllerpublic class CustomerController {

@Inject private CustomerService customerService;

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

Thursday, January 24, 13

Page 37: The spring 32 update final

Not confidential. Tell everyone.

...But Where’d the SessionFactory come from?

25

Thursday, January 24, 13

Page 38: The spring 32 update final

The Spring ApplicationContext

§ Spring Manages the beans you tell it to manage (Implicitly, Explicitly)• use annotations (JSR 250, JSR 330, native)

• XML

• Java configuration

• component scanning

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

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

26

Thursday, January 24, 13

Page 39: The spring 32 update final

The Spring ApplicationContext

§ Annotations (component-scanning)• best when you want Spring to sort it all out in the wash, no need for explicit configuration

§ Java Configuration• type-safe, and explicit - all configuration is centralized. Provides a good birds-eye view of your application

§ XML • explicit - namespaces still provide the most punch in a lot of cases

§ All together• use Java configuration for your regular third party beans (like a DataSource)

• XML namespaces for DSLs and higher level functionality (Spring Integration, Batch, etc.)

• annotations for your components (a @Service, or a Spring MVC @Controller)

27

Thursday, January 24, 13

Page 40: The spring 32 update final

The Spring ApplicationContext

28

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 XML:

Thursday, January 24, 13

Page 41: The spring 32 update final

The Spring ApplicationContext

28

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 XML:

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"); }}

From Java Configuration

Thursday, January 24, 13

Page 42: The spring 32 update final

Not confidential. Tell everyone.

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” );

Thursday, January 24, 13

Page 43: The spring 32 update final

Not confidential. Tell everyone.

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” );

Thursday, January 24, 13

Page 44: The spring 32 update final

Not confidential. Tell everyone.

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 );

Thursday, January 24, 13

Page 45: The spring 32 update final

Not confidential. Tell everyone.

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” );

Thursday, January 24, 13

Page 46: The spring 32 update final

Not confidential. Tell everyone.

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 );

Thursday, January 24, 13

Page 47: The spring 32 update final

Not confidential. Tell everyone.

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” );

Thursday, January 24, 13

Page 48: The spring 32 update final

Not confidential. Tell everyone.

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 );

Thursday, January 24, 13

Page 49: The spring 32 update final

Not confidential. Tell everyone.

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” );

Thursday, January 24, 13

Page 50: The spring 32 update final

Not confidential. Tell everyone.

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 );

Thursday, January 24, 13

Page 51: The spring 32 update final

Not confidential. Tell everyone.

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” );

Thursday, January 24, 13

Page 52: The spring 32 update final

Not confidential. Tell everyone.

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 );

Thursday, January 24, 13

Page 53: The spring 32 update final

40

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() { ... }}

Thursday, January 24, 13

Page 54: The spring 32 update final

41

"c:" Namespace

§ New XML namespace for use with bean configuration• shortcut for <constructor-arg>• inline argument values• analogous to existing "p:" namespace• use of constructor argument names• recommended for readability • debug symbols have to be available in the application's class files

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

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

Thursday, January 24, 13

Page 55: The spring 32 update final

42

Cache Abstraction

Thursday, January 24, 13

Page 56: The spring 32 update final

42

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

Thursday, January 24, 13

Page 57: The spring 32 update final

42

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

Thursday, January 24, 13

Page 58: The spring 32 update final

42

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

Thursday, January 24, 13

Page 59: The spring 32 update final

42

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

Thursday, January 24, 13

Page 60: The spring 32 update final

42

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

Thursday, January 24, 13

Page 61: The spring 32 update final

43

Cache Abstraction

Thursday, January 24, 13

Page 62: The spring 32 update final

43

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

Thursday, January 24, 13

Page 63: The spring 32 update final

43

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

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

Thursday, January 24, 13

Page 64: The spring 32 update final

43

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

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

Thursday, January 24, 13

Page 65: The spring 32 update final

43

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

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

Thursday, January 24, 13

Page 66: The spring 32 update final

43

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”)

Thursday, January 24, 13

Page 67: The spring 32 update final

43

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);

Thursday, January 24, 13

Page 68: The spring 32 update final

44

Servlet 3.0 Based Web Applications

§ Explicit support for Servlet 3.0 containers• such as Tomcat 7 and GlassFish 3•while at the same time preserving compatibility with Servlet 2.4+

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

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

Thursday, January 24, 13

Page 69: The spring 32 update final

45

WebApplicationInitializer Example

/** * Automatically detected and invoked on startup by Spring's

ServletContainerInitializer. May register listeners, filters, servlets etc against the given Servlet 3.0 ServletContext.

*/public class MyWebAppInitializer implements WebApplicationInitializer {

public void onStartup(ServletContext sc) throws ServletException { // Create the 'root' Spring application context AnnotationConfigWebApplicationContext root =

new AnnotationConfigWebApplicationContext(); root.scan("com.mycompany.myapp"); root.register(FurtherConfig.class);

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

Thursday, January 24, 13

Page 70: The spring 32 update final

46

@MVC Processing & Flash Attributes

Thursday, January 24, 13

Page 71: The spring 32 update final

46

@MVC Processing & Flash Attributes

§ RequestMethodHandlerAdapterl arbitrary mappings to handler methods across multiple controllersl better customization of handler method arguments

− HandlerMethodArgumentResolver− HandlerMethodReturnValueHandler− etc

Thursday, January 24, 13

Page 72: The spring 32 update final

46

@MVC Processing & Flash Attributes

§ RequestMethodHandlerAdapterl arbitrary mappings to handler methods across multiple controllersl better customization of handler method arguments

− HandlerMethodArgumentResolver− HandlerMethodReturnValueHandler− etc

§ FlashMap support and FlashMapManager abstractionl with RedirectAttributes as a new @MVC handler method argument type

− explicitly calling addFlashAttribute to add values to the output FlashMapl an outgoing FlashMap will temporarily get added to the user's sessionl an incoming FlashMap for a request will automatically get exposed to the model

Thursday, January 24, 13

Page 73: The spring 32 update final

47

Refined JPA Support

§ Package scanning without persistence.xmll 'packagesToScan' feature on LocalContainerEntityManagerFactoryBean

− building a persistence unit from @Entity classes within specific application packagesl similar to AnnotationSessionFactoryBean for Hibernate 3

− rolled into core LocalSessionFactoryBean for Hibernate 4l ideal for applications with a single default persistence unit

§ Consistent JPA setup by persistence unit namel JPA specification quite strongly based on the notion of persistence unit names

− @PersistenceContext / @PersistenceUnit referring to persistence unit namesl now Spring's JpaTransactionManager and co. support setup by unit name as well

− as an alternative to referring to EntityManagerFactory beans directly−

Thursday, January 24, 13

Page 74: The spring 32 update final

48

Third-Party Support Updates

§ Hibernate 4.0l natively and through JPAl native support in a dedicated org.springframework.orm.hibernate4 package

− dealing with package rearrangements in the Hibernate APIl preserving compatibility with Hibernate 3.2+ in o.sf.orm.hibernate3

§ Quartz 2.0l JobDetail and Trigger are now interfaces in the Quartz 2.0 API

− whereas they traditionally were base classes in Quartz 1.xl SchedulerFactoryBean now auto-adapts to Quartz 2.0 if present

− JobDetail/CronTrigger/SimpleTriggerFactoryBean variants for Quartz 2.0l preserving compatibility with Quartz 1.5+ in the same support package

Thursday, January 24, 13

Page 75: The spring 32 update final

49

Java SE 7

Thursday, January 24, 13

Page 76: The spring 32 update final

49

Java SE 7

§ Spring 3.1 introduces Java SE 7 supportl making best use of JRE 7 at runtimel support for JDBC 4.1l support for fork-join framework

Thursday, January 24, 13

Page 77: The spring 32 update final

49

Java SE 7

§ Spring 3.1 introduces Java SE 7 supportl making best use of JRE 7 at runtimel support for JDBC 4.1l support for fork-join framework

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

Thursday, January 24, 13

Page 78: The spring 32 update final

49

Java SE 7

§ Spring 3.1 introduces Java SE 7 supportl making best use of JRE 7 at runtimel support for JDBC 4.1l support for fork-join framework

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

Thursday, January 24, 13

Page 79: The spring 32 update final

49

Java SE 7

§ Spring 3.1 introduces Java SE 7 supportl making best use of JRE 7 at runtimel support for JDBC 4.1l support for fork-join framework

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

§ Spring Framework not being built against Java 7 yetl build upgrade coming in Spring 3.3

Thursday, January 24, 13

Page 80: The spring 32 update final

github.com/SpringSource

50

Thursday, January 24, 13

Page 81: The spring 32 update final

Spring 3.2

51

Thursday, January 24, 13

Page 82: The spring 32 update final

Current and Upcoming: 3.1, 3.2, and 3.2

§ Spring Framework 3.1 (Dec 2011)• Environment profiles, Java-based configuration, declarative caching

• Initial Java 7 support, Servlet 3.0 based deployment

§ Spring Framework 3.2 (Dec 2012)• Gradle-based build, GitHub-based contribution model

• Fully Java 7 oriented, async MVC processing on Servlet 3.0

§ Spring Framework 3.3 (Q4 2013)• Comprehensive Java SE 8 support (including lambda expressions)• Single abstract method types in Spring are well positioned

• Support for Java EE 7 API level and WebSockets

52

Thursday, January 24, 13

Page 83: The spring 32 update final

Change of Plans

§ We originally meant to have Java SE 8 and Java EE 7 themes in Spring 3.2§ However, Java EE 7 got pushed out further and further: Q2 2013• eventually descoped and delayed (no cloud focus anymore)

§ And Java SE 8 (OpenJDK 8) got rescheduled as well: September 2013• once again, descoped and delayed (no module system anymore)

• feature-complete developer preview expected for February 2013

§ Our solution: Spring 3.2 ships in Q4 2012 with core framework refinements• Spring 3.3 will ship in Q4 2013 with Java SE 8 and Java EE 7 support

53

Thursday, January 24, 13

Page 84: The spring 32 update final

So what’s in 3.2?

§ Gradle-based build§ Binaries built against Java 7§ Inlined ASM 4.0 and CGLIB 3.0§ Async MVC processing on Servlet 3.0§ Spring MVC test support§ MVC configuration refinements§ SpEL refinements§ Also including many runtime refinements• partially back-ported to 3.1.2/3.1.3

§ General Spring MVC niceties• Servlet 3 async support

• error reporting in REST scenarios

• content negotiation strategies

• matrix variables

54

Thursday, January 24, 13

Page 85: The spring 32 update final

Spring 3.2

§ Spring 3.1 came with early support for Java 7• JDBC 4.1, ForkJoinPool, etc

• framework itself still compiled on Java 6

§ Spring 3.2 is now being built on Java 7• CI builds running against Java 5, 6 and 7

§ enabled through our new Gradle build§ Spring 3.2 comes with ASM 4.0 and CGLIB 3.0• fully supporting the Java 7 byte code format

• ASM and CGLIB inlined into Spring module jars now

55

Thursday, January 24, 13

Page 86: The spring 32 update final

Async MVC Processing: Callable

56

@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

Thursday, January 24, 13

Page 87: The spring 32 update final

Async MVC Processing: DeferredResult

57

@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.

Thursday, January 24, 13

Page 88: The spring 32 update final

Async MVC Processing: AsyncTask

58

@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

Thursday, January 24, 13

Page 89: The spring 32 update final

Content Negotiation Strategies

59

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

Thursday, January 24, 13

Page 90: The spring 32 update final

Matrix Variables

60

"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

Thursday, January 24, 13

Page 91: The spring 32 update final

Matrix Variables

61

"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

Thursday, January 24, 13

Page 92: The spring 32 update final

Matrix Variables

§ Two Types of Usages§ Path Segment Name-Value Pairs

§ As delimited list path segment

62

/qa-releases;buildNumber=135;revision=3.2

/answers/id1;id2;id3;id4/comments

Thursday, January 24, 13

Page 93: The spring 32 update final

Matrix Variables: the common case

63

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

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

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

}

Thursday, January 24, 13

Page 94: The spring 32 update final

Matrix Variables: obtain all matrix variables

64

// 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]

}

Thursday, January 24, 13

Page 95: The spring 32 update final

Matrix Variables: qualify path segment

65

// 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

}

Thursday, January 24, 13

Page 96: The spring 32 update final

Spring 3.3...

66

Thursday, January 24, 13

Page 97: The spring 32 update final

Current and Upcoming: 3.1, 3.2, and 3.2

§ Spring Framework 3.1 (Dec 2011)• Environment profiles, Java-based configuration, declarative caching

• Initial Java 7 support, Servlet 3.0 based deployment

§ Spring Framework 3.2 (Dec 2012)• Gradle-based build, GitHub-based contribution model

• Fully Java 7 oriented, async MVC processing on Servlet 3.0

§ Spring Framework 3.3 (Q4 2013)• Comprehensive Java SE 8 support (including lambda expressions)• Single abstract method types in Spring are well positioned

• Support for Java EE 7 API level and WebSockets

67

Thursday, January 24, 13

Page 98: The spring 32 update final

Spring Framework 3.3 (Q4 2013)

§ Comprehensive Java 8 support• Support for Java EE 7 API levels

• Focus on message-oriented architectures

• annotation-driven JMS endpoint model

§ revised application event mechanism§ WebSocket support in Spring MVC§ Next-generation Groovy support§ Grails bean builder finally making it into Spring proper

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

68

Thursday, January 24, 13

Page 99: The spring 32 update final

The Java SE 8 Story

§ Comprehensive Java 8 support• lambda expressions a.k.a. closures

• Date and Time API (JSR-310)

• NIO-based HTTP client APIs

• parameter name discovery

• java.util.concurrent enhancements

§ Retaining support for Java 5 and higher• with Java 6 and 7 as common levels

• Java 8 potentially becoming popular rather quickly...

69

Thursday, January 24, 13

Page 100: The spring 32 update final

The Java EE 7 Story

§ Support for Java EE 7 API levels• JCache 1.0

• JMS 2.0

• JPA2.1

• JTA 1.2 (@Transactional)

• Bean Validation 1.1

• Servlet3.1

• JSF 2.2

§ Retaining support for Java EE 5 and higher

70

Thursday, January 24, 13

Page 101: The spring 32 update final

Annotation Driven JMS Endpoints

71

@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);

Thursday, January 24, 13

Page 102: The spring 32 update final

WebSocket Support

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

• but also generally for message-oriented architectures

72

Thursday, January 24, 13

Page 103: The spring 32 update final

Current and Upcoming: 3.1, 3.2, and 3.2

§ Spring Framework 3.1 (Dec 2011)• Environment profiles, Java-based configuration, declarative caching

• Initial Java 7 support, Servlet 3.0 based deployment

§ Spring Framework 3.2 (Dec 2012)• Gradle-based build, GitHub-based contribution model

• Fully Java 7 oriented, async MVC processing on Servlet 3.0

§ Spring Framework 3.3 (Q4 2013)• Comprehensive Java SE 8 support (including lambda expressions)

• Support for Java EE 7 API level and WebSockets

73

Thursday, January 24, 13

Page 104: The spring 32 update final

NOT CONFIDENTIAL -- TELL EVERYONE

@SpringSource @Starbuxman

Questions?Thursday, January 24, 13