一、什么是 Aop

AOP (Aspect Oriented Programming),意为面向切面编程,可以通过预编译方式和运行期动态代理实现在不修改源代码的情况下给程序动态统一添加功能的一种技术。

AOP的编程思想是把对类对象的横切问题点,从业务逻辑中分离出来,从而达到解耦的目的,增加代码的复用性,提高开发效率。

没使用Aop之前的:

spring boot aop Before 输入参数 springboot中的aop_spring


使用Aop之后:

spring boot aop Before 输入参数 springboot中的aop_java_02

AOP的应用场景:

spring boot aop Before 输入参数 springboot中的aop_spring_03

二、 使用到的相关注解

@Component 将当前类注入到Spring容器内

@Aspect :表明是一个切面类

@Before :前置通知,在方法执行之前执行

@After :后置通知,在方法执行之后执行

@AfterRuturning :返回通知,在方法返回结果之后执行

@AfterThrowing :异常通知,在方法抛出异常之后执行

@Around :环绕通知,围绕着方法执行

@Pointcut :切入点,PointCut(切入点)表达式有很多种,其中execution用于使用切面的连接点。

注意:上面所提到的五种通知方法中,除了环绕通知外,其他的四个通知注解中,加或者不加参数JoinPoint都可以,如果有用到JoinPoint的地方就加,用不到就可以不加。

spring boot aop Before 输入参数 springboot中的aop_System_04

三、 Aop 相关概念

Joinpoint(连接点):所谓连接点是指那些被拦截到的点,在 spring 中,这些点指的是方法,因为 spring 只支持方法类型的连接点,通俗的说就是被增强类中的所有方法

PointCut(切入点):所谓切入点是指我们要对哪些 Joinpoint 进行拦截的定义,通俗的说就是被增强类中的被增强的方法,因为被增强类中并不是所有的方法都被代理了

Advice(通知/增强):所谓通知是指拦截到 Joinpoint (被增强的方法)之后所要做的事情就是通知,通俗的说就是对被增强的方法进行增强的代码

通知的类型:前置通知,返回通知,异常通知,后置通知,环绕通知

前置通知:在被代理方法执行之前执行

返回通知:在被代理方法执行之后执行

异常通知:在被代理方法执行出错的时候执行

后置通知:无论怎样都会执行

注意:返回通知和异常通知只能有一个会被执行,因为发生异常执行异常通知,然后就不会继续向下执行,自然后置通知也就不会被执行,反之亦然。

Aspect(切面):是切入点和通知(引介)的结合,通俗的说就是建立切入点和通知方法在创建时的对应关系

四、@PointCut 表达式详解

PointCut:切入点,指哪些方法需要被执行AOP,PointCut表达式可以有一下几种方式

1、execution(表达式)

表达式:访问修饰符 返回值 包名.包名.包名…类名.方法名(参数列表)

标准的表达式写法范例:

public void com.aismall.testaop.controller.HelloController.helloAop()

访问修饰符可以省略

void com.aismall.testaop.controller.HelloController.helloAop()

返回值可以使用通配符*,表示任意返回值

* com.aismall.testaop.controller.HelloController.helloAop()

包名可以使用通配符,表示任意包,但是有几级包,就需要写几个*.

* *.*.*.*.HelloController.helloAop()

包名可以使用…表示当前包及其子包

* *...HelloController.helloAop()

类名和方法名都可以使用*来实现通配

* *..*.*()

参数列表:

1、可以直接写数据类型:

基本类型直接写名称 :例如,int

引用类型写包名.类名的方式 :例如,java.lang.String

可以使用通配符*表示任意类型,但是必须有参数

可以使用…表示有无参数均可,有参数可以是任意类型

2、全通配写法:* .*(…)

2、@annotation,带有相应注解的方法,比如对标有@Transactional注解的方法进行增强

@annotation(org.springframework.transaction.annotation.Transactional)

五、代码实战 —— execution(表达式)

使用aop来完成全局请求日志处理

spring boot aop Before 输入参数 springboot中的aop_System_05


1、创建个controller

@RestController
public class HelloController {
    @RequestMapping("/helloAop")
    public Object hello(){
        return "hello aop";
    }
    @RequestMapping("/helloError")
    public Object helloError(){
        return 1/0;
    }
}

2、创建一个aspect切面类

@Aspect
@Component
public class MyAop {
    //切入点:待增强的方法
    @Pointcut("execution(public * com.aismall.testaop.controller.*.*(..))")
    //切入点签名
    public void log(){
        System.out.println("pointCut签名。。。");
    }
    //前置通知
    @Before("log()")
    public void deBefore(JoinPoint jp) throws Throwable {
        // 接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        System.out.println("URL : " + request.getRequestURL().toString());
        System.out.println("HTTP_METHOD : " + request.getMethod());
        System.out.println("CLASS_METHOD : " + jp);
        System.out.println("ARGS : " + Arrays.toString(jp.getArgs()));

    }
    //返回通知
    @AfterReturning(returning = "ret", pointcut = "log()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求,返回内容
        System.out.println("返回通知:方法的返回值 : " + ret);
    }

