Spring定时任务执行2次问题解决

在开发定时任务时,发现定时任务每次都会执行2次.后来上网找原因知道是因为bean的重复扫描被创建了2个实例.

application.xml主配置文件中如下扫描bean

<context:component-scan base-package="com.wing" /> //扫描了所有的类

spring-mvc.xml的扫描bean配置如下

<context:component-scan base-package="com.wing" /> //这里也扫描了所有类.但理论上来说应该只扫描Controller.这就导致了bean被创建了2个实例

所以.解决方法: application.xml的bean扫描改成只扫描 Controller以外的bean.mvc.xml只扫描Controller的bean.如下

<context:component-scan base-package="com.wing" >
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
//exclude-filter.根据@Controller注解排除扫描Controller
<context:component-scan base-package="com.wing" use-default-filters="false" >
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>  
//use-default-filters="false":不实用默认的扫描filter.根据@Controller进行扫描所有Controller

这样配置就ok了.本文到此结束

发布了53 篇原创文章 · 获赞 5 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_40085888/article/details/102561795