whats new spring3

71
What's New in Spring 3.0 Chris Beams © 2010 SpringSource, A division of VMware. All rights reserved CONFIDENTIAL © 2010 SpringSource, A division of VMware. All rights reserved CONFIDENTIAL

Upload: manifromindia

Post on 07-Apr-2015

295 views

Category:

Documents


0 download

TRANSCRIPT

What's New in Spring 3.0

Chris Beams

© 2010 SpringSource, A division of VMware. All rights reserved

CONFIDENTIAL

© 2010 SpringSource, A division of VMware. All rights reserved

CONFIDENTIAL

Quick StatsQuick Stats

I l d i S i 2 5 6 GAIssues resolved since Spring 2.5.6 GA• 306 bugs• 279 improvements• 83 new features• 750+ issues in total as of 3.0 GA• 1050 as of 3.0.2

Spring 3 is backward-compatible• A drop-in replacement for Spring 2.5.x and earlierA drop in replacement for Spring 2.5.x and earlier

2CONFIDENTIALCONFIDENTIAL

Portfolio RearrangementsPortfolio Rearrangements

S i WS OXM S i CSpring WS OXM → Spring CoreSpring Web Flow type conversion → Spring CoreSpring Integration scheduling → Spring Corep g g g p gSpring JavaConfig → Spring Core

3CONFIDENTIALCONFIDENTIAL

Themes and FeaturesThemes and Features

D t ti E b dd d D t bDocumentationJava 5+IoC / DI enhancements

Embedded Databases OXM@MVC and REST

Expression LanguageType ConversionT k d S h d li

@ C a d SDeclarative ValidationPortlet 2.0J EE 6Tasks and Scheduling Java EE 6

4CONFIDENTIALCONFIDENTIAL

Documentation

5CONFIDENTIALCONFIDENTIAL

Improved Documentation

http://www springsource org/documentationhttp://www.springsource.org/documentationA major overhaul• For consistency, completeness & readability

6

Java 5+

7CONFIDENTIALCONFIDENTIAL

Core updated for Java 5+

Spring now depends on Java 5 or betterAll APIs and SPIs now fully generic & type safeV d i tVarargs used as appropriateEnums introducedStill binary compatibley p

8

Generics

public interface BeanFactory {

<T> T getBean(Class<T> requiredType);

<T> T getBean(String name, Class<T> requiredType);

<T> Map<String, T> getBeansOfType(Class<T> type);}}

9

Varargs

new ClassPathXmlApplicationContext("foo.xml");

<= Spring 2.5

new ClassPathXmlApplicationContext(new String[] { "foo.xml","bar.xml" });g

>= Spring 3.0

new ClassPathXmlApplicationContext("foo.xml");

new ClassPathXmlApplicationContext("foo.xml","bar.xml");

new ClassPathXmlApplicationContext("foo.xml","bar.xml","baz.xml");

public ClassPathXmlApplicationContext(String... configLocations);

Thanks to...

10

p pp g g

Enums

public enum HttpStatus {

CONTINUE(100);

OK(200);OK(200);

MOVED_PERMANENTLY(301);

NOT_FOUND(404);

INTERNAL SERVER ERROR(500)INTERNAL_SERVER_ERROR(500);

}

11

IoC / DI

12CONFIDENTIALCONFIDENTIAL

New XML Namespaces

<jdbc:*/><mvc:*/><oxm:*/><task:*/>

13

Additions to Annotation-Driven Injection

@@Value@DependsOn@Lazyy@Primary

@C fi ti@Configuration@Bean@Importp@ImportResource

A t ti C fi A li ti C t tAnnotationConfigApplicationContext

14

@Value in action

@Componentpublic class TransferService {

@AutowiredTransferService(@Value("${fee.amount}") double amt) {

...

}

}

15

A new code-based configuration approach

@Configuration@Import(InfrastructureConfig.class)public class AppConfig {

@Bean @Lazypublic TransferService transferService() {

TransferServiceImpl service =

new TransferServiceImpl();p

service.setAccountRepository(…);

return service;

}}

}

16

Bootstrapping with AnnotationConfigApplicationContext

public class Demo {public static void main(String... args) {

ApplicationContext context = newAnnotationConfigApplicationContext(AppConfig.class);

TransferService transferService = context.getBean(TransferService.class);

transferService.transfer(200.00, "A123", "C456");

}

}

17

Meta-Annotations

@Service

@Scope("request")

@Transactional(rollbackFor=Exception.class)

@R t ti (R t ti P li RUNTIME)@Retention(RetentionPolicy.RUNTIME)

public @interface MyService {}

@MyService@MyService

public class TransferService {

}

18

}

Further Support for Standardized Annotations

JSR-330 (@Inject)• Instead of Spring's @AutowiredJSR-220 @TransactionAttribute@• Instead of Spring's @TransactionalJSR-250 v1.1 @ManagedBean• Instead of Spring's @ManagedResource• Instead of Spring s @ManagedResource

