小白快速入门之SpringBoot面向切面编程(AOP)

1、常见应用

  • 全局异步导出
  • 全局日志打印
  • 全局异常拦截
  • 全局数据权限获取

2、简单例子

1、引入依赖

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

2、连接controller请求

注意:..代表任何a包下任意类带Controller单词的任意方法

package com.tjx.a.aa.aaa.aop;

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

/**
 * <p>
 *
 * </p>
 *
 * @author tianjiaxin
 * @createTime 2024/5/30 19:06
 * @Description:
 */
@Slf4j
@Aspect
@Component
public class LogAop {
    @Pointcut("execution(public * com.tjx.a..*Controller.*(..))")
    public void repeatPoint() {
        log.info("logAop 横切点");
    }

    @Before("repeatPoint()")
    public void before(JoinPoint joinPoint) {
        Object[] args = joinPoint.getArgs();
        Signature signature = joinPoint.getSignature();
        Object target = joinPoint.getTarget();
        log.info("我是logAop-before, args:{}, signature:{}, target:{}", args, signature, target);
    }
}

3、详细展开

3.1、切入点

1、匹配方法

@Pointcut("execution(public * com.tjx.a..*Controller.*(..))")

2、匹配注解

@Pointcut("@annotation(com.example.printdemo.annotation.UserAnnotation)")

3.2、环绕通知

@Before在目标方法执行之前执行的通知。它不能阻止方法的执行,但可以在方法执行前添加额外的功能。
@AfterReturning在目标方法正常返回后执行的通知。例如,如果一个方法正常返回而没有抛出异常,就会执行这个通知。
@AfterThrowing在目标方法抛出异常后执行的通知。如果一个方法抛出异常,就会执行这个通知。
@After在目标方法执行之后执行的通知。无论目标方法如何退出(正常返回或抛出异常),都会执行的通知。
@Around包围目标方法的通知,可以在目标方法执行前后添加额外的功能,并决定是否继续执行目标方法。

参数:

JoinPoint可以获取目标方法的信息,如方法名、参数等,
ProceedingJoinPoint同上,但是@Around必须是这个, 让方法执行pjp.proceed()

常见方法参数:

public void before() {}
public void before(JoinPoint jp) {}

public Object around(ProceedingJoinPoint joinPoint) throws Throwable{}

// 带注解的
@Around(value = "@annotation(log)")
public Object aroundLog(ProceedingJoinPoint joinPoint, Log log) throws Throwable{}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值