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

Spring FrameworkServlet won't load Properties during Tomcat startup

我在使用 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 值来自 OS 环境。

有人知道为什么全局 servlet init 中的属性为空吗?

您还需要在 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>