spring:如何定义特性文件的位置优先级



我们需要获得以下行为来解析我的spring项目中的属性文件(比如abc.properties):
1.尝试在我的jar文件附近查找abc.properties
2.如果在jar文件旁边找不到文件abc.properties,请在名为configs的文件夹中搜索它。

我们如何使用spring属性占位符配置器

实现上述功能

对于基于XML的配置

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="locations">
        <list>
            <value>classpath:abc.properties</value>
            <value>file:/some/folder/path/override.properites</value>
        </list>
    </property>
</bean>

您也可以使用context名称空间:

<context:property-placeholder locations="classpath:abc.properties,file:/some/folder/path/override.properites"/> 

对于基于注释的配置,您可以将以下注释添加到任何@Configuration文件

@PropertySource({
    "classpath:abc.properties",
    "file:/some/folder/path/override.properites" //This will override values with same keys as in abc.properties
})

有关更多详细信息:http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

关键是将ignoreResourceNotFound属性设置为true

使用PropertyPlaceholderConfigurer:的示例

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <property name="ignoreResourceNotFound" value="true" />
    <property name="locations">
        <list>
            <value>classpath:abc.properties</value>
            <value>file:/path-to-file/abc.properites</value>
        </list>
    </property>
</bean>

使用@PropertySource:的示例

@Configuration
@PropertySource(value = { "classpath:abc.properties", "file:/path-to-file/abc.properties" }, ignoreResourceNotFound = true)
class MyConfig {
    ...
}

最新更新