【问题标题】:Spring resolved property file location needs to resolve those propertiesSpring解析的属性文件位置需要解析那些属性
【发布时间】:2026-01-31 21:40:01
【问题描述】:

我正在使用 Spring 版本 4.0.6.RELEASE 并尝试从属性文件中读取 spring 并使用已解析的属性之一为另一个属性文件提供位置。我的 spring.xml 文件有以下内容:

    <bean id="applicationProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
    <property name="locations">
        <list>
            <value>classpath:application.properties</value>
            <value>classpath:version.properties</value>
            <!- The below file contains the another file location -->
            <value>file:${catalina.base}/conf/instance.properties</value>
            <value>${another.file.location}</value>

        </list>
    </property>
    <property name="ignoreResourceNotFound" value="true"/>
</bean>

instance.properties 包含:

account.id=BlahBlahBlah
another.file.location=file:/Users/beardman/.myapp/local.properties

和 /Users/beardman/.myapp/local.properties 包含:

magic.number=3
database.endpoint=blah

我不断收到以下警告:

WARN  [main] o.s.b.f.c.PropertyPlaceholderConfigurer Could not load properties from ServletContext resource [/${another.file.location}]: Could not open ServletContext resource [/${another.file.location}]

在调试我的代码时,我可以看到 account.id 被正确注入,但我永远无法让 magic.number 或 database.endpoint 显示出来。如何让 spring 使用 instance.properties 文件中的已解析属性作为 another.file.location 的值?

编辑:添加属性文件内容

【问题讨论】:

  • 看起来您的路径值设置不正确或不存在
  • 这是一个很好的观点@CodeFox,但我已经验证了这些文件确实存在于它们的正确位置,并且我实际上从 instance.properties 文件中获取了属性,而我的 local.properties 文件中没有任何内容。跨度>

标签: java spring properties configuration config


【解决方案1】:

默认情况下,Spring 将属性占位符替换为系统属性。由于您还想使用在外部文件中定义的属性,因此您需要创建一个PropertyPlaceholderConfigurer
此标记是简写,但如果您需要更多控制,可以将 PropertyPlaceholderConfigurer 定义为 bean。在你的 applicationProperties bean 之前添加它

<context:property-placeholder location="file:${catalina.base}/conf/instance.properties"/>

请注意,文件中的属性将覆盖默认模式下的系统属性。您可以通过将属性systemPropertiesMode="override" 添加到property-placeholder 元素来指定首先检查系统属性

【讨论】:

  • instance.properties 文件中的属性被正确读取,但我无法让 spring 翻译在 instance.properties 中定义的 another.file.location 属性并实际读取 another.file 中的属性。位置。
  • 感谢您的回复。我在多种不同的配置中尝试了 context:property-placeholder 并且 another.file.location 从未得到解决。
  • @beardman PropertyPlaceholderConfigurer 的警告不是针对您发布的配置部分,而是针对另一个尝试加载 ${another.file.location} 作为属性占位符的 bean。在您可以在任何地方使用 ${another.file.location} 之前,您需要使用 PropertyPlaceholderConfigurer 加载 instance.properties。如果您还尝试从 ${another.file.location} 加载属性以用作占位符,则需要将其放在第二个 PropertyPlaceholderConfigurer 中,位于 instance.properties 之后的某个位置。