第五章第九节-property-placeholder加载外部属性文件

        本节也以一个小项目来做介绍,还是和HelloWorld的项目一样,不过多加了c3p0-0.9.1.2.jar和mysql-connector-java-5.1.34.jar的包。项目是以配置数据库的连接作为演示。项目中TestMain.java是测试类;db.properties是外部的属性文件(和spring配置文件一样放在src下);spring.xml是IOC容器配置文件。

       详细的代码见下方不再做详细讨论,直接看外部文件和配置文件的关联。关键代码如下。

这里引入context命名空间,然后使用property-placeholder标签,location是外部属性文件的路径。这样设置完之后在dataSource的value中使用${ }将外部属性文件的key(key就是=左边的值)值填入其中即可完成外部属性文件的引入。

 

user=root
password=gzq123
drivenClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/test

 

	<context:property-placeholder location="classpath:db.properties"/>

	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="user" value="${user}"></property>
		<property name="password" value="${password}"></property>
		<property name="driverClass" value="${drivenClass}"></property>
		<property name="jdbcUrl" value="${jdbcUrl}"></property>
	</bean>

 

 

-------------------------------------------完整代码---------------------------------------------------------------------------------------------------------------------
TestMain.java

 

public class TestMain {

	public static void main(String[] args) throws SQLException {
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");

		DataSource ds = (DataSource) ctx.getBean("dataSource");
		
		System.out.println(ds.getConnection());
		
	}

}

db.properties

 

 

user=root
password=gzq123
drivenClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/test

spring.xml

<?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"
	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-4.1.xsd">

	<!-- 
		一、加载外部的属性文件
	 -->
	<context:property-placeholder location="classpath:db.properties"/>

	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="user" value="${user}"></property>
		<property name="password" value="${password}"></property>
		<property name="driverClass" value="${drivenClass}"></property>
		<property name="jdbcUrl" value="${jdbcUrl}"></property>
	</bean>

</beans>

 

 

 

 

 

 

 

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值