6、基于注解的AOP


【尚硅谷】SSM框架全套教程-讲师:杨博超

但行好事,莫问前程

6、基于注解的AOP

6.1、技术说明

在这里插入图片描述

1 动态代理(InvocationHandler)

JDK原生的实现方式,需要被代理的目标类必须实现接口。

因为这个技术要求代理对象和目标对象实现同样的接口(兄弟两个拜把子模式)。

2 cglib

通过继承被代理的目标类(认干爹模式)实现代理,所以不需要目标类实现接口。

3 AspectJ

AOP是一种思想,AspectJ是这种思想的具体实现方式

本质上是静态代理,将代理逻辑织入被代理的目标类编译得到的字节码文件,所以最终效果是动态的。

weaver就是织入器。

Spring只是借用了AspectJ中的注解。

6.2、准备工作

1 添加依赖

<!-- spring-aspects会帮我们传递过来aspectjweaver -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-aspects</artifactId>
    <version>5.3.22</version>
</dependency>

2 准备被代理的目标资源

接口:

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

    int sub(int i, int j);

    int mul(int i, int j);

    int div(int i, int j);

}

实现类:

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

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

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

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

6.3、创建切面类并配置

1 切面类

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

    @Before("execution(public int pers.tianyu.proxy.CalculatorPureImpl.*(..))")
    public void beforeMethod(JoinPoint joinPoint) {
        String name = joinPoint.getSignature().getName();
        String s = Arrays.toString(joinPoint.getArgs());
        System.out.println("Logger-->前置通知,方法名:" + name + ",参数:" + s);
    }

    @After("execution(public int pers.tianyu.proxy.CalculatorPureImpl.*(..))")
    public void afterMethod(JoinPoint joinPoint) {
        String name = joinPoint.getSignature().getName();
        System.out.println("Logger-->后置通知,方法名:" + name);
    }

    @AfterReturning(value = "execution(public int pers.tianyu.proxy.CalculatorPureImpl.*(..))", returning = "result")
    public void afterReturningMethod(JoinPoint joinPoint, Object result) {
        String name = joinPoint.getSignature().getName();
        System.out.println("Logger-->返回通知,方法名:" + name + "结果:" + result);
    }

    @AfterThrowing(value = "execution(public int pers.tianyu.proxy.CalculatorPureImpl.*(..))", throwing = "ex")
    public void afterThrowingMehtod(JoinPoint joinPoint, Throwable ex) {
        String name = joinPoint.getSignature().getName();
        System.out.println("Logger-->异常通知,方法名:" + name + "异常:" + ex);
    }

    @Around("execution(public int pers.tianyu.proxy.CalculatorPureImpl.*(..))")
    public Object aroundMethod(ProceedingJoinPoint joinPoint) {
        String name = joinPoint.getSignature().getName();
        String args = Arrays.toString(joinPoint.getArgs());
        Object result = null;
        try {
            System.out.println("环绕通知-->目标对象方法执行之前");
            //目标对象(连接点)方法的执行
            result = joinPoint.proceed();
            System.out.println("环绕通知-->目标对象方法返回值之后");
        } catch (Throwable e) {
            System.out.println("环绕通知-->目标对象方法出现异常时");
            throw new RuntimeException(e);
        }finally {
            System.out.println("环绕通知-->目标对象方法执行完毕");
        }
        return result;
    }

}

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: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">
	
	<!--
	基于注解的AOP的实现:
	1、将目标对象和切面交给IOC容器管理(注解+扫描)
	2、将切面类通过注解@Aspect标识
	3、开启AspectJ的自动代理,为目标对象自动生成代理
	-->

	<!--扫描包-->
	<context:component-scan base-package="pers.tianyu">
	</context:component-scan>
	
	<!--开启基于注解的aop功能-->
	<aop:aspectj-autoproxy />
</beans>

3 测试

当使用了AOP之后,为目标对象创建代理对象,在IOC容器中就无法获取目标对象。

无法直接获取 CalculatorPureImpl

CalculatorPureImpl calculatorPure = context.getBean(CalculatorPureImpl.class);

因为代理对象与目标对象实现相同接口,可以通过接口类型获取代理对象。

@Test
public void testLogAspect(){
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    Calculator bean = context.getBean(Calculator.class);
    int add = bean.add(1, 1);
}

如果项目中有其它类也实现了目标对象的接口,可以通过目标对象名字(首字母小写) + 接口获取

@Test
public void testLogAspect(){
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    Calculator bean = context.getBean("calculatorPureImpl",Calculator.class);
    int add = bean.add(1, 1);
}

