详解Spring AOP篇二

目录

Spring AOP核心概念

切点(Pointcut)

连接点(Join Point)

切点和连接点的关系

通知(Advice)

切面(Aspect)

通知类型

AspectDemo

TestControler

通知类型的执行顺序 

关于@Around表示的方法返回值问题

@Pointcut

切面优先级@Order

切点表达式

execution表达式

annotation表达式


Spring AOP核心概念
切点(Pointcut)

切点(Pointcut), 也称之为"切⼊点"。
Pointcut 的作⽤就是提供⼀组规则 (使⽤ AspectJ pointcut expression language 来描述), 告诉程序对哪些⽅法来进⾏功能增强.

上面的表达式 execution(* com.wmh.springaop.controller.*.*(..)) 就是 切点表达式。

连接点(Join Point)

满⾜切点表达式规则的⽅法, 就是连接点. 也就是可以被AOP控制的⽅法.

对于下面的代码,com.wmh.springaop.controller路径下所有类的所有方法,都是连接点。

切点和连接点的关系

连接点是满⾜切点表达式的元素. 切点可以看做是保存了众多连接点的⼀个集合。

通知(Advice)

通知就是具体要做的⼯作, 指哪些重复的逻辑,也就是共性功能(最终体现为⼀个⽅法)
⽐如上述代码中记录业务⽅法的耗时时间, 就是通知。

在AOP⾯向切⾯编程当中, 我们把这部分重复的代码逻辑抽取出来单独定义, 这部分代码就是通知的内容.

切面(Aspect)

切⾯(Aspect) = 切点(Pointcut) + 通知(Advice).
通过切⾯就能够描述当前AOP程序需要针对于哪些⽅法, 在什么时候执⾏什么样的操作.
切⾯既包含了通知逻辑的定义, 也包括了连接点的定义.

切⾯所在的类, 我们⼀般称为切⾯类(被@Aspect注解标识的类)。

通知类型

上⾯我们讲了什么是通知, 接下来学习通知的类型. @Around 就是其中⼀种通知类型, 表⽰环绕通知.
Spring中AOP的通知类型有以下⼏种:

• @Around: 环绕通知, 此注解标注的通知⽅法在⽬标⽅法前, 后都被执⾏
• @Before: 前置通知, 此注解标注的通知⽅法在⽬标⽅法前被执⾏
• @After: 后置通知, 此注解标注的通知⽅法在⽬标⽅法后被执⾏, ⽆论是否有异常都会执⾏
• @AfterReturning: 返回后通知, 此注解标注的通知⽅法在⽬标⽅法后被执⾏, 有异常不会执⾏
• @AfterThrowing: 异常后通知, 此注解标注的通知⽅法发⽣异常后执⾏

下面通过代码加深对上面通知类型的理解:

AspectDemo
package com.wmh.springaop.aspect;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@Aspect
public class AspectDemo {

    @Before("execution(* com.wmh.springaop.controller..*(..))")
    public void doBefore(){
        log.info("AspectDemo do before....");
    }

    @After("execution(* com.wmh.springaop.controller..*(..))")
    public void doAfter(){
        log.info("AspectDemo do after....");
    }

    @Around("execution(* com.wmh.springaop.controller..*(..))")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("AspectDemo do around before....");
        Object result = joinPoint.proceed();
        log.info("AspectDemo do around after...");
        return result;
    }

    @AfterReturning("execution(* com.wmh.springaop.controller..*(..))")
    public void doAfterReturning(){
        log.info("AspectDemo do after returning....");
    }

    @AfterThrowing("execution(* com.wmh.springaop.controller..*(..))")
    public void doAfterThrowing(){
        log.info("AspectDemo do after throwing....");
    }
}
TestControler
package com.wmh.springaop.controller;

import com.wmh.springaop.config.MyAspect;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RequestMapping("/test")
@RestController
public class TestController {

    @RequestMapping("/t1")
    public String t1(){
        log.info("执行t1方法...");
        return "t1";
    }

    @RequestMapping("/t2")
    public String t2(){
        log.info("执行t2方法...");
        int a = 10/0;
        return "t2";
    }

}
通知类型的执行顺序 

上面代码正常情况下的运行结果:

由此我们知道,正常情况下通知类型的执行顺序是:

发生异常时的运行结果:

由此我们知道,发生异常的情况下通知类型的执行顺序是: 

比较正常情况下和发生异常的情况下的运行结果:

从上面我们可以看到,当发生异常时@AfterReturning表示的通知方法不会执行了,@AfterThrowing表示的通知方法执行了。

