Asynchronous Task Execution in Spring
In version 3.0, Spring also supports using annotations to execute a task asynchronously. To use it, you
just need to annotate the method with @Async.
Let's go through a simple example to see it in action. Listing 15-13 and Listing 15-14 show the
AsyncService interface and its implementation class AsyncServiceImpl, respectively.
Listing 15-13. The AsyncService Interface
package com.apress.prospring3.ch15.service;
import java.util.concurrent.Future;
public interface AsyncService {
public void asyncTask();
public Future<String> asyncWithReturn(String name);
}
Listing 15-14. The AsyncServiceImpl Class
package com.apress.prospring3.ch15.service.async;
import java.util.concurrent.Future;
import
org.slf4j.Logger;
import
org.slf4j.LoggerFactory;
import
org.springframework.scheduling.annotation.Async;
import
org.springframework.scheduling.annotation.AsyncResult;
import
org.springframework.stereotype.Service;
import com.apress.prospring3.ch15.service.AsyncService;
@Service("asyncService")
public class AsyncServiceImpl implements AsyncService {
final Logger logger = LoggerFactory.getLogger(AsyncServiceImpl.class);
@Async
public void asyncTask() {
logger.info("Start execution of async. task");
try {
Thread.sleep(10000);
} catch (Exception ex) {
ex.printStackTrace();
}
logger.info("Complete execution of async. task");
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home