为什么Spring Context被加载两次?

Bal*_*sky 6 java spring

我有Spring和Spring安全的Web项目.我的web.xml:

    <web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0" >
        <display-name>BillBoard
        </display-name>
        <session-config>
            <session-timeout>
                30
            </session-timeout>
        </session-config>
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <listener>
            <listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
        </listener>
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:security-config.xml classpath:billboard-servlet.xml</param-value>
        </context-param>
        <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>
        <servlet-mapping>
            <servlet-name>billboard</servlet-name>
            <url-pattern>*.html</url-pattern>
        </servlet-mapping>
        <filter>
            <filter-name>springSecurityFilterChain</filter-name>
            <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
        </filter>

        <filter-mapping>
            <filter-name>springSecurityFilterChain</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    </web-app>
Run Code Online (Sandbox Code Playgroud)

在服务器日志中,我看到Spring上下文被加载了两次(spring bean初始化,数据库创建......).DispatcherServlet首次执行此操作,并在secont时间执行ContextLoaderListener.我该如何解决?

教程中,我看到如果出现contextParam,则不需要servlet init-params.但是,如果我删除init params,我有错误:"org.apache.catalina.LifecycleException:org.apache.catalina.LifecycleException:java.io.FileNotFoundException:无法打开ServletContext资源[/WEB-INF/billboard-servlet.xml] ".Dispather servlet在默认位置查找上下文配置.

sou*_*eck 6

您仍然需要servlet的上下文:

在初始化DispatcherServlet时,Spring MVC在Web应用程序的WEB-INF目录中查找名为[servlet-name] -servlet.xml的文件,并创建在那里定义的bean,覆盖使用相同名称定义的任何bean的定义在全球范围内.

你不需要像context-param在那里那样加载它ContextLoaderListener.

刚刚离开security-config.xmlcontext-param(它有去那里,因为安全是每个应用程序的全球性),并billboard-servlet.xmlcontextConfigLocation你的servlet的,它应该工作.


Mar*_*nik 2

这是做同一件事的两种独立方法。ContextLoaderListener例如,删除。