Spring_使用外部属性文件

 

 

beans-properties.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="root"></property>
<property name="password" value="1234"></property>
<property name="jdbcUrl" value="jdbc:mysql://test"></property>
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
</bean>

</beans>

db.properties

user=root
password=1234
jdbcUrl=jdbc:mysql://test
driverClass=com.mysql.jdbc.Driver

Main.java

package com.hy.spring.beans.properties;

import java.sql.SQLException;

import javax.sql.DataSource;

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

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());
}

}

posted @ 2016-08-22 22:20  疯狂的tiger  阅读(968)  评论(0编辑  收藏  举报