Spring MVC 3.2 Preview: Introducing Servlet 3, Async Support
Last updated on November 5th, 2012 (Spring MVC 3.2 RC1)
Overview
Spring MVC 3.2 introduces Servlet 3 based asynchronous request processing. This is the first of several blog posts covering this new capability and providing context in which to understand how and why you would use it.
The main purpose of early releases is to seek feedback. We've received plenty of it both here and in JIRA since this was first posted after the 3.2 M1 release. Thanks to everyone who gave it a try and commented! There have been numerous changes and there is still time for more feedback!
At a Glance
From a programming model perspective the new capabilities appear deceptively simple. A controller method can now return a java.util.concurrent.Callable
to complete processing asynchronously. Spring MVC will then invoke the Callable
in a separate thread with the help of a TaskExecutor
. Here is a code snippet before:
// Before
@RequestMapping(method=RequestMethod.POST)
public String processUpload(final MultipartFile file) {
// ...
return "someView";
}
// After
@RequestMapping(method=RequestMethod.POST)
public Callable<String> processUpload(final MultipartFile file) {
return new Callable<String>() {
public Object call() throws Exception {
// ...
return "someView";
}
};
}
A controller method can also return a DeferredResult
(new type in Spring MVC 3.2) to complete processing in a thread not known to Spring MVC. For example reacting to a JMS or an AMQP message, a Redis notification, and so on. Here is another code snippet:
@RequestMapping("/quotes")
@ResponseBody
public DeferredResult<String> quotes() {
DeferredResult<String> deferredResult…