Spring AOP
1.AOP概述
1.1什么是AOP
AOP:全称是Aspect Oriented Programming即:面向切面编程。
简单的说它就是把我们程序重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的基础上,对我们的已有方法进行增强。
1.2 AOP的作用及优势
作用: 在程序运行期间,不修改源码对已有方法进行增强。
优势:
减少重复代码
提高开发效率
维护方便
1.3 AOP的实现方式
使用动态代理技术
2.AOP的具体应用
2.1 AOP的引入
2.1.2 事务问题
我们在三层架构中实现账户的增删改查时,你是否能看拿出来问题?
/** * 账户的业务层实现类 * */
public class AccountServiceImpl implements IAccountService{
private IAccountDao accountDao;
public void setAccountDao(IAccountDao accountDao) {
this.accountDao = accountDao;
}
@Override
public void saveAccount(Account account) throws SQLException { accountDao.save(account); }
@Override
public void updateAccount(Account account) throws SQLException{ accountDao.update(account); }
@Override
public void deleteAccount(Integer accountId) throws SQLException{ accountDao.delete(accountId); }
@Override
public Account findAccountById(Integer accountId) throws SQLException { return accountDao.findById(accountId); }
@Override
public List<Account> findAllAccount() throws SQLException{ return accountDao.findAll(); }
}
问题就是事务被自动控制了。换言之,我们使用了connection对象的setAutoCommit(true) 此方式控制事务,如果我们每次都执行一条sql语句,没有问题,但是如果业务方法一次要执行多条sql语句,这种方式就无法实现功能了。
当我们增加一个转帐方法,设计多条sql语句。
public void transfer(String sourceName, String targetName, Float money) {
//转账
//查询转出账户
Account source = accountDao.findAccoutByName(sourceName);
//查询目标账户
Account target = accountDao.findAccoutByName(targetName);
//转出账户减钱
source.setMoney(source.getMoney()-money);
//目标账户加钱
target.setMoney(target.getMoney()+money);
//更新两个账户
accountDao.updateAccount(source);
int i=1/0; //模拟转账异常
accountDao.updateAccount(target);
当我们执行时,由于执行有异常,转账失败。导致转出账户少钱,但目标账户没有收到钱。这是因为我们是每次执行持久层方法都是独立事务,导致无法实现事务控制(不符合事务的一致性)
2.2.2 解决方法
- 让业务层来控制事务的提交和回滚
public class AccountServiceImpl implements AccountService {
private AccountDao accountDao;
private TransactionManager txManager; //事务管理类
public void setTxManager(TransactionManager txManager) {
this.txManager = txManager;
}
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
public List<Account> findAll() {
try {
//1.开启事务
txManager.beginTransaction();
//2.执行操作
List<Account> accounts = accountDao.findAll();
//3.提交事务
txManager.commit();
//4.返回结果
return accounts;
}catch (Exception e){
//5.回滚操作
txManager.rollback();
throw new RuntimeException(e);
}finally {
//6.释放连接
txManager.release();
}
}
public Account findAccountById(Integer id) {。。。 }
public void saveAccount(Account account) {。。。。}
public void updateAccount(Account account) { 。。。。。}
public void delAccount(Integer id) {
try {
//1.开启事务
txManager.beginTransaction();
//2.执行操作
accountDao.delAccount(id);
//3.提交事务
txManager.commit();
//4.返回结果
}catch (Exception e){
//5.回滚操作
txManager.rollback();
throw new RuntimeException(e);
}finally {
//6.释放连接
txManager.release();
}
}
public void transfer(String sourceName, String targetName, Float money) {
try {
//1.开启事务
txManager.beginTransaction();
//2.执行操作
//转账
//查询转出账户
Account source = accountDao.findAccoutByName(sourceName);
//查询目标账户
Account target = accountDao.findAccoutByName(targetName);
//转出账户减钱
source.setMoney(source.getMoney()-money);
//目标账户加钱
target.setMoney(target.getMoney()+money);
//更新
accountDao.updateAccount(source);
accountDao.updateAccount(target);
//3.提交事务
txManager.commit();
//4.返回结果
}catch (Exception e){
//5.回滚操作
txManager.rollback();
throw new RuntimeException(e);
}finally {
//6.释放连接
txManager.release();
}
}
}
事物管理类
开启事物 提交事务 回滚事务 释放连接
/**
* 和事务相关的工具类
*
*/
public class TransactionManager {
//获取连接时将线程与连接绑定
private ConnectionUtils connectionUtils;
public void setConnectionUtils(ConnectionUtils connectionUtils) {
this.connectionUtils = connectionUtils;
}
/**
* 开启事务
*/
public void beginTransaction(){
try {
connectionUtils.getThreadConnection().setAutoCommit(false);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 提交事务
*/
public void commit(){
try {
connectionUtils.getThreadConnection().commit();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 回滚事务
*/
public void rollback(){
try {
connectionUtils.getThreadConnection().rollback();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 释放连接
*/
public void release(){
try {
connectionUtils.getThreadConnection().close();//还回连接池中。
connectionUtils.removeConnection();//连接与线程解绑
} catch (Exception e) {
e.printStackTrace();
}
}
}
2.3 新的问题:
通过对业务层改造,已经可以实现事务控制了,但是由于我们添加了事务控制,也产生了一个新的问题: 业务层方法变得臃肿了,里面充斥着很多重复代码。并且业务层方法和事务控制方法耦合了。 试想一下,如果我们此时提交,回滚,释放资源中任何一个方法名变更,都需要修改业务层的代码,况且这还只是一个业务层实现类,而实际的项目中这种业务层实现类可能有十几个甚至几十个。
3.动态代理的引入
3.1 动态代理的特点
字节码随用随创建,随用随加载。
它与静态代理的区别也在于此。因为静态代理是字节码一上来就创建好,并完成加载。 装饰者模式就是静态代理的一种体现。
3.2 动态代理常用的有两种方式
3.2.1 基于接口的动态代理
提供者:JDK官方的Proxy类。
要求:被代理类最少实现一个接口
3.2.2 基于子类的动态代理
提供者:第三方的CGLib,如果报asmxxxx异常,需要导入asm.jar。
要求:被代理类不能用final修饰的类(最终类)。
3.3 用动态代理解决问题
我们可以创建业务层的动态代理对象,在业务层方法调用时进行事务增强。
/**
* 创建service的的动态代理对象 并实现事务增强
*/
public class BeanFactory {
//被代理对象
private AccountService accountService;
//引入事务管理类
private TransactionManager txManager;
public void setAccountService(AccountService accountService) {
this.accountService = accountService;
}
public final void setTxManager(TransactionManager txManager) {
this.txManager = txManager;
}
/**
* 创建代理对象
* @return
*/
public AccountService getAccountService() {
/**
* 获取代理对象:
* 要求: 被代理类最少实现一个接口
* 创建的方式 Proxy.newProxyInstance(三个参数)
* 参数含义:
* ClassLoader:和被代理对象使用相同的类加载器。
* Interfaces:和被代理对象具有相同的行为。实现相同的接口。
* InvocationHandler:如何代理。
*/
AccountService proxyAccountService=(AccountService) Proxy.newProxyInstance(
accountService.getClass().getClassLoader(),
accountService.getClass().getInterfaces(),
new InvocationHandler() {
/**
* 方法增强
* 执行被代理对象的任何方法,都会经过该方法。
* 此方法有拦截的功能。
* 此处添加事务控制
* @param proxy //代理对象的引用
* @param method // 当前执行的方法
* @param args // 当前执行方法的参数
* @return // 当前执行方法的返回值
* @throws Throwable
*/
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object rtValue=null;
try {
//1.开启事务
txManager.beginTransaction();
//2.执行操作
rtValue = method.invoke(accountService, args);
//3.提交事务
txManager.commit();
//4.返回结果
return rtValue;
}catch (Exception e){
//5.回滚操作
txManager.rollback();
throw new RuntimeException(e);
}finally {
//6.释放连接
txManager.release();
}
}
});
return proxyAccountService;
}
}
原来在业务层中每个方法控制事务的代码就可以删除了,在代理对象调用业务层中每一个方法时,会被拦截增进行事务增强。这样一来把我们程序重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的基础上,对我们的已有方法进行增强。这就是aop的本质。
4.Spring 中AOP
4.1 Spring中AOP的细节
4.1.1 说明
我们学习spring的aop,就是通过配置的方式,实现上述案例的功能。
4.1.2 AOP中的术语
- Joinpoint(连接点):
所谓连接点是指那些被拦截到的点。在spring中,这些点指的是方法,因为spring只支持方法类型的连接点。 - Pointcut(切入点):
所谓切入点是指我们要对哪些Joinpoint进行拦截的定义。 - Advice(通知/增强):
所谓通知是指拦截到Joinpoint之后所要做的事情就是通知。
通知的类型:前置通知,后置通知,异常通知,最终通知,环绕通知。 - Introduction(引介):
引介是一种特殊的通知在不修改类代码的前提下,
Introduction可以在运行期为类动态地添加一些方法或Field。 - Target(目标对象):
代理的目标对象。 - Weaving(织入):
是指把增强应用到目标对象来创建新的代理对象的过程。
spring采用动态代理织入,而AspectJ采用编译期织入和类装载期织入。 - Proxy(代理):
一个类被AOP织入增强后,就产生一个结果代理类。 - Aspect(切面):
是切入点和通知(引介)的结合
4.1.3 学习spring中的AOP要明确的事
- a、开发阶段
编写核心业务代码(开发主线):大部分程序员来做,要求熟悉业务需求。
把公用代码抽取出来,制作成通知。(开发阶段最后再做):AOP编程人员来做。
在配置文件中,声明切入点与通知间的关系,即切面。:AOP编程人员来做。 - b、运行阶段(Spring框架完成的)
Spring框架监控切入点方法的执行。一旦监控到切入点方法被运行,使用代理机制,动态创建目标对象的代理对象,根据通知类别,在代理对象的对应位置,将通知对应的功能织入,完成完整的代码逻辑运行。
5.基于XML的AOP配置
5.1环境搭建
以上述案例进行aop的配置
1.导入依赖
<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>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>commons-dbutils</groupId>
<artifactId>commons-dbutils</artifactId>
<version>1.4</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>
2.创建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:aop="http://www.springframework.org/schema/aop"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
</beans>
3.配置spring的ioc
<!-- 配置springIoc控制反转-依赖注入-->
<!-- 配置service-->
<bean id="accountService" class="com.zua.service.impl.AccountServiceImpl">
<!-- 注入dao-->
<property name="accountDao" ref="accountDao"></property>
<!-- 注入txManager-->
<property name="txManager" ref="txManager"></property>
</bean>
<!-- 配置accountDao-->
<bean id="accountDao" class="com.zua.dao.impl.AccountDaoImpl">
<!-- 注入QueryRunner-->
<property name="queryRunner" ref="QueryRunner"></property>
<!-- 注入ConnectionUtils-->
<property name="connectionUtils" ref="threadConn"></property>
</bean>
<!-- 配置QueryRunner-->
<bean id="QueryRunner" class="org.apache.commons.dbutils.QueryRunner"></bean>
<!-- 配置数据源-->
<bean id="datasource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<!-- 连接数据库的必备信息-->
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/mybatisdb"></property>
<property name="user" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!--配置连接工具类-->
<bean id="threadConn" class="com.zua.utils.ConnectionUtils">
<!-- 注入数据源-->
<property name="dataSource" ref="datasource"></property>
</bean>
4.抽取公共代码制作成通知
即上述的事务管理类(TransactionManager)
4.1 把通知类用bean标签配置起来
<!--配置事务管理类-->
<bean id="txManager" class="com.zua.utils.TransactionManager">
<!-- 注入连接-->
<property name="connectionUtils" ref="threadConn"></property>
</bean>
5.使用aop:config声明aop配置
aop:config: 作用:用于声明开始aop的配置
<!-- 配置spring_aop-->
<aop:config>
</aop:config>
6.使用aop:aspect配置切面
aop:aspect: 作用: 用于配置切面。
属性:
id:给切面提供一个唯一标识。
ref:引用配置好的通知类bean的id。
<aop:aspect id="txAdvice" ref="txManager">
<!--配置通知的类型要写在此处-->
</aop:aspect>
7.使用aop:pointcut配置切入点表达式
<!--配置切入点表达式-->
<aop:pointcut id="tx1" expression="execution(* com.zua.service.impl.*.*(..))"/>
8.:使用aop:xxx配置对应的通知类型
<!--配置前置通知,开启事务-->
<aop:before method="beginTransaction" pointcut-ref="tx1"></aop:before>
<!--配置后置通知,提交事务-->
<aop:after-returning method="commit" pointcut-ref="tx1"></aop:after-returning>
<!--配置异常通知,回滚事务-->
<aop:after-throwing method="rollback" pointcut-ref="tx1"></aop:after-throwing>
<!--配置最终通知,释放连接-->
<aop:after method="release" pointcut-ref="tx1"></aop:after>
5.2 切入点表达式
aop:pointcut:
作用: 用于配置切入点表达式。就是指定对哪些类的哪些方法进行增强。
属性:
expression:用于定义切入点表达式。
id:用于给切入点表达式提供一个唯一标识
execution:匹配方法的执行(常用)
execution(表达式)
表达式语法:execution([修饰符] 返回值类型 包名.类名.方法名(参数)) 写法说明:
全匹配方式:
public voidcom.itheima.service.impl.AccountServiceImpl.saveAccount(com.itheima.domain.Account)
访问修饰符可以省略
void com.itheima.service.impl.AccountServiceImpl.saveAccount(com.itheima.domain.Account)
返回值可以使用*号,表示任意返回值
* com.itheima.service.impl.AccountServiceImpl.saveAccount(com.itheima.domain.Account)
使用..来表示当前包,及其子包
* com..AccountServiceImpl.saveAccount(com.itheima.domain.Account)
类名可以使用*号,表示任意类
* * com..*.saveAccount(com.itheima.domain.Account)
* 方法名可以使用*号,表示任意方法
* * com..*.*( com.itheima.domain.Account)
参数列表可以使用*,表示参数可以是任意数据类型,但是必须有参数
* com..*.*(*)
参数列表可以使用..表示有无参数均可,有参数可以是任意类型
* com..*.*(..)
全通配方式:
* *..*.*(..)
通常情况下,我们都是对业务层的方法进行增强,所以切入点表达式都是切到业务层实现类。 execution( com.itheima.service.impl..(…))*
5.3 通知类型
5.3.1 前置通知
aop:before 作用: 用于配置前置通知。指定增强的方法在切入点方法之前执行
属性:
method: 用于指定通知类中的增强方法名称
ponitcut-ref:用于指定切入点的表达式的引用
poinitcut:用于指定切入点表达式
执行时间点:
切入点方法执行之前执行
<aop:before method="beginTransaction" pointcut-ref="pt1"/>
5.3.2 后置通知
aop:after-returning 作用: 用于配置后置通知 指定增强的方法在切入点方法之后执行
属性:
method: 用于指定通知类中的增强方法名称
ponitcut-ref:用于指定切入点的表达式的引用
poinitcut:用于指定切入点表达式
执行时间点:
切入点方法正常执行之后。它和异常通知只能有一个执行
<aop:after-returning method="commit" pointcut-ref="pt1"/>
5.3.3 异常通知
aop:after-throwing 作用: 用于配置异常通知
属性:
method: 用于指定通知类中的增强方法名称
ponitcut-ref:用于指定切入点的表达式的引用
poinitcut:用于指定切入点表达式
执行时间点:
切入点方法执行产生异常后执行。它和后置通知只能执行一个
<aop:after-throwing method="rollback" pointcut-ref="pt1"/>
5.3.4 最终通知
aop:after 作用: 用于配置最终通知
属性:
method: 用于指定通知类中的增强方法名称
ponitcut-ref:用于指定切入点的表达式的引用
poinitcut:用于指定切入点表达式
执行时间点:
无论切入点方法执行时是否有异常,它都会在其后面执行。
<aop:after method="release" pointcut-ref="pt1"/>