Spring MVC web app: application context starts twice

后端 未结 1 1018
悲哀的现实
悲哀的现实 2020-12-13 19:43

I\'m working on a Spring MVC REST API. Everything works fine, which is great, but I noticed from the logs that every time I restart my app the applicationContext loads twice

相关标签:
1条回答
  • 2020-12-13 20:02

    mvc-dispatcher is loading 2x because that is how you've defined it

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

    and at

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    

    the first approach is usually for loading something like a "global" or "root" context, where you might put all the bean/resources shared by multiple servlet contexts.

    The second approach is usually for loading a specific servlet context. As the first answer in this post points out, it uses naming convention to find the mvc-dispatcher config file, so you don't need to explicitly define it.

    Do you have everything defined in mvc-dispatcher-servlet.xml? If so you can remove the

    <context-param>
      ..
    </context-param>
    

    definition, otherwise you can (which I recommend for future maintainability) separate your configuration into multiple files. Then load shared beans/resource in something like a root-context.xml (via the first method), and each servlet specific config under servletname-servlet.xml for each servlet context.

    0 讨论(0)
提交回复
热议问题