当前位置:Gxlcms >
数据库问题 >
Spring DBCP用xml和properties2种格式配置DataSource
Spring DBCP用xml和properties2种格式配置DataSource
时间:2021-07-01 10:21:17
帮助过:23人阅读
Spring提供数据库连接池:DBCP配置DataSource并且获取连接完成数据库操作:
Spring帮助文档的地址:
http://static.springsource.org/spring/docs/2.5.6/reference/beans.html#beans-value-element
以下内容需要导入的jar包:
commons-dbcp.jar
commons-pool.jar
mysql-connector-java-5.0-nightly-20071116-bin.jar
1. 首先在容器内配置数据源
[html] view plain copy
- <!-- 配置数据源 -->
- <bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
- <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
- <property name="url" value="jdbc:mysql://localhost:3306/sms"/>
- <property name="username" value="root"/>
- <property name="password" value="root"/>
- </bean>
2.拿到注入数据源并且编写对数据库的操作
[java] view plain copy
- @Component("userService")
- public class UserServiceImpl implements UserService{
- private UserDao userDao;
- public void setUserDao(UserDao userDao) {
- this.userDao = userDao;
- }
- @Resource //resource注入
- private DataSource myDataSource;
- public DataSource getMyDataSource() {
- return myDataSource;
- }
- public void setMyDataSource(DataSource myDataSource) {
- this.myDataSource = myDataSource;
- }
- //在下面方法前面加逻辑
- public void save(){
- try{
- //拿到连接执行操作
- Connection conn = myDataSource.getConnection();
- conn.createStatement().execute("insert into dept values(‘6‘,‘bumen2‘)");
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- }
3.测试运行
[java] view plain copy
- @Test
- public void test01() {
- BeanFactory applicationContext = new ClassPathXmlApplicationContext(
- "beans.xml");
- UserService user = (UserService) applicationContext.getBean("userService");
- user.save();
- }
----------------------------------------------------------------------------------------------------------------------------------通过Properties的方式配置xml的datasource:
1、 编写properties文件:
[html] view plain copy
- jdbc.driverClassName=com.mysql.jdbc.Driver
- jdbc.url=jdbc:mysql://localhost:3306/sms
- jdbc.username=root
- jdbc.password=root
2、编写xml容器配置:
[html] view plain copy
- <!-- placeholder 占位符 -->
- <bean
- class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <property name="locations">
- <value>classpath: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>
Spring DBCP用xml和properties2种格式配置DataSource
标签:property net factor create url 格式 users hang 帮助文档