您可以使用类路径文件使用<init-param>配置DispatcherServlet吗?

时间:2017-08-22 11:11:50

标签: java spring spring-mvc

我正在浏览我正在处理的Web应用程序中的Spring配置文件,我们在web.xml中有这个:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
</context-param>

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

从类路径而不是更常见的applicationContext.xml加载/WEB-INF/applicationContext.xml的原因是因为某些属性(如JDBC连接详细信息)由Maven根据用于的配置文件进行过滤构建/运行应用程序(集成测试,功能测试,生产......)。这一切都有效,但如果我将其更改为以下配置(删除<context-param><listener>条目):

<servlet>
    <servlet-name>dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

日志说应用程序正确启动,并且从XML文件加载Web应用程序上下文:

...
11:57:15.910 [RMI TCP Connection(2)-127.0.0.1] INFO  org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'dispatcher': initialization started
11:57:15.927 [RMI TCP Connection(2)-127.0.0.1] INFO  org.springframework.web.context.support.XmlWebApplicationContext - Refreshing WebApplicationContext for namespace 'dispatcher-servlet': startup date [Tue Aug 22 11:57:15 BST 2017]; root of context hierarchy
11:57:15.958 [RMI TCP Connection(2)-127.0.0.1] INFO  org.springframework.beans.factory.xml.XmlBeanDefinitionReader - Loading XML bean definitions from class path resource [applicationContext.xml]
...

但是当我尝试获取任何页面时,Tomcat会回复404错误并在日志中回复以下NPE(我们正在使用Tiles 3):

SEVERE: Servlet.service() for servlet jsp threw exception
java.lang.NullPointerException
    at org.apache.tiles.access.TilesAccess.getContainer(TilesAccess.java:124)
    at org.apache.tiles.access.TilesAccess.getContainer(TilesAccess.java:107)
    at org.apache.tiles.access.TilesAccess.getCurrentContainer(TilesAccess.java:174)
    at org.apache.tiles.template.InsertDefinitionModel.execute(InsertDefinitionModel.java:95)
    at org.apache.tiles.jsp.taglib.InsertDefinitionTag.doTag(InsertDefinitionTag.java:254)
    at ...

我已经在其他SO问题中看到,如果你不需要在servlet之间共享上下文,你可以使用<init-param>来配置你的servlet(通常如果你只运行一个);但是我看到的所有示例都使用绝对路径来指示applicationContext.xml的位置,所以我想知道可能根本不可能使用类路径加载WAC?你有没有成功地做过这样做,或者你知道为什么不能这样做吗?

0 个答案:

没有答案