Spring 4运行调度任务两次,没有applicationContext.xml

时间:2014-11-06 12:30:50

标签: java spring spring-mvc scheduled-tasks

我读了这两个,但它们似乎无法正常工作

Java Spring @Scheduled tasks executing twice

Spring @Scheduled is executing task twice when using annotations

我没有@Configurable类,我没有使用applicationConetxt.xml

我的ScheduleTasks

@EnableScheduling
@Component
public class ScheduledTasks {
    @Autowired
    private ApplicationContext ctx;

    @Scheduled(fixedRate=5000)
    public void monitorRoom(){
        System.out.println("--------------------");
    }
}

我可以看到,当我在tomcat中运行应用程序时,任务打印两次evrey 5秒。

有人说要删除

<listener>
    <listener-class>
        org.springframework.web.context.ContextLoaderListener
    </listener-class>
</listener> 

它有效,但我觉得这不是解决方案。因为这应该是必需的。(至少来自谷歌的例子)

这是我的web.xml

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>wodinow</display-name>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/dispatcher-servlet.xml</param-value>
    </context-param>

    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener> 

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

</web-app>

调度-servlet.xml中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="wodinow.weixin.jaskey" />

    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/jsp/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

    <mvc:resources mapping="/pages/**" location="/resources/pages/" />
    <mvc:resources mapping="/images/**" location="/resources/images/" />

    <mvc:annotation-driven/>

</beans>

1 个答案:

答案 0 :(得分:1)

删除上下文加载程序侦听器。如果必须初始化父上下文,则只需要它。调度程序servlet的上下文是独立的,但如果需要可以访问这样的父上下文,即检索服务或dao。