用spring 创建ComboPooledDataSource和JdbcTemplate对象
3.1添加ioc相关jar包
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.3.18.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.3.18.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.18.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>4.3.18.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>4.3.18.RELEASE</version> </dependency>
3.2创建db.properties文件
driverClass=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/ssm user=root password=123
3.3在applicationContext.xml文件中创建对象
<context:property-placeholder location="db.properties"></context:property-placeholder> <!-- 创建一个连接池对象 --> <bean id="comboPooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${driverClass}" /> <property name="jdbcUrl" value="${url}"/> <property name="user" value="${user}" /> <property name="password" value="${password}" /> </bean> <!-- 创建一个jdbcTemplate对象 并且通过构造函数 将连接池对象 注入到jdbcTemplate --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" > <constructor-arg name="dataSource" ref="comboPooledDataSource" /> </bean>
3.4 修改dao 层
<context:property-placeholder location="db.properties"></context:property-placeholder> <!-- 创建一个连接池对象 --> <bean id="comboPooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="driverClass" value="${driverClass}" /> <property name="jdbcUrl" value="${url}"/> <property name="user" value="${user}" /> <property name="password" value="${password}" /> </bean> <!-- 创建一个jdbcTemplate对象 并且通过构造函数 将连接池对象 注入到jdbcTemplate --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" > <constructor-arg name="dataSource" ref="comboPooledDataSource" /> </bean>
3.5测试
@Test public void test() { ClassPathXmlApplicationContext applicationContext=new ClassPathXmlApplicationContext("applicationContext.xml"); IUsersDao usersDao= applicationContext.getBean("usersDao",IUsersDao.class); Users user=new Users("xiaowanglaoshi","123"); usersDao.add(user); }
标签:4.3,spring,springframework,JdbcTemplate,18,RELEASE,org,ComboPooledDataSource From: https://www.cnblogs.com/daimenglaoshi/p/16743460.html