面向切面:AOP

一、代理模式

概述

​ 代理模式是一种结构型设计模式,它使得代理对象可以代表另一个对象进行访问。它的作用就是通过提供一个代理类,让我们在调用目标方法的时候,不再是直接对目标方法进行调用,而是通过代理类间接调用。让不属于目标方法核心逻辑的代码从目标方法中剥离出来——解耦。调用目标方法时先调用代理对象的方法,减少对目标方法的调用和打扰,同时让附加功能能够集中在一起也有利于统一维护。
在这里插入图片描述

  • 代理:将非核心逻辑剥离出来以后,封装这些非核心逻辑的类、对象、方法
  • 目标:被代理“套用”了非核心逻辑代码的类、对象、方法。

1.1、静态代理

在静态代理中,代理类是在编译时期创建的,代理类和委托类实现相同的接口或继承相同的类,并在代理类中实现委托类中的方法,在调用委托类的方法之前或之后执行一些附加操作

public class CalculatorStaticProxy implements Calculator {
    
    // 将被代理的目标对象声明为成员变量
    private Calculator target;
    public CalculatorStaticProxy(Calculator target) {
        this.target = target;
    }
    
    @Override
    public int add(int i, int j) {
    
        // 附加功能由代理类中的代理方法来实现
        System.out.println("[日志] add 方法开始了,参数是:" + i + "," + j);
    
        // 通过目标对象来实现核心业务逻辑
        int addResult = target.add(i, j);
    
        System.out.println("[日志] add 方法结束了,结果是:" + addResult);
    
        return addResult;
    }
}

说明:

静态代理确实实现了解耦,但是由于代码都写死了,完全不具备任何的灵活性

1.2、动态代理

  1. 定义
    ​ 在动态代理中,代理类是在运行时期动态创建的。它不需要事先知道委托类的接口或实现类,而是在运行时期通过 Java 反射机制动态生成代理类

    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    
    interface Human{
        String getBelief();
        void Object(String food);
    }
    
    //被代理类
    class SuperMan implements Human{
        @Override
        public String getBelief() {
            return "The only planet in the solar system without a magnetic field.";
        }
        @Override
        public void Object(String food) {
            System.out.println("周围有很多" + food);
        }
    }
    
    /**
     * 要想实现动态代理,需要解决的问题?
     * 问题一:如何根据加载到内存中的被代理类,动态的创建一个代理类及其对象。
     * 问题二:当通过代理类的对象调用方法a时,如何动态的去调用被代理类中的同名方法a。
     */
    class ProxyFactory{
        //调用此方法,返回一个代理类的对象。解决问题一
        public static Object getProxyInstance(Object obj){//obj:被代理类的对象
            MyInvocationHandler hander = new MyInvocationHandler();
            hander.bind(obj);
            return Proxy.newProxyInstance(obj.getClass().getClassLoader(),obj.getClass().getInterfaces(),hander);
        }
    }
    
    class MyInvocationHandler implements InvocationHandler{
    
        private Object obj;//需要使用被代理类的对象进行赋值
    
        public void bind(Object obj){
            this.obj = obj;
        }
    
        //当我们通过代理类的对象,调用方法a时,就会自动的调用如下的方法:invoke()
        //将被代理类要执行的方法a的功能就声明在invoke()中
        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    
            //method:即为代理类对象调用的方法,此方法也就作为了被代理类对象要调用的方法
            //obj:被代理类的对象
            Object returnValue = method.invoke(obj,args);
            //上述方法的返回值就作为当前类中的invoke()的返回值。
            return returnValue;
        }
    }
    
    public class ProductTest {
        public static void main(String[] args) {
            SuperMan superMan = new SuperMan();
            //proxyInstance:代理类的对象
            Human proxyInstance = (Human) ProxyFactory.getProxyInstance(superMan);
            //当通过代理类对象调用方法时,会自动的调用被代理类中同名的方法
            String belief = proxyInstance.getBelief();
            System.out.println(belief);
            proxyInstance.Object("四川大巴山");
    
            System.out.println("+++++++++++++++++++");
    
            NeckTest fox = new NeckTest();
            ClothFactory proxyClothFactory = (ClothFactory) ProxyFactory.getProxyInstance(fox);
            proxyClothFactory.produceCloth();
        }
    }
    
    
  2. 分类
    动态代理分类

    • 基于接口的代理(有接口情况)
    • 基于类的代理(无接口情况)

