应用场景:
1、某些耗时较长的而用户不需要等待该方法的处理结果
2、某些耗时较长的方法,后面的程序不需要用到这个方法的处理结果时
要点:
1、In short, the context loaded by the ContextLoaderListener (generally from applicationContext.xml) is the parent of the context loaded by the DispatcherServlet (generally from *-servlet.xml). If you have the bean with the @Async method declared/component-scanned in both contexts, the version from the child context (DispatcherServlet) will override the one in the parent context (ContextLoaderListener). I verified this by excluding that component from component scanning in the *-servlet.xml -- it now works as expected.
以上意思是注意component-scan里面扫包不要重复扫。
2、异步调用的方法不能是静态的
测试代码:
@RequestMapping(value = "/weixin/gett", method = RequestMethod.GET)
public void get(HttpServletResponse response) {
System.out.println("start............");
userAdviseService.testAsyncMethod();
System.out.println("end............");
responseResult("....", response);
}
@Async
public void testAsyncMethod() {
try {
// 让程序暂停5秒,相当于执行一个很耗时的任务
Thread.sleep(5000);
System.out.println("UserAdviseService.111111111111111111");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
执行结果:
start............
end............
UserAdviseService.111111111111111111
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<!-- 使用spring注解 -->
<context:annotation-config />
<context:component-scan base-package="com.sf.sfbuy.web" />
<context:component-scan base-package="com.sf.sfbuy.context" />
<task:annotation-driven />