文章目录
PropertyPlaceholderConfigurer作用
在Spring中,使用PropertyPlaceholderConfigurer可以在XML配置文件中加入外部属性文件,当然也可以指定外部文件的编码。PropertyPlaceholderConfigurer可以将上下文(配置文件)中的属性值放在另一个单独的标准java Properties文件中去。在XML文件中用${key}替换指定的properties文件中的值。这样的话,只需要对properties文件进 行修改,而不用对xml配置文件进行修改。
在.xml中引入外部文件,即.properties文件
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="ignoreUnresolvablePlaceholders" value="true" />
<property name="fileEncoding" value="utf-8" />
<property name="locations">
<list>
<value>classpath:jdbc.properties</value>
<value>classpath:email.properties</value>
</list>
</property>
</bean>
编写.properties文件
# jdbc.properties 文件
jdbc.url=jdbc:mysql://66.59.208.106:3306/ds?useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true
jdbc.username=root
jdbc.password=root
引入外部文件后,就可以在Java和xml中用${key}替换指定的properties文件中的值
<bean id="dataSourceDefault" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
@Value("${jdbc.url}")
private String url;
在启动容器时,初始化bean时,${key}就会替换成properties文件中的值。
简化PropertyPlaceholderConfigurer的使用
Spring提供了<context:property-placeholder/>
元素,启用它后,开发者便不用配置PropertyPlaceholderConfigurer对象了。
<!-- 数据库配置文件位置 -->
<context:property-placeholder location="classpath:jdbc.properties" />
注:spring容器中最多只能定义一个context:property-placeholder,否则会报错:Could not resolve placeholder XXX,但如果想引入多个属性文件怎么办那,可以使用通配符:<context:property-placeholder location="classpath*:conf*.properties"/>
自定义 PropertyPlaceholderConfigurer
参考:
自用读取配置文件工具类ReadConfig
PropertyPlaceholderConfigurer读取属性文件使用详解