目录
  • spring @async无法实现异步
  • @async不起作用
    • 4.在你需要异步调用的方法上使用@async注解
    • 5.但是你可能遇到@async不起作用的时候

spring @async无法实现异步

问题原因

项目中存在2个配置文件:springmvc.xml和beandefines.xml,它们都配置了<context:component-scan base-package=”com” />。

在beandefines.xml还配置了<task:annotation-driven/>。

从启动日志中发现,spring先加载的是beandefines.xml,后加载的是springmvc.xml。

由于springmvc.xml的context:component-scan覆盖了beandefines.xml的配置,而<task:annotation-driven/>是否有效是依赖于context:component-scan的配置的。

导致beandefines.xml配置的<task:annotation-driven/>不起作用了。

解决办法

1、删除beandefines.xml的<context:component-scan base-package=”com” />和<task:annotation-driven/>;

2、springmvc.xml添加配置<task:annotation-driven/>。

@async不起作用

首先介绍一下如何@async注解,

1.xml头文件必须配置标记红色部分

2.配置任务和线程池

<!-- 任务及线程池 -->
<task:annotation-driven executor="asyncexecutor" />
 <task:executor id="asyncexecutor" pool-size="100-10000" queue-capacity="10"/>
 <!-- 注解扫描 -->
<context:component-scan base-package="com.baisq">
 <context:include-filter type="annotation"
	expression="org.springframework.stereotype.controller" />
</context:component-scan>

3.配置spring依赖的jar(不介绍这个了)

4.在你需要异步调用的方法上使用@async注解

5.但是你可能遇到@async不起作用的时候

我就遇到了,我的问题是容器启动加载了如下两个xml文件

springmvc.xml文件仅仅配置扫描注解,applicationcontext.xml配置了任务和线程池和扫描注解,先加载了applicationcontext.xml,后加载了springmvc.xml。

applicationcontext.xml为扫描到的类加上@async的作用(任务和线程池的配置依赖于扫描到的类),然后springmvc加载后的bean覆盖了applicationcontext的bean,覆盖掉了@async的作用,因为springmvc没有配置任务和线程池,

导致@async没有起到作用。

6.如果你遇到上述问题

检查一下加载的xml文件是否存在覆盖的问题。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持www.887551.com。