    //异常通知
    @AfterThrowing(throwing = "ex", pointcut = "log()")
    public void throwss(JoinPoint jp,Exception ex){
        System.out.println("异常通知:方法异常时执行.....");
        System.out.println("产生异常的方法:"+jp);
        System.out.println("异常种类:"+ex);
    }

    //后置通知
    @After("log()")
    public void after(JoinPoint jp){
        System.out.println("后置通知:最后且一定执行.....");
    }
}

3、启动项目

请求链接:http://localhost:8080/helloAop

控制台返回:

URL : http://localhost:8080/helloAop
HTTP_METHOD : GET
CLASS_METHOD : execution(Object com.aismall.testaop.controller.HelloController.hello())
ARGS : []
返回通知:方法的返回值 : hello aop
后置通知:最后且一定执行.....

分析:返回通知和异常通知只会执行一个,后置通知一定会执行。

六、代码实战二 —— @annotation方式

spring boot aop Before 输入参数 springboot中的aop_包名_06


1、编写一个自定义注解

//表示次注解可以标注在类和方法上
@Target({ElementType.METHOD, ElementType.TYPE})
//运行时生效
@Retention(RetentionPolicy.RUNTIME)
public @interface MyLogAnnotation {
    //定义一个变量,可以接受参数
    String desc() default " ";
}

2、在HelloController类中添加一个方法

@RequestMapping("helloAnnotation")
//标有这个注解的方法会被增强
@MyLogAnnotation(desc = "@Annotation")
public Object helloAnnotation() {
    return "hello annotation";
}

3、切面类

@Aspect
@Component
public class MyAopAnnotation {
    //切入点:增强标有MyLogAnnotation注解的方法
    @Pointcut(value="@annotation(com.aismall.testaop.MyAnnotation.MyLogAnnotation)")
    //切入点签名
    public void logAnnotation(){
        System.out.println("pointCut签名。。。");
    }
    //前置通知
    @Before("logAnnotation()")
    public void deBefore(JoinPoint jp) throws Throwable {
        // 接收到请求,记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        System.out.println("URL : " + request.getRequestURL().toString());
    }
    //返回通知
    @AfterReturning(returning = "ret", pointcut = "logAnnotation()")
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求,返回内容
        System.out.println("返回通知:方法的返回值 : " + ret);
    }

    //异常通知
    @AfterThrowing(throwing = "ex", pointcut = "logAnnotation()")
    public void throwss(JoinPoint jp,Exception ex){
        System.out.println("异常通知:方法异常时执行.....");
        System.out.println("产生异常的方法:"+jp);
        System.out.println("异常种类:"+ex);
    }

    //后置通知
    @After("logAnnotation()")
    public void after(JoinPoint jp){
        System.out.println("后置通知:最后且一定执行.....");
    }
}

4、启动项目

请求链接:http://localhost:8080/helloAnnotation

控制台显示:

URL : http://localhost:8080/helloAnnotation
返回通知:方法的返回值 : hello annotation
后置通知:最后且一定执行.....

七、环绕通知

环绕通知可以把前面的四种通知都表示出来,而且环绕通知一般单独使用

环绕通知的使用:

Spring框架为我们提供了一个接口:ProceedingJoinPoint,该接口有一个方法proceed(),此方法就相当于明确调用切入点方法。

该接口作为环绕通知的方法参数,在程序执行时,spring框架会为我们提供该接口的实现类供我们使用。

增强代码写在调用proceed()方法之前为前置通知,之后为返回通知,写在catch中为异常通知,写在finally中为后置通知。

spring boot aop Before 输入参数 springboot中的aop_spring_07

第一步:在HelloController类中添加一个方法

@RequestMapping("/helloAround")
public Object helloAround(){
    System.out.println("helloAround执行了。。。");
    return "hello around";
}

第二步:切面类

Aspect
@Component
public class MyAroundAop {
    //切入点:待增强的方法
    @Pointcut("execution(public * com.aismall.testaop.controller.*.*(..))")
    //切入点签名
    public void logAround() {
        System.out.println("pointCut签名。。。");
    }

    //环绕通知,环绕增强,相当于MethodInterceptor
    @Around("logAround()")
    public Object aroundAdvice(ProceedingJoinPoint pjp) {
        Object rtValue = null;
        try {
            Object[] args = pjp.getArgs();//得到方法执行所需的参数

            System.out.println("通知类中的aroundAdvice方法执行了。。前置");

            rtValue = pjp.proceed(args);//明确调用切入点方法(切入点方法)

            System.out.println("通知类中的aroundAdvice方法执行了。。返回");
            System.out.println("返回通知:"+rtValue);

            return rtValue;
        } catch (Throwable e) {
            System.out.println("通知类中的aroundAdvice方法执行了。。异常");
            throw new RuntimeException(e);
        } finally {
            System.out.println("通知类中的aroundAdvice方法执行了。。后置");
        }
    }
}

第三步:启动项目

请求链接:http://localhost:8080/helloAround

控制台返回的结果:

通知类中的aroundAdvice方法执行了。。前置
helloAround执行了。。。
通知类中的aroundAdvice方法执行了。。返回
返回通知:hello around
通知类中的aroundAdvice方法执行了。。后置