Spring中@Async 异步不执行问题

【问题中的配置】

  

  spring相关配置文件root-context.xml mvc-context.xml其中mvc-context.xml被包含于root-context.xml 

  web.xml的配置为

  <context-param>

    <param-name>contextConfigLocation</param-name>

    <param-value>

  WEB-INF/spring/root-context.xml

</param-value>

  </context-param>

  

  <servlet>

    <servlet-name>haha</servlet-name>

    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

    <init-param>

      <param-name>contextConfigLocation</param-name>

      <param-value>/WEB-INF/spring/mvc-context.xml</param-value>

    </init-param>

    <load-on-startup>1</load-on-startup>

  </servlet>

  <servlet-mapping>

    <servlet-name>haha</servlet-name>

    <url-pattern>/</url-pattern>

  </servlet-mapping>

  

  添加@Async的类被 <context:component-scan base-package="com.haha.service.impl"></context:component-scan>和

  <context:component-scan base-package="com.haha.controller"></context:component-scan>放于mvc-context.xml

  

【修改后Ok的配置】

 将 <context:component-scan base-package="com.haha.service.impl"></context:component-scan>放于root-context.xml

  注意不能将controller的也迁移到root-context.xml,否则controller的Bean无法实例化

原因:详见解决要点

===========================================

解决要点:

一、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里面扫包不要重复扫。

===========================================

解决问题参考文献:

http://blog.csdn.net/haiyangzhishen/article/details/46930677

今天用了一下spring的@Async功能,遇到了一些问题。大家用的时候一定要注意:

1、异步方法和调用类不要在同一个类中

2、注解扫描时,要注意过滤,避免重复实例化,因为存在覆盖问题,@Async就失效了

 

非常感谢下面三篇文章的作者:

http://www.kaifajie.cn/XiangMuKuangJia/s13035.html

http://www.cnblogs.com/youngjoy/p/3817471.html

http://blog.csdn.net/jokes000/article/details/24649173

猜你喜欢

转载自aoyouzi.iteye.com/blog/2302701