在这里插入图片描述

说明:

AspectJ:是AOP思想的一种实现。本质上是静态代理,将代理逻辑“织入”被代理的目标类编译得到的字节码文件,所以最终效果是动态的。weaver就是织入器。Spring只是借用了AspectJ中的注解。

在这里插入图片描述

说明:

  • 当动态代理是基于接口的代理情况时,要求代理对象和目标对象实现同样的接口。
  • 当动态代理是基于类的代理情况时,通过继承被代理的目标类实现代理。

补充:

  • JDK动态代理动态生成的代理类会在com.sun.proxy包下,类名为$proxy1,和目标类实现相同的接口
  • cglib动态代理动态生成的代理类会和目标在在相同的包下,会继承目标类

1.3、基本用例-实现动态代理

public class ProxyFactory {

    private Object target;

    public ProxyFactory(Object target) {
        this.target = target;
    }

    public Object getProxy(){
        /**
         * newProxyInstance():创建一个代理实例
         * 其中有三个参数:
         * 1、classLoader:加载动态生成的代理类的类加载器
         * 2、interfaces:目标对象实现的所有接口的class对象所组成的数组
         * 3、invocationHandler:设置代理对象实现目标对象方法的过程,即代理类中如何重写接口中的抽象方法
         */
        ClassLoader classLoader = target.getClass().getClassLoader();
        Class<?>[] interfaces = target.getClass().getInterfaces();
        InvocationHandler invocationHandler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                /**
                 * proxy:代理对象
                 * method:代理对象需要实现的方法,即其中需要重写的方法
                 * args:method所对应方法的参数
                 */
                Object result = null;
                try {
                    System.out.println("[动态代理][日志] "+method.getName()+",参数:"+ Arrays.toString(args));
                    result = method.invoke(target, args);
                    System.out.println("[动态代理][日志] "+method.getName()+",结果:"+ result);
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("[动态代理][日志] "+method.getName()+",异常:"+e.getMessage());
                } finally {
                    System.out.println("[动态代理][日志] "+method.getName()+",方法执行完毕");
                }
                return result;
            }
        };

        return Proxy.newProxyInstance(classLoader, interfaces, invocationHandler);
    }
}


@Test
public void testDynamicProxy(){
    ProxyFactory factory = new ProxyFactory(new CalculatorLogImpl());
    Calculator proxy = (Calculator) factory.getProxy();
    proxy.div(1,0);
}

说明:

  • 动态代理需要使用Proxy.newProxyInstance()方法
  • 需要设置代理对象实现目标对象的方法过程

二、概述

​ AOP(Aspect Oriented Programming)是一种设计思想,是软件设计领域中的面向切面编程,它是面向对象编程的一种补充和完善,它以通过预编译方式和运行期动态代理方式实现,在不修改源代码的情况下,给程序动态统一添加额外功能的一种技术。利用AOP可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度降低,提高程序的可重用性,同时提高了开发的效率

作用

  1. 代码重用和模块化:AOP可以将一些通用的行为(例如日志记录、安全控制、事务管理等)抽象出来,形成可重用的模块,避免在每个业务逻辑中都重复编写这些代码。

  2. 分离关注点:AOP将不同的关注点分离开来,使得各个模块间职责更加清晰明确,代码的可读性和可维护性也更强。

  3. 简化开发:AOP可以帮助开发人员将关注点从业务逻辑中分离出来,使得开发更加简单明了。

  4. 提高系统的可扩展性:在系统需求变化时,只需要修改AOP模块而不是修改业务逻辑,这可以使得系统更加易于扩展和维护。

  5. 降低代码耦合度:AOP的作用是将不同的关注点分离开来,这可以避免代码之间的紧耦合,提高代码的可复用性和可维护性。

横切关注点

​ 在 AOP 中,横切关注点指的是在应用程序中影响多个类或对象的横切性质的行为,比如日志记录、性能监控、事务处理等等。这些行为可能分散在整个应用程序中的不同类和方法中,而不是与应用程序的核心业务逻辑紧密相关。

​ 使用 AOP 技术,可以将这些横切关注点从应用程序的核心业务逻辑中分离出来,并将它们模块化为可重用的模块,从而实现更好的代码结构和更好的可维护性。
在这里插入图片描述

通知(增强)

​ 通知(advice)也被称为增强(advice),是指在 AOP 中定义的一种特殊类型的方法,它包含要在连接点(join point)执行的一些行为。通知的目的是在不修改目标对象的情况下,将增强(如日志、事务管理等)应用于应用程序的特定方法或切入点。

简单来说:通知就是你想要增强的功能,比如 安全,事务,日志等

每一个横切关注点上要做的事情都需要写一个方法来实现,这样的方法就叫通知方法。
通知分类:

  1. 前置通知:在被代理的目标方法执行
  2. 返回通知:在被代理的目标方法成功结束后执行(寿终正寝
  3. 异常通知:在被代理的目标方法异常结束后执行(死于非命
  4. 后置通知:在被代理的目标方法最终结束后执行(盖棺定论
  5. 环绕通知:使用try…catch…finally结构围绕整个被代理的目标方法,包括上面四种通知对应的所有位置

在这里插入图片描述

切面

​切面是对横切关注点和通知的封装,它包含了一组切点和通知,用于描述在何处、何时、以及如何执行横切逻辑。切面可以在不修改原代码的情况下,对原有的代码进行功能的增强或改变。通常,切面是以一个类的形式存在的,它包含了一个或多个通知和一个或多个切点。

简单来说:切面就是封装通知方法的类

在这里插入图片描述

目标

​被代理的目标对象

代理

代理(Proxy)是一种设计模式,用于控制对目标对象的访问,并在访问过程中插入额外的逻辑。简单点说,代理就是向目标对象应用通知之后创建的代理对象

连接点

​ 在 AOP 中,连接点(Join Point)表示在程序执行过程中能够插入一个切面的点,例如方法调用、异常处理、字段访问等。连接点定义了在程序中的哪个位置可以应用切面。切面可以在连接点前后增加额外的处理逻辑,从而影响程序的行为。通俗地讲,连接点就是在程序执行中可以被拦截的地方

在这里插入图片描述

说明: 把方法排成一排,每一个横切位置看成x轴方向,把方法从上到下执行的顺序看成y轴,x轴和y轴的交叉点就是连接点。通俗说,就是spring允许你使用通知的地方

切入点

定位连接点的方式。

每个类的方法中都包含多个连接点,所以连接点是类中客观存在的事物(从逻辑上来说)。

如果把连接点看作数据库中的记录,那么切入点就是查询记录的 SQL 语句。

Spring 的 AOP 技术可以通过切入点定位到特定的连接点。通俗说,要实际去增强的方法

切点通过 org.springframework.aop.Pointcut 接口进行描述,它使用类和方法作为连接点的查询条件。

三、切入点表达式

在 AOP 中,切入点表达式指定了哪些方法需要被织入增强逻辑。它是一个表达式,用于匹配目标对象中的方法,并提供切入点的精确定义
在这里插入图片描述
都是增强方法

四、基于注解的AOP

基于注解的AOP是一种AOP的实现方式,它通过在Java类、方法、参数等上添加注解的方式来实现切面的定义和应用,相比于传统的XML配置方式更加便捷和灵活

4.1、基本用例-注解实现AOP

步骤一:导入依赖

 <!--spring aop依赖-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aop</artifactId>
        <version>6.0.2</version>
    </dependency>
    <!--spring aspects依赖-->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-aspects</artifactId>
        <version>6.0.2</version>
    </dependency>

步骤二:创建接口以及实现类

1.接口

public interface Calculator {
    int add(int i, int j); 
}

2.实现类

@Component//添加@Component注解,便于Spring容器进行管理
public class CalculatorImpl implements Calculator {

    @Override
    public int add(int i, int j) {
        int result = i + j;
        System.out.println("方法内部 result = " + result);
        return result;
    }
}

步骤三:创建切面类

@Aspect//表示这个类是一个切面类
@Component//保证这个切面类能够放入IOC容器
public class LogAspect {

}

步骤四:配置Spring配置文件

基于注解的AOP的实现:

  1. 将目标对象和切面交给IOC容器管理(注解+扫描)
  2. 开启AspectJ的自动代理,为目标对象自动生成代理
  3. 将切面类通过注解@Aspect标识
<?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.atguigu.aop.annotation"></context:component-scan>

   <aop:aspectj-autoproxy> <aop:aspectj-autoproxy />
</beans>

补充:

当学习了SpringBoot后,通过SpringBoot来实现AOP,可省略此文件。因为SpringBoot以实现包扫描和切面标识

步骤五:设置切入点和通知类型

```java
@Aspect//表示这个类是一个切面类
@Component//保证这个切面类能够放入IOC容器
public class LogAspect {
	//设置切入点和通知类型
	//通知类型:
    //  前置通知:@Before
    //  异常通知:@AfterThrowing
    //  返回通知:@AfterReturning
    //  后置通知:@After
    //  环绕通知:@Around
}

步骤六:演示

@Test
public void testAdd(){
    ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
    Calculator calculator = ac.getBean( Calculator.class);
    int add = calculator.add(1, 1);
}

说明:
在这里插入图片描述

4.2、通知方式

JoinPoint 是指程序执行过程中明确的点,比如方法的调用或异常的处理。JoinPoint 提供了一个可供切面通知获取方法的关键信息的方式
joinPoint.getSignature().getName();获取增强方法的名字

4.2.1、前置通知

使用@Before注解标识,在被代理的目标方法前执行

@Before("execution(public int com.atguigu.aop.annotation.CalculatorImpl.*(..))")
public void beforeMethod(JoinPoint joinPoint){
    // getSignature()获取连接点签名,getName()获取连接点名称
    String methodName = joinPoint.getSignature().getName();
    String args = Arrays.toString(joinPoint.getArgs());
    System.out.println("Logger-->前置通知,方法名:"+methodName+",参数:"+args);
}

在这里插入图片描述

4.2.2、异常通知

使用@AfterThrowing注解标识,在被代理的目标方法异常结束后执行

@AfterThrowing(value = "execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))", throwing = "ex")
public void afterThrowingMethod(JoinPoint joinPoint, Throwable ex){
    String methodName = joinPoint.getSignature().getName();
    System.out.println("Logger-->异常通知,方法名:"+methodName+",异常:"+ex);
}


4.2.3、返回通知

使用@AfterReturning注解标识,在被代理的目标方法成功结束后执行,可以获取方法的返回结果
@AfterReturning(value = “execution(* com.atguigu.aop.annotation.CalculatorImpl.*(…))”, returning = “result”)

@AfterReturning(value = "execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))", returning = "result")
public void afterReturningMethod(JoinPoint joinPoint, Object result){
    String methodName = joinPoint.getSignature().getName();
    System.out.println("Logger-->返回通知,方法名:"+methodName+",结果:"+result);
}

在这里插入图片描述

4.2.4、后置通知

使用@After注解标识,在被代理的目标方法最终结束后执行

  @After("execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))")
    public void afterMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        System.out.println("Logger-->后置通知,方法名:"+methodName);
    }


4.2.5、环绕通知

使用@Around注解标识,使用try…catch…finally结构围绕整个被代理的目标方法,包括上面四种通知对应的所有位置

ProceedingJoinPoint 继承自 JoinPoint 接口,是用于环绕通知的特殊类型的 JoinPoint,它可以用于在通知中控制目标方法的执行。在环绕通知中,ProceedingJoinPoint 提供了一个 proceed() 方法,该方法会执行目标方法,并返回其结果。

@Around("execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))")
public Object aroundMethod(ProceedingJoinPoint joinPoint){
    String methodName = joinPoint.getSignature().getName();
    String args = Arrays.toString(joinPoint.getArgs());
    Object result = null;
    try {
        System.out.println("环绕通知-->目标对象方法执行之前");
        //目标对象(连接点)方法的执行
        result = joinPoint.proceed();
        System.out.println("环绕通知-->目标对象方法返回值之后");
    } catch (Throwable throwable) {
        throwable.printStackTrace();
        System.out.println("环绕通知-->目标对象方法出现异常时");
    } finally {
        System.out.println("环绕通知-->目标对象方法执行完毕");
    }
    return result;
}

4.3、获取通知信息

4.3.1、获取连接点信息

在任何通知方式中,获取连接点信息可以在通知方法的参数位置设置JoinPoint类型的形参

@Before("execution(public int com.atguigu.aop.annotation.CalculatorImpl.*(..))")
public void beforeMethod(JoinPoint joinPoint){
    //获取连接点的签名信息
    String methodName = joinPoint.getSignature().getName();
    //获取目标方法到的实参信息
    String args = Arrays.toString(joinPoint.getArgs());
    System.out.println("Logger-->前置通知,方法名:"+methodName+",参数:"+args);
}

4.3.2、获取目标方法的返回值

@AfterReturning中的属性returning,用来将通知方法的某个形参,接收目标方法的返回值

@AfterReturning(value = "execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))", returning = "result")
public void afterReturningMethod(JoinPoint joinPoint, Object result){
    String methodName = joinPoint.getSignature().getName();
    System.out.println("Logger-->返回通知,方法名:"+methodName+",结果:"+result);
}

4.3.3、获取目标方法的异常

@AfterThrowing中的属性throwing,用来将通知方法的某个形参,接收目标方法的异常

@AfterThrowing(value = "execution(* com.atguigu.aop.annotation.CalculatorImpl.*(..))", throwing = "ex")
public void afterThrowingMethod(JoinPoint joinPoint, Throwable ex){
    String methodName = joinPoint.getSignature().getName();
    System.out.println("Logger-->异常通知,方法名:"+methodName+",异常:"+ex);
}

4.4、重用切入点表达式

简化切入点的书写

  • 声明

    @Pointcut("execution(* com.atguigu.aop.annotation.*.*(..))")
    public void pointCut(){}
    
    
  • 同切面使用

    @Before("pointCut()")
    public void beforeMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        String args = Arrays.toString(joinPoint.getArgs());
        System.out.println("Logger-->前置通知,方法名:"+methodName+",参数:"+args);
    }
    
    
  • 不同切面使用

    @Before("com.atguigu.aop.CommonPointCut.pointCut()")
    public void beforeMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        String args = Arrays.toString(joinPoint.getArgs());
        System.out.println("Logger-->前置通知,方法名:"+methodName+",参数:"+args);
    }
    
    

五、基于XML的AOP

<context:component-scan base-package="com.atguigu.aop.xml"></context:component-scan>

<aop:config>
    <!--配置切面类-->
    <aop:aspect ref="loggerAspect">
        <aop:pointcut id="pointCut" 
                   expression="execution(* com.atguigu.aop.xml.CalculatorImpl.*(..))"/>
        <aop:before method="beforeMethod" pointcut-ref="pointCut"></aop:before>
        <aop:after method="afterMethod" pointcut-ref="pointCut"></aop:after>
        <aop:after-returning method="afterReturningMethod" returning="result" pointcut-ref="pointCut"></aop:after-returning>
        <aop:after-throwing method="afterThrowingMethod" throwing="ex" pointcut-ref="pointCut"></aop:after-throwing>
        <aop:around method="aroundMethod" pointcut-ref="pointCut"></aop:around>
    </aop:aspect>
</aop:config>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值