我需要在弹簧项目中获得以下行为来解析属性文件(例如abc.properties):
1.尝试找到我的jar文件旁边的abc.properties
2.如果在jar文件旁边找不到文件abc.properties,请在名为configs的文件夹中搜索它。
我们如何使用spring propertyplaceholderconfigurer
实现上述目标答案 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 {
...
}