而且,当@Around环绕通知中原始方法调用时有异常,通知中的环绕后的代码逻辑就不会执行了,因为原始方法调用出异常了。

关于@Around表示的方法返回值问题

当@Around标识的方法有返回值且类型为Object时:

AspectDemo

package com.wmh.springaop.aspect;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@Aspect
public class AspectDemo {

    @Around("execution(* com.wmh.springaop.controller..*(..))")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("AspectDemo do around before....");
        Object result = joinPoint.proceed();
        log.info("AspectDemo do around after...");
        return result;
    }
}

TestController

package com.wmh.springaop.controller;

import com.wmh.springaop.config.MyAspect;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RequestMapping("/test")
@RestController
public class TestController {

    @RequestMapping("/t1")
    public String t1(){
        log.info("执行t1方法...");
        return "t1";
    }

}

运行结果:

当@Around表示的方法没有返回值时:

AspectDemo

package com.wmh.springaop.aspect;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@Aspect
public class AspectDemo {

    @Around("execution(* com.wmh.springaop.controller..*(..))")
    public void doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("AspectDemo do around before....");
        Object result = joinPoint.proceed();
        log.info("AspectDemo do around after...");
    }
}

注意事项

• @Around 环绕通知需要调⽤ ProceedingJoinPoint.proceed() 来让原始⽅法执⾏, 其他
通知不需要考虑⽬标⽅法执⾏.
• @Around 环绕通知⽅法的返回值, 必须指定为Object, 来接收原始⽅法的返回值, 否则原始⽅法执⾏完毕, 是获取不到返回值的.
• ⼀个切⾯类可以有多个切点.

@Pointcut

上⾯代码存在⼀个问题, 就是存在⼤量重复的切点表达式 execution(* com.wmh.springaop.controller..*(..)) , Spring提供了 @PointCut 注解, 把公共的切点
表达式提取出来, 需要⽤到时引⽤该切⼊点表达式即可.

上述代码就可以修改为: 

package com.wmh.springaop.aspect;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@Aspect
public class AspectDemo {
    @Pointcut("execution(* com.wmh.springaop.controller..*(..))")
    public void pt(){};

    @Before("pt()")
    public void doBefore(){
        log.info("AspectDemo do before....");
    }

    @After("pt()")
    public void doAfter(){
        log.info("AspectDemo do after....");
    }

    @Around("pt()")
    public void doAround(ProceedingJoinPoint joinPoint) throws Throwable {
        log.info("AspectDemo do around before....");
        Object result = joinPoint.proceed();
        log.info("AspectDemo do around after...");
    }

    @AfterReturning("pt()")
    public void doAfterReturning(){
        log.info("AspectDemo do after returning....");
    }

    @AfterThrowing("pt()")
    public void doAfterThrowing(){
        log.info("AspectDemo do after throwing....");
    }
}

当切点定义使⽤private修饰时, 仅能在当前切⾯类中使⽤, 当其他切⾯类也要使⽤当前切点定义时, 就需要把private改为public. 引⽤⽅式为: 全限定类名.⽅法名()

package com.wmh.springaop.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;

@Order(1)
@Slf4j
@Component
@Aspect
public class AspectDemo2 {

    @Before("com.wmh.springaop.aspect.AspectDemo.pt()")
    public void doBefore(){
        log.info("AspectDemo2 do before....");
    }

    @After("com.wmh.springaop.aspect.AspectDemo.pt()")
    public void doAfter(){
        log.info("AspectDemo2 do after....");
    }

}
切面优先级@Order

当我们在⼀个项⽬中, 定义了多个切⾯类时, 并且这些切⾯类的多个切⼊点都匹配到了同⼀个⽬标⽅法.当⽬标⽅法运⾏的时候, 这些切⾯类中的通知⽅法都会执⾏, 那么这⼏个通知⽅法的执⾏顺序是什么样的呢?
我们还是通过程序来求证:
定义多个切⾯类:
为简单化, 只写了 @Before 和 @After 两个通知.

AspectDemo2

package com.wmh.springaop.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@Aspect
public class AspectDemo2 {

    @Before("com.wmh.springaop.aspect.AspectDemo.pt()")
    public void doBefore(){
        log.info("AspectDemo2 do before....");
    }

    @After("com.wmh.springaop.aspect.AspectDemo.pt()")
    public void doAfter(){
        log.info("AspectDemo2 do after....");
    }

}

AspectDemo3

package com.wmh.springaop.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@Aspect
public class AspectDemo3 {