19

Scoped Proxy Serializability

Scoped proxies may now be serialized• re-obtain references from a Spring ApplicationContext on deserialization• important for clustering and remoting use cases

20

Spring Expression Language

21CONFIDENTIALCONFIDENTIAL

Expression Language in Bean Definitions

<bean class="mycompany.RewardsTestDatabase">

<property name="databaseName"value="“#{systemProperties.databaseName}”/>

<property name="keyGenerator"value="“#{strategyBean databaseKeyGenerator}”/>value= #{strategyBean.databaseKeyGenerator} />

</bean>

22

Expression Language in Component Annotations

@Repository

public class RewardsTestDatabase {

@Value(“#{systemProperties.databaseName}”)

public void setDatabaseName(String dbName) { … }

@Value(“#{strategyBean.databaseKeyGenerator}”)

public void setKeyGenerator(KeyGenerator kg) { … }

}

23

}

Default Context Attributes

Exposed by default• "systemProperties", "systemEnvironment"

t ll S i d fi d b b• access to all Spring-defined beans by name• extensible through SPIDetermined at runtime (not init-time)

24

Web Context Attributes

Web-specific attributes:• "contextParameters"• "contextAttributes"• "request"• "session"JSF objects in a JSF request contextJSF objects in a JSF request context

25

Type Conversion

26CONFIDENTIALCONFIDENTIAL

Converter<S, T>

public interface Converter<S, T> {

T t(S )T convert(S source);

}

27

Converter<S, T>

Spring 3 introduces a new type conversion system• Designed to supersede PropertyEditor usage throughout the framework• Designed to supersede PropertyEditor usage throughout the framework• Stateless & thread-safe• Generic & type-safe• Sophisticated inference capabilities• Sophisticated inference capabilities

Many implementations out of the boxS C• StringToNumberConverter

• StringToEnumConverter• Rich support for dates including Joda Time• ...

Intended for use by end-users• Used throughout the framework internally• But implement one yourself any time custom type conversion is necessary

28

Implementing Converter<S,T>

class StringToFoo implements Converter<String, Foo> {

public Foo convert(String source) {public Foo convert(String source) {

Foo target = new Foo(source);

// any other conversion logic ...

return target;return target;

}

}

29

Converter<S, T>

<?xml version="1.0" encoding="UTF-8"?><beans>

<bean id="conversionService"class="org.sf...ConversionServiceFactoryBean">

<property name="converters"><set>

<bean name="com.acme.StringToFooConverter"></set>

</property></bean>/

</beans>

30

Converter<S, T>

Uses• Spring MVC data bindingSpring MVC data binding• In conjunction with @Autowired, @Value • Any ad-hoc use

31

Scheduling

32CONFIDENTIALCONFIDENTIAL

Lightweight Scheduling & Async task execution

Based on support first developed in Spring Integration 1.0

<task:*/><task: />@Scheduled@Async

33

Lightweight Scheduling

package com.acme;

@Component

public class Pojo {

@S h d l d(fi dD l 5000)@Scheduled(fixedDelay=5000)

public void doStuff() {

logger.log("doing stuff");

}}

}

34

Lightweight Scheduling

<?xml version="1.0" encoding="UTF-8"?><beans>

<context:component-scan base-package="com.acme"/>p p g /<task:annotation-driven/>

</beans>

35

Lightweight Scheduling

@Scheduled(fixedDelay=5000)• Delay measured from completion time of each task

@Scheduled(fixedRate=5000)@ ( )• Rate measured from start time of each task• Usually used in conjunction with a <task:scheduler/>

@Scheduled(cron="*/5 * * * * MON-FRI")

36

Lightweight Scheduling

<?xml version="1.0" encoding="UTF-8"?><beans>

<bean id="pojo" class="com.acme.Pojo" />

<task:scheduled-tasks scheduler="myScheduler"><task:scheduled ref="pojo" method="doStuff" fixed-rate="5000" />p j /

</task:scheduled-tasks>

<task:scheduler id="myScheduler" pool-size="10" />

</beans>

37

Easy Asynchronous Task Execution

package com.acme;

public class Worker {

@A@Async

public void doWork() { /* do time-intensive work */ }

}

38

Embedded Databases

39CONFIDENTIALCONFIDENTIAL

Convenient Support for Embedded Databases

Uses for embedded DBs in the enterprise• Early development• Prototyping• Shipping standalone / shrink-wrapped apps

Spring provides first-class support for• HSQL• H2H2• Derby

40

Introducing the <jdbc:*/> Namespace

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"

l i "htt // 3 /2001/XMLS h i t "xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:jdbc="http://www.springframework.org/schema/jdbc"xsi:schemaLocation="

http://www.springframework.org/schema/jdbchtt // i f k / h /jdb / i jdb dhttp://www.springframework.org/schema/jdbc/spring-jdbc.xsdhttp://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<b id " tR it " l " Jdb A tR it "><bean id="accountRepository" class="com.acme.JdbcAccountRepository"><constructor-arg ref="dataSource"/>

</bean>

<jdb b dd d d t b id "d t S " t "HSQL"><jdbc:embedded-database id="dataSource" type="HSQL"><jdbc:script location="classpath:/com/acme/schema.sql"><jdbc:script location="classpath:/com/acme/test-data.sql">

</jdbc:embedded-database>

</beans>

41

Object/XML Mapping

42CONFIDENTIALCONFIDENTIAL

Spring OXM

Migrated to Spring Core from Spring Web Services• OXM is useful not only for traditional WS• RESTful applications services & clients• RESTful applications, services & clients• Processing XML stored in DB

S t fSupport for• JAXB2• JiBX• Castor• XStream• XmlBeans

Provides common abstractions and programming model• Allowing for easier switching between marshallersg g• Greater ease of use in most cases

43

Spring OXM Abstractions

public interface Marshaller {void marshal(Object graph, Result result)

throws XmlMappingException, IOException}}

