1. 基础知识
1.1 AOP概述
AOP
:全称是Aspect Oriented Programming即:面向切面编程。
简单的说它就是把我们程序重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的基础上,对我们的已有方法进行增强。
1.2 AOP的作用及优势
-
作用:
- 在程序运行期间,不修改源码对已有方法进行增强。 优势:
- 减少重复代码
- 提高开发效率
- 维护方便
1.3 AOP的实现方式
使用动态代理技术
对于java代码中实现动态代理的两种方式可以参考这篇文章Java实现动态代理——基于子类cglib、基于接口proxy
1.4 AOP的相关术语
-
Joinpoint(连接点):
- 所谓连接点是指那些被拦截到的点。在spring中,这些点指的是方法,因为spring只支持方法类型的连接点。 Pointcut(切入点):
- 所谓切入点是指我们要对哪些Joinpoint进行拦截的定义。 Advice(通知/增强):
- 所谓通知是指拦截到Joinpoint之后所要做的事情就是通知。
- 通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知。 Introduction(引介):
- 引介是一种特殊的通知在不修改类代码的前提下, Introduction可以在运行期为类动态地添加一些方法或Field。 Target(目标对象):
- 代理的目标对象。 Weaving(织入):
- 是指把增强应用到目标对象来创建新的代理对象的过程。
- spring采用动态代理织入,而AspectJ采用编译期织入和类装载期织入。 Proxy(代理):
- 一个类被AOP织入增强后,就产生一个结果代理类。 Aspect(切面):
- 是切入点和通知(引介)的结合。
1.5 切入点表达式
表达式语法:execution([修饰符]返回值类型包名.类名.方法名(参数))
全匹配方式:
public void com.dsy.service.impl.AccountServiceImpl.saveAccount(com.dsy.domain.Account)
-
省略规则:
- 访问修饰符可以省略
- 返回值可以使用*号,表示任意返回值
- 包名可以使用 号,表示任意包,但是有几级包,需要写几个
- 使用…来表示当前包,及其子包
- 类名可以使用*号,表示任意类
- 方法名可以使用*号,表示任意方法
- 参数列表可以使用*,表示参数可以是任意数据类型,但是必须有参数
- 参数列表可以使用…表示有无参数均可,有参数可以是任意类型
-
全通配方式:
* *..*.*(..)
通常情况下,我们都是对业务层的方法进行增强,所以切入点表达式都是切到业务层实现类。
execution(* com.dsy.service.impl.*.*(..))
1.6 xml配置aop
依赖添加:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
</dependencies>
配置实现 Logger
中的 printLog()
方法在 com.dsy.service.impl
包下所有 service实现类
之前执行日志打印方法:
<?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: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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 配置srping的Ioc,把service对象配置进来-->
<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl"></bean>
<!--spring中基于XML的AOP配置步骤
1、把通知Bean也交给spring来管理
2、使用aop:config标签表明开始AOP的配置
3、使用aop:aspect标签表明配置切面
id属性:是给切面提供一个唯一标识
ref属性:是指定通知类bean的Id。
4、在aop:aspect标签的内部使用对应标签来配置通知的类型
我们现在示例是让printLog方法在切入点方法执行之前之前:所以是前置通知
aop:before:表示配置前置通知
method属性:用于指定Logger类中哪个方法是前置通知
pointcut属性:用于指定切入点表达式,该表达式的含义指的是对业务层中哪些方法增强
-->
<!-- 配置Logger类 -->
<bean id="logger" class="com.itheima.utils.Logger"></bean>
<!--配置AOP-->
<aop:config>
<!--配置切面 -->
<aop:aspect id="logAdvice" ref="logger">
<!-- 配置通知的类型,并且建立通知方法和切入点方法的关联-->
<aop:before method="printLog" pointcut="execution(* com.dsy.service.impl.*.*(..))"></aop:before>
</aop:aspect>
</aop:config>
<!-- 更多例子 -->
<!--配置AOP-->
<aop:config>
<!-- 配置切入点表达式 id属性用于指定表达式的唯一标识。expression属性用于指定表达式内容
此标签写在aop:aspect标签内部只能当前切面使用。
它还可以写在aop:aspect外面,此时就变成了所有切面可用
-->
<aop:pointcut id="pt1" expression="execution(* com.itheima.service.impl.*.*(..))"></aop:pointcut>
<!--配置切面 -->
<aop:aspect id="logAdvice" ref="logger">
<!-- 配置前置通知:在切入点方法执行之前执行
<aop:before method="beforePrintLog" pointcut-ref="pt1" ></aop:before>-->
<!-- 配置后置通知:在切入点方法正常执行之后执行。它和异常通知永远只能执行一个
<aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"></aop:after-returning>-->
<!-- 配置异常通知:在切入点方法执行产生异常之后执行。它和后置通知永远只能执行一个
<aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"></aop:after-throwing>-->
<!-- 配置最终通知:无论切入点方法是否正常执行它都会在其后面执行
<aop:after method="afterPrintLog" pointcut-ref="pt1"></aop:after>-->
<!-- 配置环绕通知 详细的注释请看Logger类中-->
<aop:around method="aroundPringLog" pointcut-ref="pt1"></aop:around>
</aop:aspect>
</aop:config>
</beans>
1.7 注解配置aop
需要依赖同1.6
开启注解扫描配置有两种方式:
xml方式:
<!-- 配置spring创建容器时要扫描的包-->
<context:component-scan base-package="com.dsy"></context:component-scan>
<!-- 配置spring开启注解AOP的支持 -->
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
配置类方式:
package com.itheima.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
@Configuration//声明为配置类
@ComponentScan("com.dsy")//指定注解扫描包
@EnableAspectJAutoProxy//开启aop支持
public class SpringConfiguration {
}
实现:
package com.itheima.utils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
/**
* 模拟日志记录
*/
@Component("logger")
@Aspect//表示当前类是一个切面类
public class Logger {
//切入点表达式
@Pointcut("execution(* com.itheima.service.impl.*.*(..))")
private void pt1(){}
/**
* 前置通知
*/
@Before("pt1()")
public void beforePrintLog(){
System.out.println("前置通知Logger类中的beforePrintLog方法开始记录日志了。。。");
}
/**
* 后置通知
*/
@AfterReturning("pt1()")
public void afterReturningPrintLog(){
System.out.println("后置通知Logger类中的afterReturningPrintLog方法开始记录日志了。。。");
}
/**
* 异常通知
*/
@AfterThrowing("pt1()")
public void afterThrowingPrintLog(){
System.out.println("异常通知Logger类中的afterThrowingPrintLog方法开始记录日志了。。。");
}
/**
* 最终通知
*/
@After("pt1()")
public void afterPrintLog(){
System.out.println("最终通知Logger类中的afterPrintLog方法开始记录日志了。。。");
}
/**
* 环绕通知
* 配置:
* Spring框架为我们提供了一个接口:ProceedingJoinPoint。该接口有一个方法proceed(),此方法就相当于明确调用切入点方法。
* 该接口可以作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用。
*
* spring中的环绕通知:
* 它是spring框架为我们提供的一种可以在代码中手动控制增强方法何时执行的方式。
*/
@Around("pt1()")
public Object aroundPringLog(ProceedingJoinPoint pjp){
Object rtValue = null;
try{
Object[] args = pjp.getArgs();//得到方法执行所需的参数
System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。前置");
rtValue = pjp.proceed(args);//明确调用业务层方法(切入点方法)
System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。后置");
return rtValue;
}catch (Throwable t){
System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。异常");
throw new RuntimeException(t);
}finally {
System.out.println("Logger类中的aroundPringLog方法开始记录日志了。。。最终");
}
}
}
2.事务控制案例
① 首先是最基础的接口代理手写事务控制
② 然后是升级使用SpringAOP来配置代理
③ 最后是使用Spring AOP为我们提供的声明式事务支持来以最简洁的方式实现事务控制
2.0. 案例准备
创建名为study的数据库,执行以下sql
create table account(
id int primary key auto_increment,
name varchar(40),
money float
)character set utf8 collate utf8_general_ci;
insert into account(name,money) values('aaa',1000);
insert into account(name,money) values('bbb',1000);
insert into account(name,money) values('ccc',1000);
创建maven工程
pom.xml加入依赖:
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
配置类:
package com.dsy.config;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import javax.sql.DataSource;
@Configuration
@ComponentScan("com.dsy")
public class SpringConfiguration {
@Bean
@Scope("prototype")//指定为多例,避免线程安全问题
public QueryRunner createQueryRunner(DataSource dataSource){
return new QueryRunner(dataSource);
}
/**
* 创建数据源对象
* @return
*/
@Bean
public DataSource createDataSource(){
try {
ComboPooledDataSource ds = new ComboPooledDataSource();
ds.setDriverClass("com.mysql.jdbc.Driver");
ds.setJdbcUrl("jdbc:mysql://localhost:3333/eesy");
ds.setUser("root");
ds.setPassword("");
return ds;
}catch (Exception e){
throw new RuntimeException(e);
}
}
}
实体类:
package com.dsy.domain;
import java.io.Serializable;
/**
* 账户的实体类
*/
public class Account implements Serializable {
private Integer id;
private String name;
private Float money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Float getMoney() {
return money;
}
public void setMoney(Float money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
Dao层:
IAccountDao
package com.dsy.dao;
import com.dsy.domain.Account;
import java.util.List;
/**
* 账户的持久层接口
*/
public interface IAccountDao {
/**
* 查询所有
* @return
*/
List<Account> findAllAccount();
/**
* 更新
* @param account
*/
void updateAccount(Account account);
/**
* 根据名称查询账户
* @param accountName
* @return 如果有唯一的结果就返回,如果没有结果就返回null
* 如果结果集超过一个就抛出异常
*/
Account findAccountByName(String accountName);
}
AccountDaoImpl
package com.itheima.dao.impl;
import com.dsy.dao.IAccountDao;
import com.dsy.domain.Account;
import com.dsy.utils.ConnectionUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* 账户的持久层实现类
*/
@Repository
public class AccountDaoImpl implements IAccountDao {
@Autowired
private QueryRunner runner;
@Autowired
private ConnectionUtils connectionUtils;
@Override
public List<Account> findAllAccount() {
try{
return runner.query(connectionUtils.getThreadConnection(),"select * from account",new BeanListHandler<Account>(Account.class));
}catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void updateAccount(Account account) {
try{
runner.update(connectionUtils.getThreadConnection(),"update account set name=?,money=? where id=?",account.getName(),account.getMoney(),account.getId());
}catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public Account findAccountByName(String accountName) {
try{
List<Account> accounts = runner.query(connectionUtils.getThreadConnection(),"select * from account where name = ? ",new BeanListHandler<Account>(Account.class),accountName);
if (accounts == null || accounts.size() == 0){
return null;
}
if (accounts.size() > 1){
throw new RuntimeException("结果不唯一,数据有问题");
}
return accounts.get(0);
}catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Service层
IAccountService
package com.itheima.service;
import com.itheima.domain.Account;
import java.util.List;
/**
* 账户的业务层接口
*/
public interface IAccountService {
/**
* 查询所有
* @return
*/
List<Account> findAllAccount();
/**
* 更新
* @param account
*/
void updateAccount(Account account);
/**
* 转账
* @param sourceName 转出账户名称
* @param targetName 转入账户名称
* @param money 转账金额
*/
void transfer(String sourceName, String targetName, Float money);
}
AccountServiceImpl
package com.itheima.service.impl;
import com.dsy.dao.IAccountDao;
import com.dsy.domain.Account;
import com.dsy.service.IAccountService;
import com.dsy.utils.TransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 账户的业务层实现类
*/
@Service
public class AccountServiceImpl implements IAccountService{
@Autowired
private IAccountDao accountDao;
@Override
public List<Account> findAllAccount() {
return accountDao.findAllAccount();
}
@Override
public void updateAccount(Account account) {
accountDao.updateAccount(account);
}
@Override
public void transfer(String sourceName, String targetName, Float money) {
//2.1.根据名称查询转出账户
Account source = accountDao.findAccountByName(sourceName);
//2.2.根据名称查询转入账户
Account target = accountDao.findAccountByName(targetName);
//2.3.转出账户减钱
source.setMoney(source.getMoney() - money);
//2.4.转入账户加钱
target.setMoney(target.getMoney() + money);
//2.5.更新转出账户
accountDao.updateAccount(source);
//在这里制造一个异常
int i = 1/0;
//2.6.更新转入账户
accountDao.updateAccount(target);
}
}
问题描述:由于int i = 1/0;
会抛出异常,直接调用accountService的transfer方法前面执行成功后面执行不成功会导致数据的不一致性,解决方法是加入事务的控制。
2.1. 手动编写事务控制并使用接口代理实现
新建utils包,创建两个util工具类:
package com.dsy.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
/**
* 连接的工具类,用于从数据源中获取一个连接,并且实现和线程的绑定
*/
@Component
public class ConnectionUtils {
private ThreadLocal<Connection> tl = new ThreadLocal<Connection>();
@Autowired
private DataSource dataSource;
/**
* 获取当前线程上的连接
* @return
*/
public Connection getThreadConnection(){
try {
//1.先从ThreadLocal上获取
Connection connection = tl.get();
//2.判断当前线程上是否有连接
if(connection == null){
//3.从数据源中获取一个连接,并且和线程绑定,并且存入ThreadLocal中
connection = dataSource.getConnection();
tl.set(connection);
}
//4.返回当前线程上的连接
return connection;
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException();
}
}
/**
* 把连接和线程解除绑定
*/
public void removeConnection(){
tl.remove();
}
}
package com.dsy.utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.sql.SQLException;
/**
* 事务管理相关的工具类,包含了开启事务、提交事务、回滚事务和释放连接
*/
@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().close();//还回连接池中
connectionUtils.removeConnection();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
通过这两个工具类,我们可以直接用以下范式来进行事务控制:
try {
//1.开启事务
txManager.beginTransaction();
//2.执行操作
.......
//3.提交事务
txManager.commit();
//4.返回结果
return resultVal;
} catch (Exception e) {
//5.回滚操作
txManager.rollback();
e.printStackTrace();
throw new RuntimeException(e);
}finally {
//6.释放连接
txManager.release();
}
那么为了不侵入之前的代码,我们直接对service进行代理:
package com.dsy.factory;
import com.dsy.domain.Account;
import com.dsy.service.IAccountService;
import com.dsy.utils.TransactionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
@Configuration
public class BeanFactory {
@Autowired
private IAccountService accountService;
@Autowired
private TransactionManager txManager;
/**
* 将service的代理对象添加到IOC容器中
* @return
*/
@Bean("proxyAccountService")
public IAccountService getAccountService() {
return (IAccountService)Proxy.newProxyInstance(accountService.getClass().getClassLoader(),
accountService.getClass().getInterfaces(),
new InvocationHandler() {
//添加事务的支持
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object resultVal = null;
try {
//1.开启事务
txManager.beginTransaction();
//2.执行操作
resultVal = method.invoke(accountService, args);
//3.提交事务
txManager.commit();
//4.返回结果
return resultVal;
} catch (Exception e) {
//5.回滚操作
txManager.rollback();
e.printStackTrace();
throw new RuntimeException(e);
}finally {
//6.释放连接
txManager.release();
}
}
});
}
}
编写测试类:
package com.dsy.test;
import com.dsy.config.SpringConfiguration;
import com.dsy.domain.Account;
import com.dsy.factory.BeanFactory;
import com.dsy.service.IAccountService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {SpringConfiguration.class, BeanFactory.class})
public class AccountServiceTest {
@Autowired
@Qualifier("accountServiceImpl")
private IAccountService accountService;//原始service对象,没有事务控制
@Autowired
@Qualifier("proxyAccountService")
private IAccountService proxyAccountService;//代理service的对象,有事务控制
//执行此方法,AccountServiceImpl的transfer()中有异常时,aaa会减100,但是bbb并不会加100,造成了数据不一致
@Test
public void testTransfer(){
accountService.transfer("aaa","bbb",100f);
}
//执行此方法,AccountServiceImpl的transfer()中有异常时,由于进行了事务控制,当出现异常时,aaa减100的操作会回滚,会保证数据一致性
@Test
public void testProxyTransfer(){
proxyAccountService.transfer("aaa","bbb",100f);
}
}
2.2. 使用Spring的AOP实现
新建utils包,创建两个util工具类
…(同上)
开启aop注解支持
在配置类上加上注解@EnableAspectJAutoProxy
@Configuration
@ComponentScan("com.dsy")
@EnableAspectJAutoProxy //开启AOP注解
public class SpringConfiguration {
......
}
编写aop实现代码
新建aop包,在包下创建AopTransaction类:
package com.dsy.aop;
import com.itheima.utils.TransactionManager;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
@Aspect //表示当前类是一个切面类
public class AopTransaction {
@Autowired
private TransactionManager txManager;
@Around("execution(* com.itheima.service.impl.*.*(..))")
public Object tansactionManage(ProceedingJoinPoint pjp){
Object resultVal = null;
try {
//1.开启事务
txManager.beginTransaction();
//2.执行操作
Object[] args = pjp.getArgs();//得到方法执行所需的参数
resultVal = pjp.proceed(args);
//3.提交事务
txManager.commit();
//4.返回结果
return resultVal;
} catch (Throwable throwable) {
//5.回滚操作
txManager.rollback();
throwable.printStackTrace();
throw new RuntimeException(throwable);
}finally {
//6.释放连接
txManager.release();
}
}
}
Test代码:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfiguration.class)
public class AccountServiceTest {
@Autowired
@Qualifier("accountServiceImpl")
private IAccountService accountService;
@Test
public void testTransfer(){
accountService.transfer("aaa","bbb",100f);
}
}
执行时会先直接到 AopTransaction
类的 tansactionManage()
方法,进行事务控制,当有异常时,会回滚,没有异常时会正常执行。
2.3 声明式事务配置
在配置类上加上@EnableTransactionManagement
开启声明式事务支持
在AccountServiceImpl类上加上@Transactional
开启事务