Spring FrameworkServlet在Tomcat启动期间不会加载Properties

时间:2017-04-14 12:32:12

标签: java spring spring-mvc tomcat8

Spring PropertyPlaceholderConfigurer

我遇到了一个奇怪的问题

所有JUnit测试都通过了,但是当我启动Tomcat时,我遇到了一个属性初始化问题:

// First root initialization, the properties are fine
[...]
INFO: Initializing Spring root WebApplicationContext
14:21:13.195 INFO  [QuartzProperties] - QuartzProperties: false 0 0/30 * * * ? true 18:00 1

// Second 'servlet' initialization, the properties are empty
[...]
INFO: Initializing Spring FrameworkServlet 'global'
14:21:16.133 INFO  [QuartzProperties] - QuartzProperties: false  false ${quartz.triggertime} 0

servlet上下文初始化不使用属性,并触发Quartz库崩溃(无效值)。

我认为配置没有任何问题,并且真的不明白发生了什么:

web.xlm

[...]
<servlet>
    <servlet-name>global</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
    <servlet-name>global</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<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>

的applicationContext.xml

<bean id="allProperties" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
    <property name="ignoreResourceNotFound" value="false" />
    <property name="locations">
        <list>
            <value>file:///${WEBSITE_HOME}/conf/jdbc.properties</value>
            <value>file:///${WEBSITE_HOME}/conf/hibernate.properties</value>
            <value>file:///${WEBSITE_HOME}/conf/quartz.properties</value>
        </list>
    </property>
</bean>

WEBSITE_HOME值来自操作系统环境。

有没有人知道全局servlet init中属性为空的原因?

1 个答案:

答案 0 :(得分:2)

您还需要在servlet定义中包含init参数。

<init-param>
     <param-name>contextConfigLocation</param-name>
     <param-value>classpath:/applicationContext.xml</param-value>
</init-param>
[...]
<servlet>
    <servlet-name>global</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>
<servlet-mapping>
    <servlet-name>global</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

<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>