关于 PropertyPlaceholderConfigurer

本文介绍如何在Spring中使用PropertyPlaceholderConfigurer来加载多个外部属性文件,并展示了如何在XML配置文件中引用这些属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Spring中,使用PropertyPlaceholderConfigurer可以在XML配置文件中加入外部属性文件,例如:



<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="classpath:config/jdoserver.properties"/>
</bean>



但是好像在属性文件定义中却不支持多个属性文件的定义,比如不能这样用config/*.properties。

经过查看源码,发现可以使用locations属性定义多个配置文件:

<property name="locations">
<list>
<value>classpath:config/maxid.properties</value>
<value>classpath:config/jdoserver.properties</value>
</list>
</property>


使用外部属性后如下:

<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.agent.driver}"/>
<property name="url" value="${jdbc.agent.main.url}"/>
</bean>



例子:
Spring的框架中为提供了一个BeanFactoryPostProcessor的实体类别: org.springframework.beans.factory.config.PropertyPlaceholderConfigurer
可以将一些动态参数,移出至.properties中,如此的安排可以让XML定义系统相关设定(不常变动),而.properties可以作为客户根据实际自定义一些相关参数。(如不同人数据库的不同密码)
applicationConfig.xml


<beans>
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.<SPAN class=hilite1>PropertyPlaceholderConfigurer</SPAN>">
<property name="location">
<value>/WEB-INF/db.properties</value>
</property>
</bean>

<bean id="dataSource"
class="org.logicalcobwebs.proxool.ProxoolDataSource">
<property name="driver">
<value>${driver}</value>
</property>
<property name="driverUrl">
<value>${driverUrl}</value>
</property>
<property name="user">
<value>${user}</value>
</property>
<property name="password">
<value>${password}</value>
</property>
<property name="alias">
<value>spring</value>
</property>
<property name="houseKeepingSleepTime">
<value>90000</value>
</property>
<property name="prototypeCount">
<value>5</value>
</property>
<property name="maximumConnectionCount">
<value>100</value>
</property>
<property name="minimumConnectionCount">
<value>10</value>
</property>
<property name="trace">
<value>true</value>
</property>
<property name="verbose">
<value>true</value>
</property>
</bean>
</beans>



db.properties

driver=com.mysql.jdbc.Driver
driverUrl=jdbc:mysql://localhost/securedoc?user=root&password=sqladmin&useUnicode=true&characterEncoding=GBK
user=root
password=sqladmin

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值