spring连接池的配置,可以有三种连接池的配置(常用):
i.c3p0
ii.dbcp
iii.proxool
用到哪种去查那种情况的配置即可。
下面我们主要说dbcp。
除了这么写:
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<!-- results in a setDriverClassName(String) call -->
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</bean>
还可以这么写:
把数据库的信息存进Properties文件
jdbc.properties文件:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring
jdbc.username=root
jdbc.password=1234
在Spring中可以使用PropertyPlaceHolderConfigure来读取Properties文件的内容
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<value>classpath:com/foo/jdbc.properties</value>
</property>
</bean>
<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
测试:
package cn.edu.hpu.service;
import org.junit.Test;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.edu.hpu.dao.UserDao;
import cn.edu.hpu.model.User;
public class UserServiceTest {
@Test
public void testAdd() throws Exception{
ClassPathXmlApplicationContext ctx=new ClassPathXmlApplicationContext("beans.xml");
UserService userService=(UserService)ctx.getBean("userService");
System.out.println(userService.getClass());
User u=new User();
u.setUsername("u1");
u.setPassword("p1");
userService.add(u);
ctx.destroy();
}
}
结果:
add success!!
存储成功
标签:userService,jdbc,框架,spring,dbcp,DataSource,import,org From: https://blog.51cto.com/u_16012040/6131095