为什么Spring Context被加载两次?

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

 BillBoard    30    org.springframework.web.context.ContextLoaderListener   org.springframework.security.web.session.HttpSessionEventPublisher   contextConfigLocation classpath:security-config.xml classpath:billboard-servlet.xml   billboard org.springframework.web.servlet.DispatcherServlet  contextConfigLocation classpath:security-config.xml classpath:billboard-servlet.xml  1   billboard *.html   springSecurityFilterChain org.springframework.web.filter.DelegatingFilterProxy   springSecurityFilterChain /*   

在服务器日志中,我看到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在默认位置查找上下文配置。

您仍然需要servlet的上下文:

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

您不需要在ContextLoaderListener中将其作为context-param加载。

只需将security-config.xml保留为context-param (它必须转到那里,因为安全性是每个应用程序的全局),而billboard-servlet.xml作为servlet的contextConfigLocation ,它应该可以工作。

我有同样的问题,原因是:

1

这是两个独立的方法来做同样的事情。 例如,删除ContextLoaderListener

由于你有spring delegatingFilterProxy ,如果删除contextLoaderLister你将得到以下exception。

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

因此,通过dispatcher servlet通过contextLoaderLister和billboard-servlet.xml加载security-config.xml。