如果对此文感兴趣,可以继续看下一篇博文,持续更新,新手学习,有问题欢迎指正:
https://blog.csdn.net/renjingjingya0429/article/details/90215902
一、AOP的相关概念
1.1 AOP概述
1.1.1 什么是AOP?
AOP:全称是Aspect Oriented Programming 即:面向切面编程。
在软件业,AOP通过预编译的方式和运行期动态代理实现程序功能的统一维护的一种技术。AOP是OOP的延续,是软件开发中的一个热点,也是Spring框架的一个重要内容,是函数式编程的一种衍生泛型。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率。
简单地说,它就是把我们程序重复的代码抽取出来,在需要执行的时候,使用动态代理的技术,在不修改源码的基础上,对我们已有方法进行增强。
1.2 AOP的作用及优势
- 作用:在程序运行期间,不修改源码对已有方法进行增强。
- 优势:
- 减少重复代码
- 提高开发效率
- 维护方便
1.3 AOP的实现方式
使用动态代理技术
2. AOP的具体应用
2.1 一些问题
我们在业务层中实现事务控制的时候,业务层的方法中存在着很多的重复代码。并且业务层方法和事务控制方法中耦合了。我们可以使用下面的知识来解决这些问题。
2.2 动态代理回顾
2.2.1 动态代理的特点
字节码随用随创建,随用随加载。
他与静态代理的区别也在于此。因为静态代理是一上来字节码就创建好,并加载完成。
2.2.2 动态代理常用的两种方式
- 基于接口的动态代理
- 提供者:JDK官方的Proxy类。
- 要求:被代理类最少实现一个接口。
- 基于子类的动态代理
- 提供者:第三方的CGLib,如果报asmxxxx异常,需要导入asm.jar。
- 要求:被代理类不能用final修饰的类。
2.2.3 使用JDK官方的Proxy 类创建代理对象
/**
* 一个经纪公司的要求:
* 能做基本的表演和危险的表演
*/
public interface IActor {
/**
* 基本的演出
*
*/
public void basicAct(float money);
/**
* 危险演出
*/
public void dangerAct(float money);
}
public class Actor implements IActor {
/**
* 基本演出
* @param money
*/
@Override
public void basicAct(float money) {
System.out.println("拿到钱,开始基本的表演:"+money);
}
/**
* 危险演出
* @param money
*/
@Override
public void dangerAct(float money) {
System.out.println("拿到钱,开始危险的表演:"+money);
}
}
public class Client {
public static void main(String[] args) {
//一个剧组找演员
Actor actor = new Actor();//直接
/**
* 代理:间接。
* 获取代理对象:
* 要求:被代理类最少实现一个接口。
* 创建的方式:Proxy.newProxyInstance(三个参数)
* 参数含义:
* ClassLoader:和被代理对象使用相同的类加载器。
* Interfaces:和被代理对象具有相同的行为。实现相同的接口。
* InvocationHandler:如何代理。
* 策略模式:使用场景是:
* 数据有了,目的明确。
* 达成目标的过程,就是策略。
*/
IActor proxyActor = (IActor) Proxy.newProxyInstance(actor.getClass().getClassLoader(), actor.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
/**
* 执行被代理对象的任何方法,都会经过该方法。
* 此方法有拦截的功能。
* 参数:
* proxy:代理对象的引用。不一定每次都用得到。
* method:当前执行的方法对象。
* args:执行方法所需的参数。
* 返回值:
* 当前执行方法的返回值。
*/
String name = method.getName();
Float money = (Float)args[0];
Object rtValue = null;
//每个经纪公司对不同演出收费不一样,此处开始判断
if ("basicAct".equals(name)) {
//基本演出
if (money > 2000) {
//看上去剧组是给了 8000,实际到演员手里只有 4000
//这就是我们没有修改原来 basicAct 方法源码,对方法进行了增强
rtValue = method.invoke(actor, money/2);
}
}
if ("dangerAct".equals(name)) {
//基本演出
if (money > 5000) {
//看上去898剧组是给了 8000,实际到演员手里只有 4000
//这就是我们没有修改原来 basicAct 方法源码,对方法进行了增强
rtValue = method.invoke(actor, money/2);
}
}
return rtValue;
}
});
//没有经济公司的时候,直接找演员。
actor.basicAct(100f);
actor.dangerAct(500f);
//剧组无法直接联系演员,而是由经纪公司找的演员
proxyActor.basicAct(8000f);
proxyActor.dangerAct(50000f);
}
}
2.2.3 使用CGLib的Enhancer类创建代理对象
public class Actor {
/**
* 基本演出
* @param money
*/
public void basicAct(float money) {
System.out.println("CGLIB拿到钱,开始基本的表演:"+money);
}
/**
* 危险演出
* @param money
*/
public void dangerAct(float money) {
System.out.println("CGLIB拿到钱,开始危险的表演:"+money);
}
}
public class Client {
public static void main(String[] args) {
//一个剧组找演员
final Actor actor = new Actor();//直接(注意在匿名内部类中只能引用final类型的外部变量)
/**
* 基于子类的动态代理
* 要求:被代理的对象不能是最终类。
* 用到的类:Enhancer
* 用到的方法:create(Class,Callback)
* 方法的参数:
* Class:被代理对象的字节码。
* Callback:如何代理。
*/
Actor cglibActor = (Actor) Enhancer.create(actor.getClass(), new MethodInterceptor() {
/**
* 执行被代理对象的任何方法,都会经过该方法。在此方法内部就可以对被代理对象的任何方法进行增强。
*
* 参数:
* 前三个和基于接口的动态代理是一样的。
* MethodProxy:当前执行方法的代理对象。
* 返回值:当前执行方法的返回值。
*/
@Override
public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
String name = method.getName();
Float money = (Float) args[0];
Object rtValue = null;
//每个经纪公司对不同演出收费不一样,此处开始判断
if ("basicAct".equals(name)) {
//基本演出
if (money > 2000) {
//看上去剧组是给了 8000,实际到演员手里只有 4000
//这就是我们没有修改原来 basicAct 方法源码,对方法进行了增强
rtValue = method.invoke(actor, money / 2);
}
}
if ("dangerAct".equals(name)) {
//基本演出
if (money > 5000) {
//看上去898剧组是给了 8000,实际到演员手里只有 4000
//这就是我们没有修改原来 basicAct 方法源码,对方法进行了增强
rtValue = method.invoke(actor, money / 2);
}
}
return rtValue;
}
});**加粗样式**
cglibActor.basicAct(10000);
cglibActor.dangerAct(100000);
}
}
二、Spring中的AOP
1. Spring中AOP的细节
1.1 AOP相关术语
- JoinPoint(连接点):所谓连接点是指那些被拦截到的点。在Spring中,这些点指的是方法,因为Spring只支持方法类型的连接点。
- PointCut(切入点):是指我们要对哪些JoinPoint 进行拦截的定义。
- Advice(通知/增强):所谓通知是指拦截到JoinPoint之后所要做的事情就是通知(增强的方法抽取而形成的类)。
通知的类型:前置通知、后置通知、异常通知、最终通知、环绕通知。 - Introduction(引介):引介是一种特殊的通知在不修改类代码的前提下,Introduction可以在运行期为类动态的添加一些方法或者Field。
- Target(目标对象):代理的目标对象(被代理对象)。
- Weaving(织入):是指把增强应用到目标对象来创建新的代理对象的过程。
Spring采用动态代理织入,而AspectJ采用编译器织入和类装载期织入。 - Proxy(代理):一个类被AOP织入增强后,就产生一个结果代理类。
- Aspect(切面):是切入点和通知(引介)的结合。
1.2 学习Spring中AOP要明确的事
-
开发阶段(我们做的)
- 编写业务核心代码(开发主线):大部分程序员来做,要求熟悉业务需求。
- 把公用代码抽取出来,制作成通知。(开发阶段最后在做):AOP编程人员来做。
- 在配置文件中,声明切入点与通知间的关系,即切面:AOP编程人员来做。
-
运行阶段(Spring框架完成的)
Spring框架监控切入点方法的执行。一旦监控到切入点方法被执行,使用代理机制,动态创建目标对象的代理对象,根据通知类别,在代理对象的对应位置,将通知对应的功能织入,完成完整的代码逻辑运行。
1.3 关于代理的选择
在Spring中,框架会根据目标类是否实现了接口来决定采用哪种动态代理的方式。
2. 基于XML的AOP配置
2.1 导入需要的jar包。
2.2 在src下创建如下结构的目录。
2.3 核心代码展示。
/**
* 模拟业务层的实现类
*/
public class CustomerServiceImpl implements ICustomerService {
@Override
public void saveCustomer() {
System.out.println("保存了客户");
// int i = 1/0;//用于模拟异常
}
@Override
public void updateCustomer(int i) {
System.out.println("更新了客户");
}
@Override
public int deleteCustomer() {
System.out.println("删除了客户");
return 0;
}
}
/**
* main方法
*/
public class client {
public static void main(String[] args) {
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
ICustomerService cs = (ICustomerService) ac.getBean("customerService");
cs.saveCustomer();
}
}
/**
* 一个用于记录日志的类
*/
public class Logger {
/**
* 记录日志的操作
* 计划让其在业务核心方法(切入点方法)执行之前执行
*/
/**
* 前置通知
*/
public void beforePrintLog(){
System.out.println("记录日志beforePrintLog");
}
/**
* 后置通知
*/
public void afterReturningPrintLog(){
System.out.println("记录日志afterReturningPrintLog");
}
/**
* 异常通知
*/
public void afterThrowingPrintLog(){
System.out.println("记录日志afterThrowingPrintLog");
}
/**
* 最终通知
*/
public void afterPrintLog(){
System.out.println("记录日志afterPrintLog");
}
/**
* 环绕通知
* 问题:
* 当我们配置了环绕通知之后,切入点方法没有执行,而环绕通知里的代码执行了。
* 分析:
* 由动态代理可知,环绕通知指的是invoke方法,并且里面有明确的方法调用。
* 而我么现在的环绕通知没有明确的切入点方法调用。
* 解决:
* Spring为我们提供了一个接口:ProceedingJoinPoint。该接口可以作为环绕通知的方法参数来使用。
* 在程序运行时,Spring框架会为我们提供该接口的实现类,供我们使用。
* 该接口中有一个方法,proceed(),它的作用就等同于method.invoke方法,就是明确调用业务层核心方法。
*
* 环绕通知:他是Spring框架为我们提供的一种可以在代码中手动控制通知方法什么时候执行的方式。
*/
public Object aroundPrintlog(ProceedingJoinPoint point) {
Object rtValue = null;
try {
System.out.println("记录日志aroundPrintlog---前置");
rtValue = point.proceed();
System.out.println("记录日志aroundPrintlog---后置");
} catch (Throwable throwable) {
System.out.println("记录日志aroundPrintlog---异常");
throwable.printStackTrace();
}finally {
System.out.println("记录日志aroundPrintlog---最终");
}
return rtValue;
}
}
2.4 配置步骤。
①第一步:把通知类用bean标签配置起来。
<!--配置Service-->
<bean id="customerService" class="com.renjing.service.impl.CustomerServiceImpl"></bean>
② 第二步:使用aop:config声明aop配置。
aop:config:用于声明开始aop的配置。
<aop:config>
<!-- 配置的代码都写在此处 -->
</aop:config>
③ 第三步:使用aop:aspect配置切面
aop:aspect:
- 作用:用于配置切面。
- 属性:
- id:给切面提供一个唯一标识。
- ref:引用配置好的通知类bean的id。
<aop:aspect id="Advice" ref="customerService">
<!--配置通知的类型要写在此处-->
</aop:aspect>
④ 第四步:使用aop:aspect配置切入点表达式。
aop:pointcut:
- 作用:用于配置切入点表达式。就是指定对哪些类的哪些方法进行增强。
- 属性:
- expression:用于定义切入点表达式。
- id:用于给切入点表达式提供一个唯一标识。
<aop:pointcut id="pt1" expression="execution(* com.renjing.service.impl..*.*(..))"></aop:pointcut>
⑤ 使用aop:xxx配置对应的通知类型
aop:before
- 作用:用于配置前置通知。
- 属性:
- method:用于指定通知类中的增强方法名称。
- point:用于指定切入点表达式。
- pointcut-ref:用于指定切入表达式的引用。
- 执行时间点:切入点方法执行之前执行。
<aop:before method="beforePrintLog" pointcut-ref="pt1"></aop:before>
aop:after-returning
- 作用:用于配置后置通知。
- 属性:
- method:用于指定通知类中的增强方法名称。
- point:用于指定切入点表达式。
- pointcut-ref:用于指定切入表达式的引用。
- 执行时间点:切入点方法正常执行之后执行。它和异常通知只能有一个执行。
<aop:after-returning method="afterReturningPrintLog" pointcut-ref="pt1"></aop:after-returning>
aop:after-throwing
- 作用:用于配置异常通知。
- 属性:
- method:用于指定通知类中的增强方法名称。
- point:用于指定切入点表达式。
- pointcut-ref:用于指定切入表达式的引用。
- 执行时间点:切入点方法产生异常后执行。它和后置通知只能有一个执行。
<aop:after-throwing method="afterThrowingPrintLog" pointcut-ref="pt1"></aop:after-throwing>
aop:after
- 作用:用于配置最终通知。
- 属性:
- method:用于指定通知类中的增强方法名称。
- point:用于指定切入点表达式。
- pointcut-ref:用于指定切入表达式的引用。
- 执行时间点:无论切入点方法执行是否有异常,它都会在其后面执行。
<aop:after method="afterPrintLog" pointcut-ref="pt1"></aop:after>
-->
2.5 切入点表达式说明。
切入点表达式:
关键字:execution(表达式)
表达式写法:
访问修饰符 返回值 包名.包名...类名.方法名(参数列表)
全匹配方式:
public void com.renjing.service.impl.CustomerServiceImpl.saveCustomer()
访问修饰符可以省略:
void com.renjing.service.impl.CustomerServiceImpl.saveCustomer()
返回值可以使用通配符:
* com.renjing.service.impl.CustomerServiceImpl.saveCustomer()
包名可以使用通配符,表示任意包。但是,有几个包就写几个*:
* *.*.*.*.CustomerServiceImpl.saveCustomer()
包名可以使用..表示当前包及其子包:
* com..CustomerServiceImpl.saveCustomer()
类名和方法名都可以使用通配符:
* com..*.*()
参数列表可以使用具体类型,来表示参数类型:
基本类型直接写类型名称:int
引用类型必须是包名.类名。java.lang.Integer
参数列表可以使用通配符,表示任意参数类型,但是必须有参数
* com..*.*(*)
参数列表可以使用..表示有无参数均可,有参数可以是任意类型。
* com..*.*(..)
全通配方式:
* *..*.*(..)
实际开发中,我们一般情况下,都是对业务层方法进行增强:
写法:* com.renjing.service.impl.*.*(..)
2.6 环绕通知。
配置方式:
<aop:config>
<!--定义通用的切入点表达式,如果写在aop:aspect标签外部的前面(必须写在前面,否则报错),则表示所有切面可用,-->
<aop:pointcut id="pt1" expression="execution(* com.renjing.service.impl..*.*(..))"></aop:pointcut>
<!--配置切面-->
<aop:aspect id="logAdvice" ref="logger">
<!--配置环绕通知-->
<aop:around method="aroundPrintlog" pointcut-ref="pt1"></aop:around>
</aop:aspect>
</aop:config>
aop:around:
- 作用:用于配置环绕通知。
- 属性:
- method:用于指定通知类中的增强方法名称。
- point:用于指定切入点表达式。
- pointcut-ref:用于指定切入表达式的引用。
- 说明:它是Spring框架为我们提供的一种可以在代码中手动控制增强代码什么时候执行的方式。
- 注意:通常情况下,环绕通知都是独立使用的。
/**
* 环绕通知
*/
public Object aroundPrintlog(ProceedingJoinPoint point) {
Object rtValue = null;
try {
System.out.println("记录日志aroundPrintlog---前置");
rtValue = point.proceed();
System.out.println("记录日志aroundPrintlog---后置");
} catch (Throwable throwable) {
System.out.println("记录日志aroundPrintlog---异常");
throwable.printStackTrace();
}finally {
System.out.println("记录日志aroundPrintlog---最终");
}
return rtValue;
}
3. 基于注解的AOP配置
3.1环境搭建
(1)导入需要的jar包。
(2)在配置文件中导入context的名称空间。
(3)把资源使用注解配置
/**
* 模拟业务层的实现类
*/
@Service("customerService")
public class CustomerServiceImpl implements ICustomerService {
@Override
public void saveCustomer() {
System.out.println("保存了客户");
// int i = 1/0;
}
@Override
public void updateCustomer(int i) {
System.out.println("更新了客户");
}
@Override
public int deleteCustomer() {
System.out.println("删除了客户");
return 0;
}
}
(4)第四步:在配置文件中指定Spring要扫描的包
<!--初始化Spring容器时要扫描的包-->
<context:component-scan base-package="com.renjing"></context:component-scan>
3.2 配置步骤
(1)把通知类也使用注解配置
(2)在通知类上使用@Aspect 注解声明为切面
(3)在增强的方法上使用注解配置通知
@Before
- 作用:
把当前方法看成是前置通知。 - 属性:
value:用于指定切入点表达式,还可以指定切入点表达式的引用。
@AfterReturning
- 作用:
把当前方法看成是后置通知。 - 属性:
value:用于指定切入点表达式,还可以指定切入点表达式的引用
@AfterThrowing
- 作用:
把当前方法看成是异常通知。 - 属性:
value:用于指定切入点表达式,还可以指定切入点表达式的引用。
@After
- 作用:
把当前方法看成是最终通知。 - 属性:
value:用于指定切入点表达式,还可以指定切入点表达式的引用
@Around
- 作用:
把当前方法看成是环绕通知。 - 属性:
value:用于指定切入点表达式,还可以指定切入点表达式的引用。
/**
* 一个用于记录日志的类
*/
@Component("logger")//放入Spring容器(1)
@Aspect//配置切面(2)
public class Logger {
/**
* 记录日志的操作
* 计划让其在业务核心方法(切入点方法)执行之前执行
*/
/**
* 切入点表达式
*/
@Pointcut("execution(* com.renjing.service.impl.*.*(..))")
public void pt1(){
}
/**
* 前置通知
*/
// @Before("pt1()")
public void beforePrintLog(){
System.out.println("记录日志beforePrintLog---前置");
}
/**
* 后置通知
*/
// @AfterReturning("pt1()")
public void afterReturningPrintLog(){
System.out.println("记录日志afterReturningPrintLog---后置");
}
/**
* 异常通知
*/
// @AfterThrowing("pt1()")
public void afterThrowingPrintLog(){
System.out.println("记录日志afterThrowingPrintLog---异常");
}
/**
* 最终通知
*/
// @After("pt1()")
public void afterPrintLog(){
System.out.println("记录日志afterPrintLog---最终");
}
/**
* 环绕通知
* 问题:
* 当我们配置了环绕通知之后,切入点方法没有执行,而环绕通知里的代码执行了。
* 分析:
* 由动态代理可知,环绕通知指的是invoke方法,并且里面有明确的方法调用。
* 而我么现在的环绕通知没有明确的切入点方法调用。
* 解决:
* Spring为我们提供了一个接口:ProceedingJoinPoint。该接口可以作为环绕通知的方法参数来使用。
* 在程序运行时,Spring框架会为我们提供该接口的实现类,供我们使用。
* 该接口中有一个方法,proceed(),它的作用就等同于method.invoke方法,就是明确调用业务层核心方法。
*
* 环绕通知:他是Spring框架为我们提供的一种可以在代码中手动控制通知方法什么时候执行的方式。
*/
@Around("pt1()")
public Object aroundPrintlog(ProceedingJoinPoint point) {
Object rtValue = null;
try {
System.out.println("记录日志aroundPrintlog---前置");
rtValue = point.proceed();
System.out.println("记录日志aroundPrintlog---后置");
} catch (Throwable throwable) {
System.out.println("记录日志aroundPrintlog---异常");
throwable.printStackTrace();
}finally {
System.out.println("记录日志aroundPrintlog---最终");
}
return rtValue;
}
}
补充:切入点表达式注解
@Pointcut
- 作用:
指定切入点表达式 - 属性:
value:指定表达式的内容
(4)在 spring 配置文件中开启 spring 对注解 AOP 的支持
<?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">
<!--初始化Spring容器时要扫描的包-->
<context:component-scan base-package="com.renjing"></context:component-scan>
<!--开启Spring对注解AOP的支持-->
<aop:aspectj-autoproxy/>
</beans>
- 不使用 XML 的配置方式
@Configuration//让当前类变成一个配置类
@ComponentScan("com.renjing")//初始化Spring容器时要扫描的包
@EnableAspectJAutoProxy//开启Spring对注解aop的支持
public class SpringConfiguration {
}