6.4、各种通知

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

1 通知的执行顺序

  • Spring版本5.3.x以前:
    • 前置通知
    • 目标操作
    • 后置通知
    • 返回通知或异常通知
  • Spring版本5.3.x以后:
    • 前置通知
    • 目标操作
    • 返回通知或异常通知
    • 后置通知

6.5、切入点表达式语法

1 作用

在这里插入图片描述

2 语法细节

  • 用*号代替“权限修饰符”和“返回值”部分表示“权限修饰符”和“返回值”不限
  • 在包名的部分,一个“*”号只能代表包的层次结构中的一层,表示这一层是任意的。
    • 例如:*.Hello匹配com.Hello,不匹配com.atguigu.Hello
  • 在包名的部分,使用“*…”表示包名任意、包的层次深度任意
  • 在类名的部分,类名部分整体用*号代替,表示类名任意
  • 在类名的部分,可以使用*号代替类名的一部分
    • 例如:*Service匹配所有名称以Service结尾的类或接口
  • 在方法名部分,可以使用*号表示方法名任意
  • 在方法名部分,可以使用*号代替方法名的一部分
    • 例如:*Operation匹配所有方法名以Operation结尾的方法
  • 在方法参数列表部分,使用(…)表示参数列表任意
  • 在方法参数列表部分,使用(int,…)表示参数列表以一个int类型的参数开头
  • 在方法参数列表部分,基本数据类型和对应的包装类型是不一样的
    • 切入点表达式中使用 int 和实际方法中 Integer 是不匹配的
  • 在方法返回值部分,如果想要明确指定一个返回值类型,那么必须同时写明权限修饰符
    • 例如:execution(public int …Service.*(…, int)) 正确
    • 例如:execution(* int …Service.*(…, int)) 错误

在这里插入图片描述

6.6、重用切入点表达式

1 声明

@Pointcut("execution(public int pers.tianyu.proxy.CalculatorPureImpl.*(..))")
public void pointCut() {
}

2 在同一个切面中使用

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

3 在不同切面中使用

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

6.7、获取通知的相关信息

1 获取连接点信息

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

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

2 获取目标方法的返回值

通过@AfterReturning注解的returning属性,可以将通知方法的某个参数指定为接收目标对象方法返回值参数

@AfterReturning(value = "execution(public int pers.tianyu.proxy.CalculatorPureImpl.*(..))", returning = "result")
public void afterReturningMethod(JoinPoint joinPoint, Object result) {
    String name = joinPoint.getSignature().getName();
    System.out.println("Logger-->返回通知,方法名:" + name + "结果:" + result);
}

3 获取目标方法的异常

@AfterThrowing中的属性throwing,将通知方法中某个参数,设置为目标方法中出现的异常参数对象

@AfterThrowing(value = "execution(public int pers.tianyu.proxy.CalculatorPureImpl.*(..))", throwing = "ex")
public void afterThrowingMehtod(JoinPoint joinPoint, Throwable ex) {
    String name = joinPoint.getSignature().getName();
    System.out.println("Logger-->异常通知,方法名:" + name + "异常:" + ex);
}

6.8、环绕通知

环绕通知的方法返回值一定要和目标对象方法返回值一致。

@Around("execution(public int pers.tianyu.proxy.CalculatorPureImpl.*(..))")
public Object aroundMethod(ProceedingJoinPoint joinPoint) {
    String name = joinPoint.getSignature().getName();
    String args = Arrays.toString(joinPoint.getArgs());
    Object result = null;
    try {
        System.out.println("环绕通知-->目标对象方法执行之前");
        //目标方法的执行,目标方法的返回值一定要返回给外界调用者
        result = joinPoint.proceed();
        System.out.println("环绕通知-->目标对象方法返回值之后");
    } catch (Throwable e) {
        System.out.println("环绕通知-->目标对象方法出现异常时");
        throw new RuntimeException(e);
    } finally {
        System.out.println("环绕通知-->目标对象方法执行完毕");
    }
    return result;
}

6.9、切面的优先级

  • 相同目标方法上同时存在多个切面时,切面的优先级控制切面的内外嵌套顺序。
    • 优先级高的切面:外面
    • 优先级低的切面:里面
  • 使用@Order注解可以控制切面的优先级:
    • @Order(较小的数):优先级高
    • @Order(较大的数):优先级低 默认值是Integer的最大值
@Component
@Aspect
@Order(1)
public class LogAspectPro {

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

}

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值