public interface Unmarshaller {Object unmarshal(Source source)throws XmlMappingException IOExceptionthrows XmlMappingException, IOException}

44

Spring OXM Abstractions

45

OXM in Action

public static void main(String... args) {ApplicationContext ctx =

new CPXAC("marshalling-config.xml");

Account account = new Account();account.setNumber("A123");account.setBalance(200.00);

Result result = new StreamResult(System.out);Marshaller m = ctx.getBean(Marshaller.class);m marshal(account result);m.marshal(account, result);

}

// console output123 200 00 /<account number="A123" balance="200.00"/>

46

marshalling-config.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:oxm="http://www.springframework.org/schema/oxm"

i h L ti "xsi:schemaLocation="

http://www.springframework.org/schema/oxm

http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<oxm:jaxb2-marshaller id="marshaller" contextPath="com.bank.domain"/>

</beans>

47

@MVC and REST

48CONFIDENTIALCONFIDENTIAL

<mvc:*/> namespace

*/new <mvc:*/> namespace• Simplifies configuration of Spring MVC internals

<mvc:annotation-driven/>• Sets up HandlerMapping / HandlerAdapters necessary to dispatch to

@Controllers@• Sets up sensible defaults for formatting, type conversion and more

<mvc:interceptors/><mvc:interceptors/>• Convenient support for registering Spring HandlerInterceptors• Allows for restriction based on paths

http://blog.springsource.com/2009/12/21/mvc-simplifications-in-spring-3-0

49

URI Templates

URI like string containing one or more variable namesURI-like string, containing one or more variable namesVariables can be substituted for values to become a URIHelps to create nice, “RESTful” URLs

URI Template Request Variables

/hotels/{hotel} /hotels/guoman hotel=guoman

/hotels/{hotel}/bookings /hotels/guoman/bookings hotel=guoman

/hotels/{hotel}/bookings/{booking}

/hotels/guoman/bookings/42

hotel=guomanbooking=42

50

@PathVariable

