`

学习Spring笔记_DataSource

阅读更多

 

适合有一定Spring基础的人观看

 

利用DBCP实现Spring的DataSource。

 

实现DBCP,必须引入如下几个JAR包(附件中有下载):

DBCP依赖JAR:commons-dbcp.jar、commons-pool.jar。

 

数据库依赖JAR:mySql , oracle等。

 

实现代码段如下:

beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- spring2.5配置文件固定写法 -->
<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"
	xmlns:aop="http://www.springframework.org/schema/aop"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context
           http://www.springframework.org/schema/context/spring-context-2.5.xsd
           http://www.springframework.org/schema/aop
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">

	<!-- 配置数据源 1 -->
	<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"
		destroy-method="close">
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
		<property name="url" value="jdbc:oracle:thin:@localhost:1521:orcl" />
		<property name="username" value="scott" />
		<property name="password" value="tiger" />
	</bean>

	<!-- 配置数据源 2:读取property文件 -->
	<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>


	<!-- 加入此配置就可以在源码中写Annotation(注解),注解编程 -->
	<context:annotation-config />
	<!-- 使用此配置代码,spring会自动扫描com.yusj包下的所有带@component注解的Class文件 @Component包括:@controller,@service,@repository和@component 
		当分不清楚Class具体要做什么工作时,可以统一写成@component. @controller:一般写在控制层。 @service:一般写在服务层。 
		@repository:一般写在持久层,也就是DAO。 @component (把普通pojo实例化到spring容器中,相当于配置文件中的<bean 
		id="" class=""/> -->
	<context:component-scan base-package="com.yusj" />
</beans>

 UserDAOImpl.java

package com.yusj.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.stereotype.Component;

import com.yusj.dao.IUserDAO;
import com.yusj.model.User;

/**
 * 使用@Component实现把普通类实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>
 * Component自动实例化的bean名为类的首字母小写,即userDAOImpl。如果想指定固定名可以写成@Component("udi")
 * 当此处用@Component("udi")进行重命名后,需要在用到此Bean的源代码(UserServiceImpl.setUserDAO)处使用@Resource(name="udi")注入。
 * @author yushaojian
 *
 */
@Component("udi")
public class UserDAOImpl implements IUserDAO {
	DataSource dataSource ;
	
	public DataSource getDataSource() {
		return dataSource;
	}
	/**
	 * 注入XML配置文件中配置的数据源
	 *   1. 直接在XML中配置数据源用@Resource(name="myDataSource")
	 *   2. 在XML中读取properties属性文件配置数据源用@Resource(name="dataSource")
	 * @param dataSource
	 */
	@Resource(name="dataSource")
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}

	@Override
	public void save(User user) {
		Connection conn = null ;
		PreparedStatement pstmt  = null ;
		try {
			conn = dataSource.getConnection() ;
			conn.setAutoCommit(false);
			pstmt = conn.prepareStatement("insert into person(empno,ename,job) values('1',?,?)");
			pstmt.setString(1, user.getUsername());
			pstmt.setString(2, user.getPassword());
			pstmt.executeUpdate();
			conn.commit();
			System.out.println("user save success...");
			System.out.println(user.toString());
			conn.setAutoCommit(true);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			if (conn != null) {
				try {
					conn.close();
					conn = null ;
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}
}

 jdbc.properties

jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.username=scott
jdbc.password=tiger

 Test.java

package com.yusj.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import com.yusj.model.User;
import com.yusj.service.IUserService;

public class Test {

	public static void main(String[] args) {
		
		/**
		 * Spring提供的读取配置文件方法,此处推荐使用ApplicationContext而非BeanFactory.
		 * beans配置文件默认读取src根目录文件名相同的XML文件
		 * 如果需要放在特殊的位置,那么需要指定具体路径,比如:com/yusj/xml/beans.xml
		 * 
		 */
		ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
		/**
		 * 获取UserServiceImpl.java中利用@Component("usi")自动装载的bean
		 * 
		 */
		IUserService service = (IUserService) ctx.getBean("usi");
		// 初始化用户并赋值
		User u = new User();
		u.setUsername("张三");
		u.setPassword("zhangsan");
		// 添加用户测试
		service.add(u);
		/**
		 * 输出结果:
		 * user save success...
		 * User [username=张三, password=zhangsan]
		 */
	}
}

 

 

完整代码导出见附件(Export -> General ->File System):

 

 

 

 

 

1
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics