原创

Spring笔记四(AOP-junit)

温馨提示:
本文最后更新于 2023年11月30日,已超过 519 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我

一 代理模式

代理模式是设计模式中的一种,属于结构型模式。目标是通过提供一个代理类,让我们在调用目标方法的时候,不再是直接调用目标方法,而是间接通过代理类去调用。让不属于目标方法的逻辑代码从目标方法中剥离出来,这种方式叫做解耦,目的是减少对目标方法的改动,同时让其他附加业务/功能集中 在一起,有利于维护和扩展。

1.1.静态代理

为每一个目标对象创建一个代理类,将目标对象设置到代理对象的属性,且代理类需要实现目标对象的接口,然后在代理类中新增其他的业务逻辑。

缺点:虽然实现了解耦,但是会增加很多的代码,没有实现统一管理,而且增加项目的工作量。

1.2.动态代理

在项目运行的过程中动态的去创建目标类,然后调用目标方法。

静态代理的缺点,在动态代理中得到了完善。

以计算器加减方法为例,需要在调用方法前后增加日志

public interface Calculator {

    int add(int a,int b);

    int re(int a,int b);
}
public class CalculatorImpl implements Calculator{

    @Override
    public int add(int a, int b) {
        return a+b;
    }

    @Override
    public int re(int a, int b) {
        return a-b;
    }
}

静态代理示例:

从示例中不难看出,当需要调整业务逻辑时,需求修改很多的代理类,无法进行统一管理。

//静态代理
public class CalculatorStaticProxyImpl implements Calculator{

    private CalculatorImpl calculator;

    public CalculatorStaticProxyImpl(CalculatorImpl calculator) {
        this.calculator = calculator;
    }

    @Override
    public int add(int a, int b) {
        System.out.println("方法执行前。。。。。。。。");
        int add = calculator.add(a, b);
        System.out.println("方法执行后。。。。。。。。");
        return add;
    }

    @Override
    public int re(int a, int b) {
        System.out.println("方法执行前。。。。。。。。");
        int re = calculator.re(a, b);
        System.out.println("方法执行后。。。。。。。。");
        return re;
    }
}

动态代理示例:

动态代理的核心是Proxy对象和InvocationHandler接口。

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

//动态代理类
public class DynCalculatorProxy {

    private Object target;
    public DynCalculatorProxy(Object object) {
        this.target = object;
    }
    //通过动态代理获取目标对象,需要用到Proxy代理类
    public Object getTarget(){
        /*
        * ClassLoader loader: 目标对象的类加载器
        * Class<?>[] interfaces: 目标对象的所有接口类的class集合
        * InvocationHandler h : 调用处理器,需要扩展的功能都在该处理器中实现
        */
        ClassLoader loader = target.getClass().getClassLoader();
        Class<?>[] interfaces = target.getClass().getInterfaces();
        //InvocationHandler是一个接口,可以写一个匿名内部类,也可以实现接口后作为属性引入(使用容器管理时需要);
        InvocationHandler h = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //在此处实现需要扩展的业务功能
                System.out.println("执行方法前..........."+ Arrays.asList(args));
                Object result = method.invoke(target, args);
                System.out.println("执行方法后..........."+result);
                return result;
            }
        };
        return Proxy.newProxyInstance(loader,interfaces,h);
    }

}

测试:

    public static void main(String[] args) {
        DynCalculatorProxy dProxy = new DynCalculatorProxy(new CalculatorImpl());
        Calculator target = (Calculator) dProxy.getTarget();
        target.add(1,2);
    }

二 AOP

2.1. 概述

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

2.2.相关术语

①横切关注点

分散在每个各个模块中解决同一样的问题,如用户验证、日志管理、事务处理、数据缓存都属于横切关注点。

从每个方法中抽取出来的同一类非核心业务。在同一个项目中,我们可以使用多个横切关注点对相关方法进行多个不同方面的增强。

这个概念不是语法层面的,而是根据附加功能的逻辑上的需要:有十个附加功能,就有十个横切关注点。

②通知(增强)

增强,通俗说,就是你想要增强的功能,比如 安全,事务,日志等。

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

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

③切面

封装通知方法的类。

④目标

被代理的目标对象。

⑤代理

向目标对象应用通知之后创建的代理对象。

⑥连接点

这也是一个纯逻辑概念,不是语法定义的。

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

⑦切入点

定位连接点的方式。

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

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

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

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

2.3.作用

  • 简化代码:把方法中固定位置的重复的代码抽取出来,让被抽取的方法更专注于自己的核心功能,提高内聚性。

  • 代码增强:把特定的功能封装到切面类中,看哪里有需要,就往上套,被套用了切面逻辑的方法就被切面给增强了。

2.4.基于注解的AOP

2.4.1 技术说明

  • 动态代理分为JDK动态代理和cglib动态代理
  • 当目标类有接口的情况使用JDK动态代理和cglib动态代理,没有接口时只能使用cglib动态代理
  • JDK动态代理动态生成的代理类会在com.sun.proxy包下,类名为$proxy1,和目标类实现相同的接口
  • cglib动态代理动态生成的代理类会和目标在在相同的包下,会继承目标类
  • 动态代理(InvocationHandler):JDK原生的实现方式,需要被代理的目标类必须实现接口。因为这个技术要求代理对象和目标对象实现同样的接口(兄弟两个拜把子模式)。
  • cglib:通过继承被代理的目标类(认干爹模式)实现代理,所以不需要目标类实现接口。
  • AspectJ:是AOP思想的一种实现。本质上是静态代理,将代理逻辑“织入”被代理的目标类编译得到的字节码文件,所以最终效果是动态的。weaver就是织入器。Spring只是借用了AspectJ中的注解。

2.4.2 需要的依赖

pom中引入 AOP和aspects依赖。

        <!--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>

2.4.3 测试

在bean.xml中开启组件扫描和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: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.manage.ano"></context:component-scan>

    <!--    开启AOP自动代理-->
    <aop:aspectj-autoproxy></aop:aspectj-autoproxy>
</beans>

切面类:

除@Around 环绕通知外,其他四种使用方式一致。

AOP一般应用于访问日志记录、访问权限控制等。

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Aspect  //告诉spring这是一个切面类
@Component //该类交给spring容器管理
public class MyAspect {

    /*
    * 切入点通知
    * 前置通知:@Before
    * 返回通知:@AfterReturning
    * 异常通知:@AfterThrowing
    * 返回通知:@After
    * 环绕通知:@Around
    */
    @Before(value = "execution(* com.manage.ano.*.*(..))")
    public void cutAddMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        String args = Arrays.toString(joinPoint.getArgs());
        System.out.println("方法名="+methodName+",参数="+args);
    };

    @AfterReturning(value = "execution(* com.mhld.manage.ano.*.*(..))",returning = "result")
    public void afterReturning(JoinPoint joinPoint,Object result){
        System.out.println("返回的结果值");
        System.out.println("AfterReturning");
    };

    @AfterThrowing(value = "execution(* com.mhld.manage.ano.*.*(..))",throwing = "ex")
    public void AfterThrowing(JoinPoint joinPoint,Exception ex){
        System.out.println("出现异常后的通知"+ex.getMessage());
        System.out.println("AfterThrowing");
    };
    @After(value = "execution(* com.manage.ano.*.*(..))")
    public void After(JoinPoint joinPoint){
        System.out.println("After");
    };
    @Around(value = "execution(* com.manage.ano.*.*(..))")
    public Object aroundMethod(ProceedingJoinPoint joinPoint){
        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;
    }

}
    @Test
    public void testAno(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
        Calculator calculator = context.getBean(Calculator.class);
        calculator.add(1,23);
    }
    打印日志:
    环绕通知-->目标对象方法执行之前
    方法名=add,参数=[1, 23]
    Before
    AfterReturning
    After
    环绕通知-->目标对象方法返回值之后
    环绕通知-->目标对象方法执行完毕

2.4.4 切入点方法重写

当很多地方都需要同一个切入点时,我们可以将切入点写成一个方法,使用@Pointcut方法进行标识,方便统一管理。在使用的时候直接指定切入点方法即可。

@Aspect  //告诉spring这是一个切面类
@Component //该类交给spring容器管理
public class MyAspectPointCut {

    @Pointcut("execution(* com.mhld.manage.ano.*.*(..))")
    public void addLogs(){};


    //同一个切面下可以直接写上方法,不同切面需要加上全路径
    @Before(value = "addLogs()")
    //@Before(value = "com.manage.ano.MyAspectPointCut.addLogs()")
    public void cutAddMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        String args = Arrays.toString(joinPoint.getArgs());
        System.out.println("方法名="+methodName+",参数="+args);
        System.out.println("Before");
    };

}

2.4.5 切入点表达式介绍

  • 用*号代替“权限修饰符”和“返回值”部分表示“权限修饰符”和“返回值”不限
  • 在包名的部分,一个“*”号只能代表包的层次结构中的一层,表示这一层是任意的。
    • 例如:*.Hello匹配com.Hello,不匹配com.atguigu.Hello
  • 在包名的部分,使用“*..”表示包名任意、包的层次深度任意
  • 在类名的部分,类名部分整体用*号代替,表示类名任意
  • 在类名的部分,可以使用*号代替类名的一部分

    • 例如:*Service匹配所有名称以Service结尾的类或接口
  • 在方法名部分,可以使用*号表示方法名任意

  • 在方法名部分,可以使用*号代替方法名的一部分

    • 例如:*Operation匹配所有方法名以Operation结尾的方法
  • 在方法参数列表部分,使用(..)表示参数列表任意

  • 在方法参数列表部分,使用(int,..)表示参数列表以一个int类型的参数开头
  • 在方法参数列表部分,基本数据类型和对应的包装类型是不一样的
    • 切入点表达式中使用 int 和实际方法中 Integer 是不匹配的
  • 在方法返回值部分,如果想要明确指定一个返回值类型,那么必须同时写明权限修饰符
    • 例如:execution(public int ..Service.(.., int)) 正确
      例如:execution(
      int ..Service.*(.., int)) 错误

img025

2.4.6 切面优先级

相同目标方法上同时存在多个切面时,切面的优先级控制切面的内外嵌套顺序。

  • 优先级高的切面:外面
  • 优先级低的切面:里面

使用@Order注解可以控制切面的优先级:

  • @Order(较小的数):优先级高
  • @Order(较大的数):优先级低

2.5. 基于xml配置AOP

配置类

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component //该类交给spring容器管理
public class MyAspect {

    public void cutAddMethod(JoinPoint joinPoint){
        String methodName = joinPoint.getSignature().getName();
        String args = Arrays.toString(joinPoint.getArgs());
        System.out.println("方法名="+methodName+",参数="+args);
        System.out.println("Before");
    };

    public void afterReturning(JoinPoint joinPoint,Object result){
        System.out.println("返回的结果值");
        System.out.println("AfterReturning");
    };

    public void AfterThrowing(JoinPoint joinPoint,Exception ex){
        System.out.println("出现异常后的通知"+ex.getMessage());
        System.out.println("AfterThrowing");
    };
    public void After(JoinPoint joinPoint){
        System.out.println("After");
    };

    public Object aroundMethod(ProceedingJoinPoint joinPoint){
        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;
    }
}

xml

<?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.manage.xmlaop"></context:component-scan>

    <!--配置AOP代理类-->
    <aop:config>
        <!--指定切面类-->
        <aop:aspect ref="myAspect">
            <!--配置切点方法-->
            <aop:pointcut id="addLogs" expression="execution(* com.manage.xmlaop.*.*(..))"/>
            <!--配置前置通知-->
            <aop:before pointcut-ref="addLogs" method="cutAddMethod"></aop:before>
            <!--配置返回通知 返回值名称和方法中一致-->
            <aop:after-returning pointcut-ref="addLogs" method="afterReturning" returning="result" ></aop:after-returning>
            <!--配置异常通知 一场返回参数和方法中一致-->
            <aop:after-throwing pointcut-ref="addLogs" method="AfterThrowing" throwing="ex"></aop:after-throwing>
            <!--配置后置通知-->
            <aop:after pointcut-ref="addLogs" method="After"></aop:after>
            <!--配置环绕通知-->
            <aop:around pointcut-ref="addLogs" method="aroundMethod"></aop:around>
        </aop:aspect>

    </aop:config>
</beans>

三 Spring整合Junit

3.1. 引入相关依赖

        <!--spring对junit的支持相关依赖-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>6.0.2</version>
        </dependency>

        <!--junit5测试-->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>5.7.2</version>
        </dependency>

3.2. xml

在xml中开启组件扫描

<?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.manage"></context:component-scan>
</beans>

3.3. test配置

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;

//指定配置文件
@SpringJUnitConfig(locations = "classpath:bean.xml")
public class TestMain {

    @Autowired
    private User user;

    @Test
    public void testUser(){
        user.helloUnit();
    }
}
正文到此结束