我们知道springmvc项目进项包扫描的时候要避免Controller和Service被重复扫描导致创建两个实例。办法就是在applicationContext.xml中配置
<context:component-scan base-package="com.pinguoba.pinguo"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"/> <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"/> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
在springmvc的配置文件例如springmvc-default.xml中配置
<context:component-scan base-package="com.pinguoba.pinguo" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Service"/> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Repository"/> </context:component-scan>
但我们这次说的定时任务重复执行两次的问题,和上面的配置没有关系。最初发现定时任务重复执行是在linux系统的项目日志中,于是我又在本地(Windowsxito系统)跑了一下项目,发现定时任务并没有重复执行。太奇怪了!那么问题很可能就不在程序的配置上面,而是在外在环境上面。最后在网上看到有人给出了原因,因为tomcat的server.xml里面配置不当导致tomcat加载了两次项目。比如我的server.xml配置如下:
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
<Context docBase="/home/apache-tomcat-7.0.84/webapps/jinggai" path="/" privileged="true" reloadable="true"/>
</Host>
tomcat首先扫描到appBase属性,于是加载了webapps下的目录(包含jinggai目录)。tomcat又扫描到docBase,于是又加载了/home/apache-tomcat-7.0.84/webapps/jinggai目录。
这就导致我的jinggai项目被chog重复加载了。
解决办法就是只让tomcat加载一次。所以把appBase的值去掉就可以了。配置改成如下:
<Host name="localhost" appBase=""
unpackWARs="true" autoDeploy="true">
<Context docBase="/home/apache-tomcat-7.0.84/webapps/jinggai" path="/" privileged="true" reloadable="true"/>
</Host>