Spring boot 中简单使用AOP实例+自定义注解

1. AOP使用案例

1. 导入AOP依赖

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

2.编写测试方法入口

@RestController
public class TestController {

    @RequestMapping(value = "/testAop", method = RequestMethod.POST)
    public void testAop() {

        System.out.println("testAop方法");

    }

}

3. 编写AOP方法

@Aspect
@Component
public class AopController {

    /** 配置切入点*/
    @Pointcut("execution(* com.szk.test..*(..))")
    public void controllerPointCut(){

    }

    /** 进入切点前要执行的方法*/
    @Before("controllerPointCut()")
    public void before(){
        System.out.println("进入前");
    }

    /** 进入要切点后要执行的方法*/
    @After("controllerPointCut()")
    public void after(){
        System.out.println("进入后");
    }

    /** 围绕切点执行的方法*/
    @Around("controllerPointCut()")
    public void round(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("环绕前");
        joinPoint.proceed();
        System.out.println("环绕后");
    }

4.启动项目,用postman调用方法打印结构

在这里插入图片描述

2.自定义注解

1. 导入AOP依赖上面的一样

2. 测试方法入口(把自定义的注解添加到方法上)

在这里插入图片描述

3. 切入点配置做一下调整,指向自定义的注解

@Aspect
@Component
public class AopController {

    /** 配置切入点*/
    @Pointcut("@annotation(com.szk.test.TestInterface)")
    public void controllerPointCut(){

    }

    /** 进入切点前要执行的方法*/
    @Before("controllerPointCut()")
    public void before(){
        System.out.println("自定义注解进入前");
    }

    /** 进入要切点后要执行的方法*/
    @After("controllerPointCut()")
    public void after(){
        System.out.println("自定义注解进入后");
    }

    /** 围绕切点执行的方法*/
    @Around("controllerPointCut()")
    public void round(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("自定义注解环绕前");
        joinPoint.proceed();
        System.out.println("自定义注解环绕后");
    }

}

2.调用打印日志

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值