天天看點

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了.本文到此結束

繼續閱讀