Spring-Boot AOP 的简单创建

AOP 切面

1.导依赖

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
  1. 定义一个切面类
@Aspect
@Component
public class AopAspect {

    /**
     *  @Pointcut:定义一个切面,所关注的某件事入口
     *  execution():表达式主体
     *  第一个 *:表示返回值类型, *表示所有类型
     *  com.sapphire.common.service:包名
     *  ..:表示当前包和当前包子包
     *  第二个*:表示类名,*表示所有类
     *  *(..):*表示方法名,括弧里边表示参数,..表示任何参数
     */
    @Pointcut("execution(* com.sapphire.common.service..*.*(..))")
    public void pointCut1(){
    
//        业务逻辑

    }

    /**
     *  针对注解定义切面
     */
    @Pointcut("@annotation(org.springframework.web.bind.annotation.GetMapping)")
    public void pointCut1() {
//        业务逻辑
    }
    
}
  1. 一些重要的注解(括号里填的是pointCut方法名)
@Before("pointCut1()") //在目的方法前执行pointCut1方法
@After("pointCut1()")
//在目的方法 返回结果后 做出操作,一般用于对结果进行增强处理,注意返回结果参数类型一定要一样,不然不能识别出来
@AfterRuning(pointcut = "pointCut1()",returning = "resultType")
//目的方法出现异常时执行切面方法
@AfterThrowing(pointcut = "pointCut()", throwing = "ex")
  1. 一般AOP 会应用与拦截 或者自定义注解方面
posted @ 2024-03-08 19:21  Liang2003  阅读(2)  评论(0编辑  收藏  举报