jdbc.properties
user=root password=root driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/test initialSize=5 maxActive=10
<?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.alibaba.druid.pool.DruidDataSource"> <property name="username" value="${user}" /> <property name="password" value="${password}" /> <property name="driverClassName" value="${driverClassName}" /> <property name="url" value="${url}" /> <property name="initialSize" value="${initialSize}" /> <property name="maxActive" value="${maxActive}" /> </bean> </beans>
package com.cn.test; import javax.sql.DataSource; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class DataSourceTest { @Test public void test1() throws Exception { ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml"); DataSource dataSource = (DataSource) applicationContext.getBean("dataSource"); System.out.println( dataSource.getConnection() ); } }