Spring初学之使用外部配置文件dataSource
一、在Spring的基础上还要另外导入c3p0包和mysql的驱动包。
二、配置文件,
jdbc.propertices:这里只做了一些简单配置
user=root
password=123
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc\:mysql\:///test
三、spring配置文件:
<?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.3.xsd"> <!-- 导入外部配置文件--> <context:property-placeholder location="classpath:jdbc.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>
四、测试:
package spring.beans.properties.test; 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()); } }
五、输出
数据库中有对应数据库test,并配置成功,会输出
com.mchange.v2.c3p0.impl.NewProxyConnection@28ac3dc3