4

我有一个在 tomcat 容器中运行的基于 Spring 的 Web 应用程序,我想维护两个不同的配置文件:

  • src/main/resources/default.properties:包含开发、集成测试和未设置其他属性时的默认值
  • .../tomcat/conf/app.properties:在不同的环境中有不同的内容,应该覆盖default.properties

当应用程序在 tomcat 中运行时,我有一个运行良好的 spring 配置

应用程序上下文.xml

<context:property-placeholder
    ignore-resource-not-found="true"
    ignore-unresolvable="true"
    system-properties-mode="OVERRIDE"
    location="classpath:default.properties,
              file:${catalina.home}/conf/app.properties"/>

但是,当我尝试在 tomcat 容器之外的集成测试中使用此配置时,加载 applicationContext 失败:

java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:308)
    ...
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: Invalid bean definition with name 'org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0' defined in null: Could not resolve placeholder 'catalina.home'
    at org.springframework.beans.factory.config.PropertyPlaceholderConfigurer.processProperties(PropertyPlaceholderConfigurer.java:287)

当当前上下文中未设置属性 catalina.home 时,有什么方法可以告诉 Spring 忽略位置文件:${catalina.home}/conf/app.properties?

4

3 回答 3

0

你可以设置ignore-resource-not-found来解决这个问题。

试试这个:

<context:property-placeholder
    ignore-resource-not-found="true"
    ignore-unresolvable="true"
    system-properties-mode="OVERRIDE"
    location="classpath:default.properties,
              file:${catalina.home}/conf/app.properties"/>

spring-context.xsd 中的代码片段:

<xsd:attribute name="ignore-resource-not-found" type="xsd:boolean" default="false">
            <xsd:annotation>
                <xsd:documentation><![CDATA[
    Specifies if failure to find the property resource location should be ignored.
    Default is "false", meaning that if there is no file in the location specified
    an exception will be raised at runtime.
                ]]></xsd:documentation>
            </xsd:annotation>
        </xsd:attribute>
于 2015-01-09T13:32:46.557 回答
0

由于您有一个上下文,其中一些 PP 值可能无法解析,您可以尝试使用 adefault variant作为属性:

file:${catalina.home:}/conf/app.properties

在这种情况下,如果没有catalina.home属性,则路径前缀将解析为空字符串,例如在 中System.getProperties(),我猜是 Tomcat 的情况。

之后,ignore-resource-not-found="true"做的东西。

于 2015-01-09T13:54:48.157 回答
0

我建议使用弹簧配置文件来启用/禁用属性文件。

当在“tomcat”或“web”配置文件上运行 tomcat 时,将 app.properties 的加载放入该配置文件中。

于 2015-04-30T11:27:16.863 回答