This document summarizes Josh Long's presentation on updates to the Spring framework. It discusses:
- Spring Framework versions 3.1, 3.2, and the upcoming 4.0 release
- New features in Spring 3.1 including environment profiles, Java-based configuration, caching, and Servlet 3.0 support
- Plans for Spring 3.2 including a Gradle build, contribution model on GitHub, and asynchronous MVC processing
- Changes to plans for Spring 3.2 where support for Java EE 7 and Java SE 8 was postponed due to delays in those projects. Spring 3.2 will instead focus on core framework refinements with Java 8 and EE 7 features planned for Spring 3.
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 WebSockets
4
Tuesday, June 11, 13
6. 6
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
Tuesday, June 11, 13
7. Not confidential. Tell everyone.
So, What’s All of This Look Like in Code?
7
Tuesday, June 11, 13
8. Not confidential. Tell everyone.
I want Database Access ... with Hibernate 4 Support
8
@Service
public 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 Support
9
@Service
public class CustomerService {
@Inject
private SessionFactory sessionFactory;
public Customer createCustomer(String firstName,
String lastName,
Date signupDate) {
Customer customer = new Customer();
customer.setFirstName(firstName);
customer.setLastName(lastName);
customer.setSignupDate(signupDate);
sessionFactory.getCurrentSession().save(customer);
return customer;
}
}
Tuesday, June 11, 13
10. Not confidential. Tell everyone.
I want Database Access ... with Hibernate 4 Support
10
@Service
public class CustomerService {
@Inject
private SessionFactory sessionFactory;
@Transactional
public Customer createCustomer(String firstName,
String lastName,
Date signupDate) {
Customer customer = new Customer();
customer.setFirstName(firstName);
customer.setLastName(lastName);
customer.setSignupDate(signupDate);
sessionFactory.getCurrentSession().save(customer);
return customer;
}
}
Tuesday, June 11, 13
11. Not confidential. Tell everyone.
I want Declarative Cache Management...
11
@Service
public class CustomerService {
@Inject
private 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...
12
package org.springsource.examples.spring31.web;
..
@Controller
public class CustomerController {
@Inject
private 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?
13
Tuesday, 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
@ComponentScan
public 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. 16
Bean 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=embedded
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 application's class files
<bean class="…" c:age="10" c:name="myName"/>
<bean class="…" c:name-ref="nameBean" c:spouse-ref="spouseBean"/>
Tuesday, June 11, 13
21. 20
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
Tuesday, June 11, 13
22. 20
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
Tuesday, June 11, 13
23. 20
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
Tuesday, June 11, 13
24. 20
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
Tuesday, June 11, 13
25. 20
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
Tuesday, June 11, 13
26. 20
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
@Cacheable ( name = “owner”)
public Owner loadOwner(int id);
Tuesday, June 11, 13
27. 20
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
@Cacheable ( name = “owner”)
public Owner loadOwner(int id);
@Cacheable(name = “owners”,
condition="name.length < 10")
Tuesday, June 11, 13
28. 20
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
@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. 20
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
@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. 20
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
@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. 21
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
Tuesday, June 11, 13
32. 22
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 MyApplicationWebApplicationInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext sc) throws ServletException {
// create ‘root’ Spring ApplicationContext
AnnotationConfigWebApplicationContext root = root AnnotationConfigWebApplicationContext();
root.scan("com.mycompany.myapp");
root.register(FurtherConfig.class);
// Manages the lifecycle of the root application context
sc.addListener(new ContextLoaderListener(root));
}
}
Tuesday, June 11, 13
34. 23
@MVC Processing & Flash Attributes
§ RequestMethodHandlerAdapter
l arbitrary mappings to handler methods across multiple controllers
l better customization of handler method arguments
− HandlerMethodArgumentResolver
− HandlerMethodReturnValueHandler
− etc
Tuesday, June 11, 13
35. 23
@MVC Processing & Flash Attributes
§ RequestMethodHandlerAdapter
l arbitrary mappings to handler methods across multiple controllers
l better customization of handler method arguments
− HandlerMethodArgumentResolver
− HandlerMethodReturnValueHandler
− etc
§ FlashMap support and FlashMapManager abstraction
l with RedirectAttributes as a new @MVC handler method argument type
− explicitly calling addFlashAttribute to add values to the output FlashMap
l an outgoing FlashMap will temporarily get added to the user's session
l an incoming FlashMap for a request will automatically get exposed to the model
Tuesday, 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.
26
Tuesday, 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 variables
27
Tuesday, June 11, 13
40. Async MVC Processing: Callable
28
@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
Tuesday, June 11, 13
41. Async MVC Processing: DeferredResult
29
@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.
Tuesday, June 11, 13
42. Async MVC Processing: AsyncTask
30
@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
Tuesday, June 11, 13
43. Content Negotiation Strategies
31
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
Tuesday, June 11, 13
44. Matrix Variables
32
"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
Tuesday, June 11, 13
45. Matrix Variables
33
"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
Tuesday, June 11, 13
46. Matrix Variables
§ Two Types of Usages
§ Path Segment Name-Value Pairs
§ As delimited list path segment
34
/qa-releases;buildNumber=135;revision=3.2
/answers/id1;id2;id3;id4/comments
Tuesday, June 11, 13
47. Matrix Variables: the common case
35
// 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 variables
36
// 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 segment
37
// 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. 38
MVC Test Framework Server
import ... 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. 39
MVC Test Framework Client
RestTemplate 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
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 proper
41
Tuesday, 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.2
43
§ 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 pipeline
44
Tuesday, June 11, 13
57. Groovy Support
§ Groovy BeanBuilder might make it into Spring 4 core
§ Enhanced language level support
45
Tuesday, June 11, 13
58. @Conditional
46
@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 to
support 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 JDK
8 changes
§ Incorporate JDK 8 reflection support (java.lang.reflect.Parameter)
47
Tuesday, June 11, 13
61. Bean Validation 1.1 Support in Spring
49
§ now works with Hibernate Validator 5
§ MethodValidationInterceptor auto-detects Bean Validation 1.1's ExecutableValidator API now
and uses it in favor of Hibernate Validator 4.2's native variant.
Tuesday, June 11, 13
62. JSR 236 (ManagedExecutorService) support
50
• ConcurrentTask(Executor|Scheduler) now automatically detect a
JSR 236 ManagedExecutorService and adapt them
Tuesday, June 11, 13
63. • simplest case: let JSR 356 scan for your endpoint
• drawback: scanning takes a long time
Web Sockets Support (JSR-356) - Servlet scanning
51
import 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)
52
import org.springframework.web.socket.server.endpoint.ServerEndpointExporter;
import org.springframework.web.socket.server.endpoint.ServerEndpointRegistration;
@Configuration
public 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;
@Configuration
public 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 instance
instance per socket Spring scope
Tuesday, 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 WebSocketHandler
Tuesday, 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;
@Configuration
public 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;
// ...
@Configuration
public 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;
@Configuration
public 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 Support
59
• Added "deliveryDelay" property on JmsTemplate
• Added support for "deliveryDelay" and CompletionListener to CachedMessageProducer
• Added support for the new "create(Shared)DurableConsumer" variants in Spring’s
CachingConnectionFactory
• Added support for the new "createSession" variants with fewer parameters in Spring’s
SingleConnectionFactory
Tuesday, 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 WebSockets
60
Tuesday, June 11, 13
73. NOT CONFIDENTIAL -- TELL EVERYONE
@SpringSource @Starbuxman
Questions?
Tuesday, June 11, 13