Spring 使用外部属性文件
--在配置文件中配置Bean时,有时需要在Bean的配置里混入系统部署的细节信息(例如:文件路径,数据源配置信息等),而这些部署细节实际上需要和Bean配置 相分离。
--Spring提供了PropertyPlaceholderConfiguer的BeanFactory后置处理器,这个处理器允许用户将bean配置的部分内容外移到属性文件中,可以在bean配置文件里使用形式为 ${var}的变量,PropertyPlaceholderConfiguer从属性文件中加载属性,并使用这些属性来替换变量。
--Spring还允许在属性文件中使用${propName},以实现属性之间的相互引用。
--可以通过修改外部文件,从而修改引入数据,可以更直观。
要加载外部文件中的数据,需要注册PropertyPlaceholderConfiguer:
--<bean>中添加contetxtSchema定义
--在配置文件中加入如下配置:
从类路径下加载文件(db.properties)
<context:property-placeholder location="classpath:db.properties" />
从外部文件中加载数据源:
db.properties:
user=root driverclass=com.mysql.jdbc.Driver jdbcurl=jdbc:mysql///test
配置文件:
<?xml version="1.0" encoding="UTF-8" ?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <context:component-scan base-package="com.eduask.jxb"/> <!-- 将jdbc.properties 读取到xml --> <context:property-placeholder location="classpath:db.properties" /> <!-- 使用外部化属性文件的属性 --> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="user" value="${user}"></property> <property name="driverClass" value="${driverclass}"></property> <property name="jdbcUrl" value="${jdbcurl}"></property> </bean> </beans>

浙公网安备 33010602011771号