转账案例
使用spring框架整合DBUtils技术,实现用户转账功能
- 创建java项目,导入坐标
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.15</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
</dependencies>
- 编写Account实体类
@Data
public class Account {
private int id;
private String name;
private double money;
}
- 编写线程绑定连接工具类
@Component
public class ConnectionUtils {
// ThreadLocal : 线程内部的存储类,可以在指定的线程内存储数据 key:threadLocal(当前线程) value:任意类型的值 Connection
private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
@Autowired
private DataSource dataSource;
/**
* 获取当前线程上的连接,如果获取到的连接为空,那么就要从数据源中获取连接,并且放到ThreadLocal中(绑定到当前线程)
*
* @return connection
*/
public Connection getThreadConnection() {
Connection connection = threadLocal.get();
if (connection == null) {
try {
connection = dataSource.getConnection();
threadLocal.set(connection);
} catch (SQLException e) {
e.printStackTrace();
}
}
return connection;
}
/**
* 解除当前线程的连接绑定
*/
public void removeThreadConnection() {
threadLocal.remove();
}
}
- 编写事务管理器
@Component
public class TransactionManager {
@Autowired
private ConnectionUtils connectionUtils;
/**
* 开启手动提交事务
*/
public void beginTransaction() {
try {
connectionUtils.getThreadConnection().setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 提交事务
*/
public void commit() {
try {
connectionUtils.getThreadConnection().commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 回滚事务
*/
public void rollback() {
try {
connectionUtils.getThreadConnection().rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 释放资源
*/
public void release() {
try {
connectionUtils.getThreadConnection().setAutoCommit(true);
connectionUtils.getThreadConnection().close();
connectionUtils.removeThreadConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
- JDK动态代理方式
@Component
public class JDKProxyFactory {
@Autowired
private AccountService accountService;
@Autowired
private TransactionManager transactionManager;
/**
* 采用JDK动态代理技术来生成目标类的代理对象
* ClassLoader loader, : 类加载器:借助被代理对象获取到类加载器
* Class<?>[] interfaces, : 被代理类所需要实现的全部接口
* InvocationHandler h : 当代理对象调用接口中的任意方法时,那么都会执行InvocationHandler中invoke方法
*
* @return AccountService对象
*/
public AccountService createAccountServiceJDKProxy() {
return (AccountService) Proxy.newProxyInstance(
accountService.getClass().getClassLoader(), accountService.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
transactionManager.beginTransaction();
method.invoke(accountService, args);
transactionManager.commit();
} catch (Exception e) {
e.printStackTrace();
transactionManager.rollback();
} finally {
transactionManager.release();
}
return null;
}
});
}
}
- CGLIB动态代理方式
@Component
public class CglibProxyFactory {
@Autowired
private AccountService accountService;
@Autowired
private TransactionManager transactionManager;
public AccountService createAccountServiceCglibProxy() {
return (AccountService) Enhancer.create(accountService.getClass(), new MethodInterceptor() {
@Override
public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
try {
transactionManager.beginTransaction();
method.invoke(accountService, objects);
transactionManager.commit();
} catch (Exception e) {
e.printStackTrace();
transactionManager.rollback();
} finally {
transactionManager.release();
}
return null;
}
});
}
}
- 编写AccountDao接口和实现类
public interface AccountDao {
/**
* 转出
*
* @param name 转账人
* @param money 转账金额
*/
void out(String name, double money);
/**
* 转入
*
* @param name 入账人
* @param money 入账金额
*/
void in(String name, double money);
}
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
@Autowired
private QueryRunner queryRunner;
@Autowired
private ConnectionUtils connectionUtils;
public void out(String name, double money) {
String sql = "update account set money = money - ? where name = ?";
try {
queryRunner.update(connectionUtils.getThreadConnection(), sql, money, name);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void in(String name, double money) {
String sql = "update account set money = money + ? where name = ?";
try {
queryRunner.update(connectionUtils.getThreadConnection(), sql, money, name);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
- 编写AccountService接口和实现类
public interface AccountService {
/**
* 转账入账
*
* @param outName 转账人
* @param inName 入账人
* @param money 金额
*/
void transfer(String outName, String inName, double money);
}
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
public void transfer(String outName, String inName, double money) {
accountDao.out(outName, money);
int i = 1/0;
accountDao.in(inName, money);
}
}
- 编写spring核心配置文件
<?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"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
">
<!--开启注解扫描-->
<context:component-scan base-package="com.lagou"/>
<!--加载jdbc.properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<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>
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
<constructor-arg name="ds" ref="dataSource"/>
</bean>
</beans>
- 编写测试代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestTransfer {
@Autowired
private JDKProxyFactory jdkProxyFactory;
@Autowired
private CglibProxyFactory cglibProxyFactory;
@Test
public void test1() {
// JDK动态代理
jdkProxyFactory.createAccountServiceJDKProxy().transfer("tom", "jerry", 100.00);
//cglib动态代理
cglibProxyFactory.createAccountServiceCglibProxy().transfer("tom", "jerry", 100.00);
}
}
常用的动态代理技术
- JDK 代理 : 基于接口的动态代理技术·:利用拦截器(必须实现invocationHandler)加上反射机制生成一个代理接口的匿名类,在调用具体方法前调用InvokeHandler来处理,从而实现方法增强
- CGLIB代理:基于父类的动态代理技术:动态生成一个要代理的子类,子类重写要代理的类的所有不是final的方法。在子类中采用方法拦截技术拦截所有的父类方法的调用,顺势织入横切逻辑,对方法进行增强
AOP
- AOP 为 Aspect Oriented Programming 的缩写,意思为面向切面编程
- AOP 是 OOP(面向对象编程) 的延续,是软件开发中的一个热点,也是Spring框架中的一个重要内容,利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
- 好处:
- 在程序运行期间,在不修改源码的情况下对方法进行功能增强
- 逻辑清晰,开发核心业务的时候,不必关注增强业务的代码
- 减少重复代码,提高开发效率,便于后期维护
AOP底层实现
AOP 的底层是通过 Spring 提供的的动态代理技术实现的。在运行期间,Spring通过动态代理技术动态的生成代理对象,代理对象方法执行时进行增强功能的介入,在去调用目标对象的方法,从而完成功能的增强。
AOP相关术语
- Spring 的 AOP 实现底层就是对上面的动态代理的代码进行了封装,封装后我们只需要对需要关注的部分进行代码编写,并通过配置的方式完成指定目标的方法增强。
- 常用的术语:
Target(目标对象):代理的目标对象
Proxy (代理):一个类被 AOP 织入增强后,就产生一个结果代理类
Joinpoint(连接点):所谓连接点是指那些可以被拦截到的点。在spring中,这些点指的是方法,因为spring只支持方法类型的连接点,通俗的说所有方法都可以是连接点
Pointcut(切入点):所谓切入点是指已经增强的方法
Advice(通知/ 增强):所谓通知是指拦截到 Joinpoint 之后所要做的事情就是通知
分类:前置通知、后置通知、异常通知、最终通知、环绕通知Aspect(切面):是切入点和通知(引介)的结合
Weaving(织入):是指把增强应用到目标对象来创建新的代理对象的过程。spring采用动态代理织入,而AspectJ采用编译期织入和类装载期织入
AOP开发明确事项
开发阶段(我们做的)
- 编写核心业务代码(目标类的目标方法) 切入点
- 把公用代码抽取出来,制作成通知(增强功能方法) 通知
- 在配置文件中,声明切入点与通知间的关系,即切面
运行阶段(Spring框架完成的)
Spring 框架监控切入点方法的执行。一旦监控到切入点方法被运行,使用代理机制,动态创建目标对象的代理对象,根据通知类别,在代理对象的对应位置,将通知对应的功能织入,完成完整的代码逻辑运行。
底层代理实现
在 Spring 中,框架会根据目标类是否实现了接口来决定采用哪种动态代理的方式。
- 当bean实现接口时,会用JDK代理模式
- 当bean没有实现接口,用cglib实现( 可以强制使用cglib(在spring配置中加入
<aop:aspectjautoproxy proxyt-target-class=”true”/>
)
基于XML的AOP开发
- 创建java项目,导入AOP相关坐标
<dependencies>
<!--导入spring的context坐标,context依赖aop-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<!-- aspectj的织入(切点表达式需要用到该jar包) -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.6</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.15</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
- dao层接口和实现类
public interface AccountDao {
/**
* 转账
*
* @param name 转账人
* @param money 金额
*/
void out(String name, double money);
/**
* 入账
*
* @param name 入账人
* @param money 金额
*/
void in(String name, double money);
}
@Repository("accountDao")
public class AccountDaoImpl implements AccountDao {
@Autowired
private QueryRunner queryRunner;
@Autowired
private ConnectionUtils connectionUtils;
public void out(String name, double money) {
String sql = "update account set money = money - ? where name = ?";
try {
queryRunner.update(connectionUtils.getConnection(), sql, money, name);
} catch (SQLException e) {
e.printStackTrace();
}
}
public void in(String name, double money) {
String sql = "update account set money = money + ? where name = ?";
try {
queryRunner.update(connectionUtils.getConnection(), sql, money, name);
} catch (SQLException e) {
e.printStackTrace();
}
}
}
- 创建目标接口和目标实现类(定义切入点)
public interface AccountService {
/**
* 转账
*
* @param outName 转账人
* @param inName 入账人
* @param money 金额
*/
void transfer(String outName, String inName, double money);
}
@Service("accountService")
public class AccountServiceImpl implements AccountService {
@Autowired
private AccountDao accountDao;
public void transfer(String outName, String inName, double money) {
accountDao.out(outName, money);
int i = 1/0;
accountDao.in(inName, money);
}
}
- 编写获取连接工具类
@Component
public class ConnectionUtils {
private ThreadLocal<Connection> threadLocal = new ThreadLocal<>();
@Autowired
private DataSource dataSource;
/**
* 获取连接
* @return connection
*/
public Connection getConnection() {
Connection connection = threadLocal.get();
if (connection == null) {
try {
connection = dataSource.getConnection();
threadLocal.set(connection);
} catch (SQLException e) {
e.printStackTrace();
}
}
return connection;
}
/**
* 解除线程绑定
*/
public void removeThreadLocal() {
threadLocal.remove();
}
}
- 创建通知类及方法(定义通知)
@Component("transactionManager")
public class TransactionManager {
@Autowired
private ConnectionUtils connectionUtils;
/**
* 开启手动提交事务
*/
public void beginTransaction() {
try {
connectionUtils.getConnection().setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 手动提交事务
*/
public void commit() {
try {
connectionUtils.getConnection().commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 事务回滚
*/
public void rollback() {
try {
connectionUtils.getConnection().rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 释放资源
*/
public void release() {
try {
connectionUtils.getConnection().setAutoCommit(true);
connectionUtils.getConnection().close();
connectionUtils.removeThreadLocal();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
- 在核心配置文件中配置织入关系,及切面
<?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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!--开启注解扫描-->
<context:component-scan base-package="com.lagou"/>
<!--加载jdbc.properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--将dataSource交给IOC容器管理-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<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>
<!--将queryRunner交给IOC容器管理-->
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
<constructor-arg name="ds" ref="dataSource"/>
</bean>
<!--AOP配置-->
<aop:config>
<!--抽取切点,方便后续增强方法引入-->
<aop:pointcut id="transactionPointcut" expression="execution(* com.lagou.service.impl.AccountServiceImpl.*(..))"/>
<!--配置切面,引入通知类(增强类)-->
<aop:aspect ref="transactionManager">
<!--前置增强-->
<aop:before method="beginTransaction" pointcut-ref="transactionPointcut"/>
<!--后置增强-->
<aop:after-returning method="commit" pointcut-ref="transactionPointcut"/>
<!--异常增强-->
<aop:after-throwing method="rollback" pointcut-ref="transactionPointcut"/>
<!--最终增强-->
<aop:after method="release" pointcut-ref="transactionPointcut"/>
</aop:aspect>
</aop:config>
</beans>
- 编写测试代码
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class SpringTransactionTest {
@Autowired
private AccountService accountService;
@Test
public void test() {
accountService.transfer("tom", "jerry", 1000);
}
}
XML配置AOP详解
切点表达式
表达式语法:execution([修饰符] 返回值类型 包名.类名.方法名(参数))
- 访问修饰符可以省略
- 返回值类型、包名、类名、方法名可以使用星号 * 代替,代表任意
- 包名与类名之间一个点 . 代表当前包下的类,两个点 … 表示当前包及其子包下的类
- 参数列表可以使用两个点 … 表示任意个数,任意类型的参数列表
例如:
execution(public void com.lagou.service.impl.AccountServiceImpl.transfer())
execution(void com.lagou.service.impl.AccountServiceImpl.*(..))
execution(* com.lagou.service.impl.*.*(..))
execution(* com.lagou.service..*.*(..))
切点表达式抽取
当多个增强的切点表达式相同时,可以将切点表达式进行抽取,在增强中使用 pointcut-ref 属性代替pointcut 属性来引用抽取后的切点表达式。
通知类型
注意:
1.通常情况下,环绕通知都是独立使用的
2.使用注解开发的话最终通知会在后置通知和异常通知之前执行,是spirng的bug
3.如果使用注解开发的话最好使用环绕通知,因为我们可以手动编写代码来规定执行的顺序
4.后置通知和异常通知只会执行一个
基于注解的AOP开发
@Component("transactionManager")
@Aspect
public class TransactionManager {
@Autowired
private ConnectionUtils connectionUtils;
@Pointcut("execution(* com.lagou.service.impl.AccountServiceImpl.*(..))")
public void transactionPointcut() {
}
/**
* 环绕通知
*
* @param pjp pjp
* @return Object
*/
@Around("execution(* com.lagou.service.impl.AccountServiceImpl.*(..))")
public Object around(ProceedingJoinPoint pjp) throws SQLException {
Object proceed = null;
try {
connectionUtils.getConnection().setAutoCommit(false);
proceed = pjp.proceed();
connectionUtils.getConnection().commit();
} catch (Throwable throwable) {
throwable.printStackTrace();
connectionUtils.getConnection().rollback();
} finally {
connectionUtils.getConnection().setAutoCommit(true);
connectionUtils.getConnection().close();
connectionUtils.removeThreadLocal();
}
return proceed;
}
}
<?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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
">
<!--开启注解扫描-->
<context:component-scan base-package="com.lagou"/>
<!--加载jdbc.properties文件-->
<context:property-placeholder location="classpath:jdbc.properties"/>
<!--将dataSource交给IOC容器管理-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<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>
<!--将queryRunner交给IOC容器管理-->
<bean id="queryRunner" class="org.apache.commons.dbutils.QueryRunner">
<constructor-arg name="ds" ref="dataSource"/>
</bean>
<!--开启AOP自动代理-->
<aop:aspectj-autoproxy expose-proxy="true"/>
</beans>
注解配置AOP详解
配置切面类
核心配置类
注意:当使用注解的方式来配置增强方法时,一定要在配置文件或配置类中开启AOP自动代理