一、通过标签<context:property-placeholder >
<context:property-placeholder location="classpath:redis-key.properties"/>
2. 用法
(1)在xml文件中使用
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
(2)在java文件中使用
@Value("${jdbc_url}") private String jdbcUrl;
3. 注意
(1)属性说明
location:表示属性文件位置,多个之间通过如逗号/分号等分隔;
ignore-unresolvable:(多文件时使用)是否忽略解析不到的属性,如果不忽略,找不到将抛出异常 ,默认false
(2)引入多个properties文件问题
会遇到如下错误:
nested exception is java.lang.IllegalArgumentException:
Could not resolve placeholder 'key' in string value${key1}
原因:
在加载第一个context:property-placeholder时会扫描所有的bean,而有的bean里面出现第二个
context:property-placeholder引入的properties的占位符${key2},但此时还没有加载第二个property-placeholder,
所以解析不了${key2}。
解决:
方法一,可以将通过模块的多个property-placeholder合并为一个,将初始化放在一起。
<context:property-placeholder location="classpath:config.properties,classpath:jdbc.properties">
</context:property-placeholder>
方法二,添加ignore-unresolvable="true",这样在加载第一个property-placeholder时出现解析不了的占位符进行忽略掉。
二、通过标签<bean class="org.springframework.beans.factory.config.
PropertyPlaceholderConfigurer" >
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config.properties</value>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
2. 用法
等价于 方式一,用法参考方式一。
三、通过标签< util:properties>
<util:properties id="propertyConfigurer" local-override="true" location="classpath:jdbc.properties"/>
2. 用法
(1)在xml文件中使用
<property name="url" value="${jdbc.url}" />
<property name="username" value="#{propertyConfigurer['jdbc.username']}" />
<property name="password" value="#{propertyConfigurer['jdbc.password']}" />
(2)在java文件中使用
@Value(value="#{propertyConfigurer['jdbc.url']}") private String jdbcUrl;
四、通过标签<bean class="org.springframework.beans.factory.config.
PropertiesFactoryBean" >
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="locations">
<list>
<value>classpath:config.properties</value>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
2. 用法
在java文件中使用
@Value(value="#{propertyConfigurer['jdbc.url']}") private String jdbcUrl;