Your SlideShare is downloading. ×
  • Like
  • Save
the Spring 4 update
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×

Now you can save presentations on your phone or tablet

Available for both IPhone and Android

Text the download link to your phone

Standard text messaging rates apply

the Spring 4 update

  • 2,496 views
Published

This talk introduces some of the compelling features coming in Spring 3.1, 3.2 and then gazes into the future and looks at some of the powerful new features in the upcoming Spring 4.0 release.

This talk introduces some of the compelling features coming in Spring 3.1, 3.2 and then gazes into the future and looks at some of the powerful new features in the upcoming Spring 4.0 release.

Published in Technology , Education
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
2,496
On SlideShare
0
From Embeds
0
Number of Embeds
3

Actions

Shares
Downloads
0
Comments
0
Likes
12

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide

Transcript

  • 1. © 2013 SpringSource, by VMwareThe Spring UpdateJosh Long (⻰龙之春)@starbuxmanjoshlong.comjosh.long@springsource.comslideshare.net/joshlongTuesday, June 11, 13
  • 2. Josh Long (⻰龙之春)@starbuxmanjoshlong.comjosh.long@springsource.comslideshare.net/joshlongJosh Long (⻰龙之春)@starbuxmanjoshlong.comjosh.long@springsource.comslideshare.net/joshlongTuesday, June 11, 13
  • 3. Josh Long (⻰龙之春)@starbuxmanjoshlong.comjosh.long@springsource.comslideshare.net/joshlongContributor To:•Spring Integration•Spring Batch•Spring Hadoop•Activiti Workflow EngineTuesday, June 11, 13
  • 4. Current and Upcoming: 3.1, 3.2, and 4§ 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 4 (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 WebSockets4Tuesday, June 11, 13
  • 5. Spring 3.15Tuesday, June 11, 13
  • 6. 6Spring 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 7Tuesday, June 11, 13
  • 7. Not confidential. Tell everyone.So, What’s All of This Look Like in Code?7Tuesday, June 11, 13
  • 8. Not confidential. Tell everyone.I want Database Access ... with Hibernate 4 Support8@Servicepublic class CustomerService {public Customer getCustomerById( long customerId) {...}public Customer createCustomer( String firstName, String lastName, Date date){...}}Tuesday, June 11, 13
  • 9. Not confidential. Tell everyone.I want Database Access ... with Hibernate 4 Support9@Servicepublic class CustomerService {@Injectprivate 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;}}Tuesday, June 11, 13
  • 10. Not confidential. Tell everyone.I want Database Access ... with Hibernate 4 Support10@Servicepublic class CustomerService {@Injectprivate SessionFactory sessionFactory;@Transactionalpublic 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;}}Tuesday, June 11, 13
  • 11. Not confidential. Tell everyone.I want Declarative Cache Management...11@Servicepublic class CustomerService {@Injectprivate SessionFactory sessionFactory;@Transactional(readOnly = true)@Cacheable(“customers”)public Customer getCustomerById( long customerId) {...}...}Tuesday, June 11, 13
  • 12. Not confidential. Tell everyone.I want a RESTful Endpoint...12package org.springsource.examples.spring31.web;..@Controllerpublic class CustomerController {@Injectprivate CustomerService customerService;@RequestMapping(value = "/customer/{id}" )public HttpEntity<Customer> customerById( @PathVariable Integer id ) {return new ResponseEntity<Customer>( customerService.getCustomerById( id ), HttpStatus.OK );}...}Tuesday, June 11, 13
  • 13. Not confidential. Tell everyone....But Where’d the SessionFactory come from?13Tuesday, June 11, 13
  • 14. Not confidential. Tell everyone.A Quick Primer on Configuration in Spring 3.1....<beans><tx:annotation-driven transaction-manager = "transactionManager" /><context:component-scan base-package = "some.package" /><context:property-placeholder properties = "config.properties" /><bean id = "transactionManager" 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.username}"/>...</bean></beans>ApplicationContext ctx = new ClassPathXmlApplication( “service-config.xml” );Tuesday, June 11, 13
  • 15. Not confidential. Tell everyone.A Quick Primer on Configuration in Spring 3.1@Configuration@PropertySource(“config.properties”)@EnableTransactionManagement@ComponentScanpublic class ApplicationConfiguration {@Inject private Environment environment;@Bean public PlatformTransactionManager transactionManager( SessionFactory sf ){return new HibernateTransactionManager( sf );}@Bean public SessionFactory sessionFactory (){ ... }@Bean public DataSource dataSource(){SimpleDriverDataSource sds = new SimpleDriverDataSource();sds.setUserName( environment.getProperty( “ds.username”));// ...return sds;}}ApplicationContext ctx = new AnnotationConfigApplicationContext( ApplicationConfiguration.class );Tuesday, June 11, 13
  • 16. 16Bean Definition Profiles@Configuration@Profile(“production”)public class ProductionDataSourceConfiguration {@Bean public javax.sql.DataSource dataSource(){return new SimpleDriverDataSource( .. ) ;}}@Configuration@Profile(“embedded”)public class LocalDataSourceConfiguration {@Bean public javax.sql.DataSource dataSource(){return new EmbeddedDatabaseFactoryBean( ... );}}@Configuration@Import( { LocalDataSourceConfiguration.class, ProductionDataSourceConfiguration.class } )public class ServiceConfiguration {// EmbeddedDatabaseFactoryBean@Bean public CustomerService customerService( javax.sql.DataSource dataSource ){// ...-Dspring.profiles.active=embeddedTuesday, June 11, 13
  • 17. 17Bean Definition Profiles<beans><beans profile=”embedded”><jdbc:embedded-datasource id= “ds” ... /></beans><beans profile= “production” ><bean id= “ds” class = “...DataSource” .. /></beans></beans>-Dspring.profiles.active=embeddedTuesday, June 11, 13
  • 18. 18Test Context Framework@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(loader=AnnotationConfigContextLoader.class,classes={TransferServiceConfig.class, DataConfig.class})@ActiveProfiles("dev")public class TransferServiceTest {@Autowiredprivate TransferService transferService;@Testpublic void testTransferService() {...}}Tuesday, June 11, 13
  • 19. 19"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"/>Tuesday, June 11, 13
  • 20. 20Cache AbstractionTuesday, June 11, 13
  • 21. 20Cache Abstraction§ CacheManager and Cache abstraction• in org.springframework.cache• which up until 3.0 just contained EhCache support• particularly important with the rise of distributedcaching• not least of it all: in cloud environmentsTuesday, June 11, 13
  • 22. 20Cache Abstraction§ CacheManager and Cache abstraction• in org.springframework.cache• which up until 3.0 just contained EhCache support• particularly important with the rise of distributedcaching• not least of it all: in cloud environmentsTuesday, June 11, 13
  • 23. 20Cache Abstraction§ CacheManager and Cache abstraction• in org.springframework.cache• which up until 3.0 just contained EhCache support• particularly important with the rise of distributedcaching• not least of it all: in cloud environments§ Backend adapters for EhCache, GemFire,Coherence, etc• EhCache adapter shipping with Spring coreTuesday, June 11, 13
  • 24. 20Cache Abstraction§ CacheManager and Cache abstraction• in org.springframework.cache• which up until 3.0 just contained EhCache support• particularly important with the rise of distributedcaching• not least of it all: in cloud environments§ Backend adapters for EhCache, GemFire,Coherence, etc• EhCache adapter shipping with Spring coreTuesday, June 11, 13
  • 25. 20Cache Abstraction§ CacheManager and Cache abstraction• in org.springframework.cache• which up until 3.0 just contained EhCache support• particularly important with the rise of distributedcaching• 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 – throughprofiles?• potentially even adapting to a runtime-providedserviceTuesday, June 11, 13
  • 26. 20Cache Abstraction§ CacheManager and Cache abstraction• in org.springframework.cache• which up until 3.0 just contained EhCache support• particularly important with the rise of distributedcaching• 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 – throughprofiles?• potentially even adapting to a runtime-providedservice@Cacheable ( name = “owner”)public Owner loadOwner(int id);Tuesday, June 11, 13
  • 27. 20Cache Abstraction§ CacheManager and Cache abstraction• in org.springframework.cache• which up until 3.0 just contained EhCache support• particularly important with the rise of distributedcaching• 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 – throughprofiles?• potentially even adapting to a runtime-providedservice@Cacheable ( name = “owner”)public Owner loadOwner(int id);@Cacheable(name = “owners”,condition="name.length < 10")Tuesday, June 11, 13
  • 28. 20Cache Abstraction§ CacheManager and Cache abstraction• in org.springframework.cache• which up until 3.0 just contained EhCache support• particularly important with the rise of distributedcaching• 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 – throughprofiles?• potentially even adapting to a runtime-providedservice@Cacheable ( name = “owner”)public Owner loadOwner(int id);@Cacheable(name = “owners”,condition="name.length < 10")public Owner loadOwner(String name);Tuesday, June 11, 13
  • 29. 20Cache Abstraction§ CacheManager and Cache abstraction• in org.springframework.cache• which up until 3.0 just contained EhCache support• particularly important with the rise of distributedcaching• 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 – throughprofiles?• potentially even adapting to a runtime-providedservice@Cacheable ( name = “owner”)public Owner loadOwner(int id);@Cacheable(name = “owners”,condition="name.length < 10")public Owner loadOwner(String name);@CacheEvict (name = “owners”)Tuesday, June 11, 13
  • 30. 20Cache Abstraction§ CacheManager and Cache abstraction• in org.springframework.cache• which up until 3.0 just contained EhCache support• particularly important with the rise of distributedcaching• 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 – throughprofiles?• potentially even adapting to a runtime-providedservice@Cacheable ( name = “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);Tuesday, June 11, 13
  • 31. 21Servlet 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.2Tuesday, June 11, 13
  • 32. 22WebApplicationInitializer Example/**Automatically detected and invoked on startup by SpringsServletContainerInitializer. May register listeners, filters,servlets etc against the given Servlet 3.0 ServletContext.*/public class MyApplicationWebApplicationInitializer implements WebApplicationInitializer {public void onStartup(ServletContext sc) throws ServletException {// create ‘root’ Spring ApplicationContextAnnotationConfigWebApplicationContext root = root AnnotationConfigWebApplicationContext();root.scan("com.mycompany.myapp");root.register(FurtherConfig.class);// Manages the lifecycle of the root application contextsc.addListener(new ContextLoaderListener(root));}}Tuesday, June 11, 13
  • 33. 23@MVC Processing & Flash AttributesTuesday, June 11, 13
  • 34. 23@MVC Processing & Flash Attributes§ RequestMethodHandlerAdapterl arbitrary mappings to handler methods across multiple controllersl better customization of handler method arguments− HandlerMethodArgumentResolver− HandlerMethodReturnValueHandler− etcTuesday, June 11, 13
  • 35. 23@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 users sessionl an incoming FlashMap for a request will automatically get exposed to the modelTuesday, June 11, 13
  • 36. github.com/SpringSource24Tuesday, June 11, 13
  • 37. Spring 3.225Tuesday, June 11, 13
  • 38. 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 Q1 2014• 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.26Tuesday, June 11, 13
  • 39. 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 variables27Tuesday, June 11, 13
  • 40. Async MVC Processing: Callable28@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, etcTuesday, June 11, 13
  • 41. Async MVC Processing: DeferredResult29@RequestMapping("/quotes")@ResponseBodypublic 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.Tuesday, June 11, 13
  • 42. Async MVC Processing: AsyncTask30@RequestMapping(name =“/upload”, method=RequestMethod.POST)public AsyncTask<Foo> processUpload(MultipartFile file) {TaskExecutor asyncTaskExecutor = new AsyncTaskExecutor(...);return new AsyncTask<Foo>(1000L, // timeoutasyncTaskExecutor, // thread poolnew Callable<Foo>(){ ..} // thread);}- same as Callable, with extra features- override timeout value for async processing- lets you specify a specific AsyncTaskExecutorTuesday, June 11, 13
  • 43. Content Negotiation Strategies31ContentNegotiationStrategy• 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 optionContentNegotiationManager• has one or more ContentNegotiationStrategy instances• works with:RequestMappingHandlerMapping,RequestMappingHandlerAdapter,ExceptionHandlerExceptionResolverContentNegotiatingViewResolverTuesday, June 11, 13
  • 44. Matrix Variables32"Each path segment may include asequence of parameters, indicated by thesemicolon ";" character. The parametersare not significant to the parsing ofrelativeb references.RFC 2396, section 3.3Tuesday, June 11, 13
  • 45. Matrix Variables33"The semicolon (";") and equals ("=") reserved charactersare often used to delimit parameters andparameter values applicable to that segment. Thecomma (",") reserved character is often used forsimilar purposes."RFC 3986, section 3.3Tuesday, June 11, 13
  • 46. Matrix Variables§ Two Types of Usages§ Path Segment Name-Value Pairs§ As delimited list path segment34/qa-releases;buildNumber=135;revision=3.2/answers/id1;id2;id3;id4/commentsTuesday, June 11, 13
  • 47. Matrix Variables: the common case35// GET /pets/42;q=11;r=22@RequestMapping(value = "/pets/{petId}")public void findPet(@PathVariable String petId, @MatrixVariable int q) {// petId == 42// q == 11}Tuesday, June 11, 13
  • 48. Matrix Variables: obtain all matrix variables36// 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]}Tuesday, June 11, 13
  • 49. Matrix Variables: qualify path segment37// 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}Tuesday, June 11, 13
  • 50. 38MVC Test Framework Serverimport ... MockMvcBuilders.* ;import ... MockMvcRequestBuilders.*;import ... MockMvcResultMatchers.*;@RunWith(SpringJUnit4ClassRunner.class)@WebAppConfiguration@ContextConfiguration("servlet-context.xml")public class SampleTests {   @Autowired  private WebApplicationContext wac;   private MockMvc mockMvc;   @Before  public void setup() {    this.mockMvc = webAppContextSetup(this.wac).build();  }   @Test  public void getFoo() throws Exception {    this.mockMvc.perform(get("/foo").accept("application/json"))        .andExpect(status().isOk())        .andExpect(content().mimeType("application/json"))        .andExpect(jsonPath("$.name").value("Lee"));  }}Tuesday, June 11, 13
  • 51. 39MVC Test Framework ClientRestTemplate restTemplate = new RestTemplate();MockRestServiceServer mockServer = MockRestServiceServer.createServer(restTemplate); mockServer.expect(requestTo("/greeting"))  .andRespond(withSuccess("Hello world", "text/plain")); // use RestTemplate ... mockServer.verify();Tuesday, June 11, 13
  • 52. Spring 440Tuesday, June 11, 13
  • 53. Spring Framework 4 (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 proper41Tuesday, June 11, 13
  • 54. 42§ you can follow along at home..Spring Framework 4 (Q4 2013)Tuesday, June 11, 13
  • 55. The Java SE 8 and Java EE 7 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§ 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.243§ Retaining support for Java 5 and higher• with Java 6 and 7 as common levels• Java 8 potentially becoming popular rather quickly...Tuesday, June 11, 13
  • 56. Resource Caching§ expanding mvc:resources§ Support for pre-processing resources§ Might look similar to the Grails resource pipeline44Tuesday, June 11, 13
  • 57. Groovy Support§ Groovy BeanBuilder might make it into Spring 4 core§ Enhanced language level support45Tuesday, June 11, 13
  • 58. @Conditional46@Retention(RetentionPolicy.RUNTIME)@Target({ ElementType.TYPE, ElementType.METHOD })public @interface Conditional { /** * All {@link Condition}s that must {@linkplain Condition#matches match} in order for * the component to be registered. */ Class<? extends Condition>[] value();}public interface Condition { /** * Determine if the condition matches. * @param context the condition context * @param metadata meta-data of the {@link AnnotationMetadata class} or * {@link MethodMethod method} being checked. * @return {@code true} if the condition matches and the component can be registered * or {@code false} to veto registration. */ boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata);}Tuesday, June 11, 13
  • 59. JDK 8 Support In-Depth§ implicit use of LinkedHash{Map|Set} instead of HashMap/Set to preserver ordering diffs in JDK 7 and JDK 8§ Embed ASM 4.1 into Spring codebase tosupport JDK8 bytecode changes and to keep compatability cglib 3.0§ JDK 8 Date and Time (JSR 310)§ add awatTerminationSeconds / commonPool properties to ForkJoinPoolFactoryBean to support JDK8 changes§ Incorporate JDK 8 reflection support (java.lang.reflect.Parameter)47Tuesday, June 11, 13
  • 60. JMS 2.0 Support48<jms:annotation-driven>@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);Tuesday, June 11, 13
  • 61. Bean Validation 1.1 Support in Spring49§ now works with Hibernate Validator 5§ MethodValidationInterceptor auto-detects Bean Validation 1.1s ExecutableValidator API nowand uses it in favor of Hibernate Validator 4.2s native variant.Tuesday, June 11, 13
  • 62. JSR 236 (ManagedExecutorService) support50• ConcurrentTask(Executor|Scheduler) now automatically detect aJSR 236 ManagedExecutorService and adapt themTuesday, June 11, 13
  • 63. • simplest case: let JSR 356 scan for your endpoint• drawback: scanning takes a long timeWeb Sockets Support (JSR-356) - Servlet scanning51import javax.websocket.server.ServerEndpoint;import org.springframework.web.socket.server.endpoint. SpringConfigurator. @ServerEndpoint(value = "/echo", configurator = SpringConfigurator.class)public class EchoEndpoint {   private final EchoService echoService;   @Autowired  public EchoEndpoint(EchoService echoService) {    this.echoService = echoService;  }   @OnMessage  public void handleMessage(Session session, String message) {    // ...  } }Tuesday, June 11, 13
  • 64. Web Sockets Support (JSR-356) - Spring container-centric registration (you can turn off scan)52import org.springframework.web.socket.server.endpoint.ServerEndpointExporter;import org.springframework.web.socket.server.endpoint.ServerEndpointRegistration; @Configurationpublic class EndpointConfig {@Bean public EchoService service(){ ... }   @Bean  public EchoEndpoint echoEndpoint(EchoService service) {    return new EchoEndpoint(service );  } // once per application  @Bean  public ServerEndpointExporter endpointExporter() {    return new ServerEndpointExporter();  }  }Tuesday, June 11, 13
  • 65. import org.springframework.web.socket.server.endpoint.ServerEndpointExporter;import org.springframework.web.socket.server.endpoint.ServerEndpointRegistration; @Configurationpublic class EndpointConfig {@Bean public EchoService service(){ ... } @Bean public EchoEndpoint endpoint(EchoService service) {return new EchoEndpoint( service );}  @Bean  public EndpointRegistration echoEndpointRegistration (EchoEndpoint eep ) {    return new EndpointRegistration(“/echo”, eep );  } // once per application  @Bean  public ServerEndpointExporter endpointExporter() {    return new ServerEndpointExporter();  }}Web Sockets Support (JSR-356) - Spring container-centric registration (you can turn off scan)endpoint class endpoint instanceinstance per socket Spring scopeTuesday, June 11, 13
  • 66. Web Sockets Support (Spring Web Sockets Abstraction)54§ rooted in org.springframework.web.socket§ not meant to be consumed directly, too low level.§ A good practice is one handler (and one web socket) per application.§ You’d have to handle all requests with one class and handler.§ (Imagine REST without verbs, too limited!)§ This begs for a higher level API with annotations.§ Basis for other support, including SockJS§ More flexible API, first (and likely permanent) implementation based on Jetty 9§ implementation based on Jetty 9§ API rooted at WebSocketHandlerTuesday, June 11, 13
  • 67. import org.springframework.web.socket.adapter.TextWebSocketHandlerAdapter; public class EchoHandler extends TextWebSocketHandlerAdapter {   @Override  public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {    session.sendMessage(message);  } }Web Sockets Support (Spring Web Sockets Abstraction - WebSocketHandler)Tuesday, June 11, 13
  • 68. import org.springframework.web.socket.server.support. WebSocketHttpRequestHandler; @Configurationpublic class WebConfig {@Bean public EchoHandler handler(){ ... }   @Bean  public SimpleUrlHandlerMapping handlerMapping(EchoHandler handler ) {     Map<String, Object> urlMap = new HashMap<String, Object>();    urlMap.put("/echo", new WebSocketHttpRequestHandler( handler ));     SimpleUrlHandlerMapping hm = new SimpleUrlHandlerMapping();    hm.setUrlMap(urlMap);    return hm;  } }Web Sockets Support (Spring Web Sockets Abstraction - WebSocketHandler)Tuesday, June 11, 13
  • 69. import org.springframework.web.socket.sockjs.SockJsService;// ... @Configurationpublic class WebConfig {   @Bean  public SimpleUrlHandlerMapping handlerMapping( EchoHandler handler, TaskScheduler ts ) {     SockJsService sockJsService = new DefaultSockJsService( ts );     Map<String, Object> urlMap = new HashMap<String, Object>();    urlMap.put("/echo/**", new SockJsHttpRequestHandler(sockJsService, handler ));     SimpleUrlHandlerMapping hm = new SimpleUrlHandlerMapping();    hm.setUrlMap(urlMap);    return hm;  }   @Bean  public TaskScheduler taskScheduler() { ... } }Web Sockets Support (Spring Web Sockets Abstraction - SockJS)Tuesday, June 11, 13
  • 70. import org.springframework.web.socket.client.endpoint.AnnotatedEndpointConnectionManager; @Configurationpublic class EndpointConfig {   // For Endpoint sub-classes use EndpointConnectionManager instead   @Bean  public AnnotatedEndpointConnectionManager connectionManager(EchoEndpoint endpoint) {    return new AnnotatedEndpointConnectionManager(endpoint, "ws://localhost:8080/webapp/echo");  }   @Bean  public EchoEndpoint echoEndpoint() {    // ...  } }Web Sockets Support (client side)Tuesday, June 11, 13
  • 71. JMS 2.0 Support59• Added "deliveryDelay" property on JmsTemplate• Added support for "deliveryDelay" and CompletionListener to CachedMessageProducer• Added support for the new "create(Shared)DurableConsumer" variants in Spring’sCachingConnectionFactory• Added support for the new "createSession" variants with fewer parameters in Spring’sSingleConnectionFactoryTuesday, June 11, 13
  • 72. 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 WebSockets60Tuesday, June 11, 13
  • 73. NOT CONFIDENTIAL -- TELL EVERYONE@SpringSource @StarbuxmanQuestions?Tuesday, June 11, 13