Why Spring Context is loaded twice?

后端 未结 5 1119
终归单人心
终归单人心 2021-01-05 12:20

I have web project with Spring and Spring security. My web.xml:

    

        
相关标签:
5条回答
  • 2021-01-05 12:28

    When you configure the spring MVC framework configuration in the XML, you may configure it as bellow:

    <!-- for Spring context loader -->
    <servlet>
        <servlet-name>billboard</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:security-config.xml classpath:billboard-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    
    </servlet>
    

    this configuration will cause the IoC container initialize twice.

    You should change the default servlet name[billboard] to others to solve this problem.

    Because your dispatcher servlet is using the default context namespace [name of servlet]-servlet.xml (in the case billboard-servlet.xml) then Spring MVC will automatically load it.

    For more details see: https://www.conqtech.com/blog/?p=85

    0 讨论(0)
  • 2021-01-05 12:33

    You still need a context for your servlet:

    Upon initialization of a DispatcherServlet, Spring MVC looks for a file named [servlet-name]-servlet.xml in the WEB-INF directory of your web application and creates the beans defined there, overriding the definitions of any beans defined with the same name in the global scope.

    You don't need to load it as context-param in the ContextLoaderListener though.

    Just leave the security-config.xml as context-param (it has to go there, as security is global per application), and billboard-servlet.xml as contextConfigLocation of your servlet and it should work.

    0 讨论(0)
  • 2021-01-05 12:44

    Since you have spring delegatingFilterProxy, if you drop contextLoaderLister you will get the below exception.

    java.lang.IllegalStateException: No WebApplicationContext found: 
    no   ContextLoaderListener registered?
    

    So load security-config.xml via contextLoaderLister and billboard-servlet.xml via dispatcher servlet.

    0 讨论(0)
  • 2021-01-05 12:45

    I had the same issue and the reason was:

    <load-on-startup>1</load-on-startup

    0 讨论(0)
  • 2021-01-05 12:51

    These are two independent methods to do the same thing. Drop the ContextLoaderListener, for example.

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