SpringBoot的AOP编程

引入依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

相关注解

# 切面注解
- @Aspect 用来类上,代表这个类是一个切面
- @Before 用在方法上代表这个方法是一个前置通知方法 
- @After 用在方法上代表这个方法是一个后置通知方法 @Around 用在方法上代表这个方法是一个环绕的方法
- @Around 用在方法上代表这个方法是一个环绕的方法

案例

package com.codegzy.config;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.context.annotation.Configuration;

@Configuration
@Aspect     //切面配置
public class MyAdviceConfig {

    @Before("execution(* com.codegzy.controller.*.before*(..))")
    public void before(JoinPoint joinPoint) {
        System.out.println("执行前置通知的方法" + joinPoint.getSignature());
        System.out.println("执行前置通知的目标对象" + joinPoint.getTarget());
        System.out.println("前置通知已执行...");
    }

    @After("within(com.codegzy.controller.*)")
    public void after(JoinPoint joinPoint) {
        System.out.println("执行前置通知的方法" + joinPoint.getSignature());
        System.out.println("执行前置通知的目标对象" + joinPoint.getTarget());
        System.out.println("后置通知已执行");
    }

    @Around("@annotation(com.codegzy.annotations.MyAnnotation)")
    public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("执行前置通知的方法" + joinPoint.getSignature());
        System.out.println("执行前置通知的目标对象" + joinPoint.getTarget());
        System.out.println("环绕通知已执行");
        Object proceed = joinPoint.proceed();
        System.out.println("环绕通知已放行");
        return proceed;
    }
}


注意: 环绕通知存在返回值,参数为ProceedingJoinPoint,如果执行放行,不会执行目标方法,一旦放行必须将目标方法的返回值返回,否则调用者无法接受返回数据

个人推荐使用自定义注解方式使用切面,例子中第三个around方法

posted @ 2021-09-08 18:37  code-G  阅读(79)  评论(0)    收藏  举报