    @Before("com.wmh.springaop.aspect.AspectDemo.pt()")
    public void doBefore(){
        log.info("AspectDemo3 do before....");
    }

    @After("com.wmh.springaop.aspect.AspectDemo.pt()")
    public void doAfter(){
        log.info("AspectDemo3 do after....");
    }

}

 AspectDemo4

package com.wmh.springaop.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@Aspect
public class AspectDemo4 {

    @Before("com.wmh.springaop.aspect.AspectDemo.pt()")
    public void doBefore(){
        log.info("AspectDemo4 do before....");
    }

    @After("com.wmh.springaop.aspect.AspectDemo.pt()")
    public void doAfter(){
        log.info("AspectDemo4 do after....");
    }

}

TestController

package com.wmh.springaop.controller;

import com.wmh.springaop.config.MyAspect;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RequestMapping("/test")
@RestController
public class TestController {

    @RequestMapping("/t1")
    public String t1(){
        log.info("执行t1方法...");
        return "t1";
    }

}

运行结果:

通过上述程序的运⾏结果, 可以看出:
存在多个切⾯类时, 默认按照切⾯类的类名字⺟排序:

• @Before 通知:字⺟排名靠前的先执⾏
• @After 通知:字⺟排名靠前的后执⾏

但这种⽅式不⽅便管理, 我们的类名更多还是具备⼀定含义的.
Spring 给我们提供了⼀个新的注解, 来控制这些切⾯通知的执⾏顺序: @Order
修改上面的代码:

AspectDemo2

package com.wmh.springaop.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Order(1)
@Slf4j
@Component
@Aspect
public class AspectDemo2 {

    @Before("com.wmh.springaop.aspect.AspectDemo.pt()")
    public void doBefore(){
        log.info("AspectDemo2 do before....");
    }

    @After("com.wmh.springaop.aspect.AspectDemo.pt()")
    public void doAfter(){
        log.info("AspectDemo2 do after....");
    }

}

AspectDemo3

package com.wmh.springaop.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Order(100)
@Slf4j
@Component
@Aspect
public class AspectDemo3 {

    @Before("com.wmh.springaop.aspect.AspectDemo.pt()")
    public void doBefore(){
        log.info("AspectDemo3 do before....");
    }

    @After("com.wmh.springaop.aspect.AspectDemo.pt()")
    public void doAfter(){
        log.info("AspectDemo3 do after....");
    }

}

AspectDemo4

package com.wmh.springaop.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Order(25)
@Slf4j
@Component
@Aspect
public class AspectDemo4 {

    @Before("com.wmh.springaop.aspect.AspectDemo.pt()")
    public void doBefore(){
        log.info("AspectDemo4 do before....");
    }

    @After("com.wmh.springaop.aspect.AspectDemo.pt()")
    public void doAfter(){
        log.info("AspectDemo4 do after....");
    }

}

运行结果:

通过上述程序的运⾏结果, 得出结论:
@Order 注解标识的切⾯类, 执⾏顺序如下:

• @Before 通知:数字越⼩先执⾏
• @After 通知:数字越⼤先执⾏

@Order 控制切⾯的优先级, 先执⾏优先级较⾼的切⾯, 再执⾏优先级较低的切⾯, 最终执⾏⽬标⽅法. 

切点表达式

上⾯的代码中, 我们⼀直在使⽤切点表达式来描述切点. 下⾯我们来介绍⼀下切点表达式的语法.
切点表达式常⻅有两种表达⽅式:

1. execution(RR):根据⽅法的签名来匹配
2. @annotation(RR) :根据注解匹配

execution表达式

execution() 是最常⽤的切点表达式, ⽤来匹配⽅法, 语法为: 

execution(<访问修饰符> <返回类型> <包名.类名.⽅法(⽅法参数)> <异常>)

其中: 访问修饰符和异常可以省略。

切点表达式⽀持通配符表达:

1. * :匹配任意字符,只匹配⼀个元素(返回类型, 包, 类名, ⽅法或者⽅法参数)
        a. 包名使⽤ * 表⽰任意包(⼀层包使⽤⼀个*)
        b. 类名使⽤ * 表⽰任意类
        c. 返回值使⽤ * 表⽰任意返回值类型
        d. ⽅法名使⽤ * 表⽰任意⽅法
        e. 参数使⽤ * 表⽰⼀个任意类型的参数
2. .. :匹配多个连续的任意符号, 可以通配任意层级的包, 或任意类型, 任意个数的参数
        a. 使⽤ .. 配置包名,标识此包以及此包下的所有⼦包
        b. 可以使⽤ .. 配置参数,任意个任意类型的参数

