spring:如何定义属性文件位置优先级?

时间:2016-05-15 17:46:22

标签: java spring spring-mvc

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

我们如何使用spring propertyplaceholderconfigurer

实现上述目标

2 个答案:

答案 0 :(得分:1)

  

对于基于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

答案 1 :(得分:1)

关键是将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 {
    ...
}