使用Spring JDBC访问数据库(DataSource)

bean.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"
	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">
	<context:annotation-config />
	<context:component-scan base-package="com.lbx" />

	<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/testhib" />
		<property name="username" value="root" />
		<property name="password" value="root" />
	</bean>



	<bean id="logInterceptor" class="com.lbx.aop.LogInterceptor"></bean>
	<aop:config>
		<aop:pointcut expression="execution(public * com.lbx.dao..*.*(..))"
			id="servicePointCut" />
		<aop:aspect id="logAspect" ref="logInterceptor">
			<aop:before method="before" pointcut-ref="servicePointCut" />
			<aop:after method="afterReturning" pointcut-ref="servicePointCut" />
		</aop:aspect>
	</aop:config>

</beans>

 

 

得到数据源了,就简单了,直接使用就可以了,要在那用就使用IoC注入就OK了

package com.lbx.dao.impl;

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

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

import org.springframework.stereotype.Component;

import com.lbx.dao.UserDao;
import com.lbx.po.User;

@Component("userDao")   //UserDaoImpl
public class UserDaoImpl implements UserDao {

	private DataSource dataSource;
	
	public DataSource getDataSource() {
		return dataSource;
	}

	@Resource
	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}



	public void add(User user) {
		// TODO Auto-generated method stub
		try {
			Connection conn = dataSource.getConnection();
			conn.createStatement().executeUpdate("insert into user(username) values('libinxuan')");
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		System.out.println("一个user添加进来");
	//	throw new RuntimeException("exception!!!!"); 
	}

}

 

你可能感兴趣的:(spring,AOP,bean,mysql,jdbc)