Spring使用c3p0属性文件

首先,在 applicationContext.xml 核心配置文件中需要用到 context 命名空间,然后用一个标签指定 properties文件 的位置就OK

  1. 属性文件: jdbc.properties

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test_spring5?useUnicode=true&characterEncoding=utf8&useSSL=true
jdbc.user=root
jdbc.password=123456


c3p0.initialPoolSize=5
c3p0.acquireIncrement=5
c3p0.maxPoolSize=20
c3p0.minPoolSize=5
c3p0.maxStatements=200
c3p0.maxStatementsPerConnection=5

 2. 核心配置文件:applicationContext.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.3.xsd">

	<!-- 导入资源属性文件 -->
	<context:property-placeholder location="classpath:jdbc.properties"/>
	<!-- c3p0 连接池 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<!-- 类似EL表达式取资源文件的值 -->
		<property name="driverClass" value="${jdbc.driverClass}"></property>
		<property name="jdbcUrl" value="${jdbc.url}"></property>
		<property name="user" value="${jdbc.user}"></property>
		<property name="password" value="${jdbc.password}"></property>


		<property name="initialPoolSize" value="${c3p0.initialPoolSize}"></property>
		<property name="acquireIncrement" value="${c3p0.acquireIncrement}"></property>
		<property name="maxPoolSize" value="${c3p0.maxPoolSize}"></property>
		<property name="minPoolSize" value="${c3p0.minPoolSize}"></property>
		<property name="maxStatements" value="${c3p0.maxStatements}"></property>
		<property name="maxStatementsPerConnection" value="${c3p0.maxStatementsPerConnection}"></property>
	</bean>
</beans>

 3. 测试类:

	@Test
	public void test() throws SQLException {
		// 1.初始化ioc容器(装对象的容器)
		ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
	
		//2. javax.sql.DataSource;
		DataSource dataSource = (DataSource) context.getBean("dataSource");
		System.out.println(dataSource.getConnection());
	}
----
com.mchange.v2.c3p0.impl.NewProxyConnection@7d3a22a9 [wrapping: com.mysql.jdbc.JDBC4Connection@1d082e88]

配置参数参考文章:https://www.cnblogs.com/JavaSubin/p/5294721.html

猜你喜欢

转载自blog.csdn.net/qq_42402854/article/details/81951215