使用外部属性文件(通常用来配置系统文件,比如数据源)

一:使用外部属性文件

1.在配置文件里配置Bean时,有时需要在Bean的配置里混入系统部署的细节信息(例如:文件路径,数据源,等其他配置信息)

而这些部署细节实际上需要和Bean配置相分离的

2.spring提供了一个PropertyplaceholderConfigures的BeanFactory后置处理器,这个处理器允许用户将Bean配置的部分内容外移到

属性文件中,可以在bean配置文件内使用形式为${var}的变量,PropertyplaceholderConfigures从属性文件里加载属性,并使用这些属性来替换变量。

3.spring还允许在属性文件中使用${propName}以实现属性之间的互相引用。

二:如何配置属性文件

1.在beans导入context:property-placeholder的命名空间

2.导入属性文件

<!--导入属性文件  -->
	<context:property-placeholder location="classpath:db.properties"/>
	

 3.使用db.properties文件中的属性

<?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.0.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="${driverclass}"></property>
		<property name="jdbcUrl" value="${jdbcurl}"></property>
	</bean>

</beans>

4.测试

package com.dhx.properties;

import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;

public class Main {

	public static void main(String[] args) throws SQLException {
		
		
		ApplicationContext ctx=new ClassPathXmlApplicationContext("beans-properties.xml");
		DataSource dataSource=(DataSource) ctx.getBean("dataSource");
		System.out.println(dataSource.getConnection());
	}

}

猜你喜欢

转载自blog.csdn.net/qq_39093474/article/details/85289396