Java Spring @Scheduled tasks executing twice

During the servlet container lifecycle, the container first initializes the ServletContextListener, then the Filter and Servlet instances.

A Spring Web application typically loads two contexts: the root context and the dispatcher servlet context. The ContextLoaderListener class is a ServletContextListener which loads the application (or root) context. It identifies the file to load either through the context-param with the name contextConfigLocation as given in the web.xml like below

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

or, by default, by looking for a file at /WEB-INF/applicationContext.xml. Since you've specified /WEB-INF/mvc-dispatcher-servlet.xml as the contextConfigLocation, that context will be loaded.

Once this is done, the container initializes the DispatcherServlet, which also loads a context. It identifies the file load either through an init-param element with the name contextConfigLocation as given in the web.xml below

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appServlet/some-random-location.xml</param-value>
    </init-param>
</servlet>

or, by default, by looking for a file at /WEB-INF/name-of-your-servlet-servlet.xml. In other words, it takes the value of the <servlet-name> element and appends -servlet.xml to it and looks for it in WEB-INF.

Since you haven't specified an init-param with name contextConfigLocation, the DispatcherServlet loads the context file at /WEB-INF/mvc-dispatcher-servlet.xml, since its name is mvc-dispatcher. The context loaded by the DispatcherServlet has access to the beans loaded by the ContextLoaderListener, that's why we call that the root context (and the others children).

All this to say that both your ContextLoaderListener and your DispatcherServlet are creating their own copy of an ApplicationContext by each loading a XmlWebApplicationContext from the same file at /WEB-INF/mvc-dispatcher-servlet.xml.

Identify what beans or configuration you think should be available to the whole application and put them in the file that will be loaded by the ContextLoaderListener. Identify the beans or configuration you think should be available to the DispatcherServlet and put them in its context file.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值