切点表达式示例

TestController 下的 public修饰, 返回类型为String ⽅法名为t1, ⽆参⽅法

execution(public String com.example.demo.controller.TestController.t1()) 

省略访问修饰符

execution(String com.example.demo.controller.TestController.t1()) 

匹配所有返回类型

execution(* com.example.demo.controller.TestController.t1())

匹配TestController 下的所有⽆参⽅法

 execution(* com.example.demo.controller.TestController.*()) 

匹配TestController 下的所有⽅法

execution(* com.example.demo.controller.TestController.*(..)) 

匹配controller包下所有的类的所有⽅法

execution(* com.example.demo.controller.*.*(..)) 

匹配所有包下⾯的TestController

execution(* com..TestController.*(..)) 

匹配com.example.demo包下, ⼦包下的所有类的所有⽅法 

execution(* com.example.demo..*(..))

annotation表达式

execution表达式更适⽤有规则的, 如果我们要匹配多个⽆规则的⽅法呢, ⽐如:TestController中的t1()和UserController中的u1()这两个⽅法.
这个时候我们使⽤execution这种切点表达式来描述就不是很⽅便了.
我们可以借助⾃定义注解的⽅式以及另⼀种切点表达式 @annotation 来描述这⼀类的切点。

实现步骤:

1. 编写⾃定义注解
2. 使⽤ @annotation 表达式来描述切点
3. 在连接点的⽅法上添加⾃定义注解 

自定义注解@MyAspect

package com.wmh.springaop.config;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAspect {
}

说明

1.@Target 标识了 Annotation 所修饰的对象范围, 即该注解可以⽤在什么地⽅.
常⽤取值:
        ElementType.TYPE: ⽤于描述类、接⼝(包括注解类型) 或enum声明
        ElementType.METHOD: 描述⽅法
        ElementType.PARAMETER: 描述参数
        ElementType.TYPE_USE: 可以标注任意类型
2. @Retention 指Annotation被保留的时间⻓短, 标明注解的⽣命周期
@Retention 的取值有三种:
        1. RetentionPolicy.SOURCE:表⽰注解仅存在于源代码中, 编译成字节码后会被丢弃. 这意味着在运⾏时⽆法获取到该注解的信息, 只能在编译时使⽤. ⽐如 @SuppressWarnings , 以及lombok提供的注解 @Data , @Slf4j
        2. RetentionPolicy.CLASS:编译时注解. 表⽰注解存在于源代码和字节码中, 但在运⾏时会被丢弃. 这意味着在编译时和字节码中可以通过反射获取到该注解的信息, 但在实际运⾏时⽆法获取. 通常⽤于⼀些框架和⼯具的注解.
        3. RetentionPolicy.RUNTIME:运⾏时注解. 表⽰注解存在于源代码, 字节码和运⾏时中. 这意味着在编译时, 字节码中和实际运⾏时都可以通过反射获取到该注解的信息. 通常⽤于⼀些需要在运⾏时处理的注解, 如Spring的 @Controller @ResponseBody 

切面类

使⽤ @annotation 切点表达式定义切点, 只对 @MyAspect ⽣效
切⾯类代码如下: 

package com.wmh.springaop.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@Aspect
public class MyAspectDemo {
    @Around("@annotation(com.wmh.springaop.config.MyAspect)")
    public Object doAround(ProceedingJoinPoint joinPoint){
        log.info("do around before...");
        Object o = null;
        try {
            o = joinPoint.proceed();
        } catch (Throwable e) {
            log.error("发生异常,e:", e);
        }
        log.info("do around after...");
        return o;
    }
}

添加自定义注解

TestController

package com.wmh.springaop.controller;

import com.wmh.springaop.config.MyAspect;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RequestMapping("/test")
@RestController
public class TestController {

    @MyAspect
    @RequestMapping("/t1")
    public String t1(){
        log.info("执行t1方法...");
        return "t1";
    }

    @RequestMapping("/t2")
    public String t2(){
        log.info("执行t2方法...");
        int a = 10/0;
        return "t2";
    }

}

UserController

package com.wmh.springaop.controller;

import com.wmh.springaop.config.MyAspect;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RequestMapping("/user")
@RestController
public class UserController {
    @RequestMapping("/u1")
    public String u1(){
        log.info("执行u1方法...");
        return "u1";
    }

    @MyAspect
    @RequestMapping("/u2")
    public String u2(){
        log.info("执行u2方法...");
        return "u2";
    }
}

 访问test/t1运行结果:

访问user/u2运行结果:

评论 44
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

新绿MEHO

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值