Optional@Controller@RequestMapping("/hotels/{hotel}")public class HotelsController {

Optional

@RequestMappingpublic void handleHotel(@PathVariable("hotel") String hotel)

{Matches /hotels/42

{// ...

}

@RequestMapping("bookings/{booking}")public void handleBooking(@PathVariable("hotel") String

hotel,@PathVariable int booking) {

// ...}

Matches /hotels/42/bookings/21

}

51

Views

Mime Type View

application/xml MarshallingView

application/atom+xml AbstractAtomFeedViewapplication/atom+xml AbstractAtomFeedView

application/rss+xml AbstractRssFeedView

application/json MappingJacksonJsonView

52

Other Goodies

HiddenHttpMethodFilter• Allows browsers to use PUT and DELETEShallowEtagHeaderFilter• Adds an ETag header to the response• Allows for client-side cachingAllows for client side cachingVarious handler method annotations• @RequestHeader• @RequestBody• @RequestBody• @ResponseBody• @CookieValue

http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/

53

RestTemplate

RestTemplate as core client-side componentSimilar to other templates in Spring• JdbcTemplate• JmsTemplate• WebServiceTemplate

54

RestTemplateString uri = "http://example.com/hotels/{id}";template = new RestTemplate();template = new RestTemplate();HotelList result = template.getForObject(uri,HotelList.class, "1");

Booking booking = // create booking objecturi = "http://example.com/hotels/{id}/bookings";Map<String, String> vars = Collections.singletonMap("id", "1");URI l ti t l t tF L ti ( i b ki )URI location = template.postForLocation(uri, booking, vars);

template.delete(location);

template.execute(uri, HttpMethod.GET,myRequestCallback,R C llb k)myResponseCallback);

http://blog.springsource.com/2009/03/27/rest-in-spring-3-resttemplate/

55

Other Goodies

HiddenHttpMethodFilter• Allows browsers to use PUT and DELETEShallowEtagHeaderFilter• Adds an ETag header to the response• Allows for client-side cachingAllows for client side cachingVarious handler method annotations• @RequestHeader• @RequestBody• @RequestBody• @ResponseBody• @CookieValue

http://blog.springsource.com/2009/03/08/rest-in-spring-3-mvc/

56

Declarative Validation

57CONFIDENTIALCONFIDENTIAL

Declarative Validation

Annotation-basedSame metadata can be used for multiple purposes• Persistence• Renderingg• Service validation• EtcJSR-303 "Bean Validation" as the common groundJSR-303 Bean Validation as the common groundBased on JSR-303

58

Declarative Validation Sample

public class Reward {p {

@NotNull

@Past@

private Date transactionDate;

}}

<form:input path="transactionDate">

59

Portlet 2.0

60CONFIDENTIALCONFIDENTIAL

Portlet 2.0 Support

@Controller

@RequestMapping("EDIT")

public class MyPortletController {

@ActionMapping("delete")

public void removeBook(@RequestParam("book") String bookId) {

this.myService.deleteBook(bookId);

}

@EventMapping("BookUpdate")

public void updateBook(BookUpdateEvent bookUpdate) {

// extract book entity data from event payload object// extract book entity data from event payload object

this.myService.updateBook(…);

}

}

61

Java EE 6

62CONFIDENTIALCONFIDENTIAL

Spring 3.0 and Java EE 6

Java EE 6 support in Spring 3 0Java EE 6 support in Spring 3.0• JSF 2.0• JPA 2.0

JSR 303 B V lid ti• JSR-303 Bean Validation• JSR-330 Dependency InjectionMore forthcoming in Spring 3.1• Servlet 3.0

63

Themes and FeaturesThemes and Features

D t ti E b dd d D t bDocumentationJava 5+IoC / DI enhancements

Embedded Databases OXM@MVC and REST

Expression LanguageType ConversionT k d S h d li

@ C a d SDeclarative ValidationPortlet 2.0J EE 6Tasks and Scheduling Java EE 6

64CONFIDENTIALCONFIDENTIAL

Upgrading to Spring 3Upgrading to Spring 3

B k d tibilitBackward compatibilityPruning & deprecationGotchasRecommendations

65CONFIDENTIALCONFIDENTIAL

Pruning & Deprecation

Pruned• Commons Attributes support• legacy TopLink API support

Deprecated• MVC controller hierarchy• JUnit 3 8 support• JUnit 3.8 support• Struts 1.x support• several outdated helper classes

66

Backward Compatibility

Spring 3 is a drop-in replacement for earlier versions• 100% backward compatibility in programming model / public API• 95% compatibility in integration points / internalsp y g p

No need to change component code• Upgrade today• Upgrade today• Incrementally adopt Spring 3 features as time and resources allow

67

Gotchas when Upgrading

Modules have been renamed• Don't let this throw you; they're primarily the same

Monolithic spring.jar distribution is no longer available• only individual module jars• Maven / Ivy are your friends• Maven / Ivy are your friends• All Spring 3.0.x.RELEASE artifacts are available in Maven Central

68

Recommendations

Consider moving to Spring 2.5/3.0 annotations when upgrading• Instead of sticking to 100% XML• Classpath scanning and POJO annotations leave minimal XMLp g• "If you own it, annotate it"

Consider adopting standard annotationsConsider adopting standard annotations• JSR-330 in Spring-managed beans• JSR-303 in entities

Consider using (custom) stereotype annotations• Adds richer semantics throughout your codebase• Opens up opportunities for adding services via AOP without complicated

pointcuts

69

RoadmapRoadmap

3 0 2 i il bl3.0.2 is available now• 3.0.3 in the next few weeks3.1 planning and early development is underwayp g y p y• Further support for Java EE 6 (e.g.: Servlet 3.0)• Conversation management facility• Environment-specific beansp• Refreshable bean configuration• Move to Maven build system• Serve as the foundation forServe as the foundation for

• Spring Web Flow 3• Spring Integration 2• Spring Roo

70CONFIDENTIALCONFIDENTIAL

p g

SummarySummary

S i 3 i il bl d d f i tiSpring 3 is available and ready for primetime• A drop-in replacement• If you're not using it already, give it a try• If you are, give us feedback!Spring provides early support for Java EE 6• No waiting necessary for app server vendors to catch upg y pp pContinued enhancements in DI and ease of useFully embraces Java 5, RESTS EL i t dSpEL introduces new power

71CONFIDENTIALCONFIDENTIAL