Spring 引用外部属性文件

1. property-placeholder加载外部文件的几种方式

1
2
3
4
5
6
7
8
<!-- 从classpath加载 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 从本地加载 -->
<context:property-placeholder location="file:///c:/file3.properties" />
<!-- 相对路径加载(相对于当前Bean配置文件的路径) -->
<context:property-placeholder location="config/file1.properties" />
<!-- 加载多个文件,路径之间用逗号分隔 -->
<context:property-placeholder location="classpath:file1.properties,config/file2.properties,file:///c:/file3.properties" />

2. property-placeholder属性

location:表示属性文件位置,多个之间通过如(逗号/分号)等分隔;

file-encoding:文件编码;

ignore-resource-not-found:如果属性文件找不到,是否忽略,默认false,即不忽略,找不到将抛出异常

ignore-unresolvable:是否忽略解析不到的属性,如果不忽略,找不到将抛出异常

properties-ref:本地java.util.Properties配置

local-override:是否本地覆盖模式,即如果true,那么properties-ref的属性将覆盖location加载的属性

system-properties-mode:系统属性模式,ENVIRONMENT(默认),NEVER,OVERRIDE

3. property-placeholder读取中文

3.1. 方式1:值以Unicode编码表示

properties文件

1
2
# 值以Unicode编码表示
name=\u5F20\u4E09

Bean配置

1
2
<!-- 直接加载文件即可 -->
<context:property-placeholder location="classpath:file1.properties"/>

3.2. 方式2:加载UTF-8

properties文件,编码UTF-8

1
name=张三

Bean配置

1
2
<!-- 指定file-encoding -->
<context:property-placeholder location="classpath:file1.properties" file-encoding="UTF-8" />

4. property-placeholder只有首个配置有效

Spring容器是采用反射扫描的发现机制,通过标签的命名空间实例化实例,当Spring探测到容器中有一个org.springframework.beans.factory.config.PropertyPlaceholderCVonfigurer的Bean就会停止对剩余PropertyPlaceholderConfigurer的扫描,即只能存在一个实例

1
2
3
4
5
6
<!-- 有效 -->
<context:property-placeholder location="classpath:file1.properties"/>
<!-- 无效 -->
<context:property-placeholder location="classpath:file2.properties"/>
<!-- 无效 -->
<context:property-placeholder location="classpath:file3.properties"/>

5. 注意空白字符

有时在设置value时,一不小心前后可能多打了几个空白字符,这会导致出错。因为Spring不会把这些空白字符给去掉

1
2
<!-- ERROR -->
<property name="username" value=" ${jdbc.username} "/>

panchaoxin wechat
关注我的公众号
支持一下