代码编织梦想

1.首先创建一个注解类,如下

package com.ruoyi.common.annotation;

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NeedTest {
   public boolean isNeed() default false;

   public int number() default 0;

   public String methodName() default "test";
}

2.创建一个切入类

package com.ruoyi.framework.aspectj;

import com.ruoyi.common.annotation.NeedTest;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class NeedTestAspect {

    @AfterReturning(pointcut = "@annotation(needTest)",returning = "returnJson")
    public void testAspect(JoinPoint joinPoint, NeedTest needTest,Object returnJson){
        System.out.println(joinPoint.getArgs().toString());
        System.out.println("-------------------------");
        System.out.println("return"+returnJson);
    }
}

其中
@Aspect是标记其为切入类
@Component将其加载到容器中
@annotation(needTest),就是所有有这个注解的方法都会被切入,里面的参数就是方法中的参数名
JoinPoint可以获取方法的参数等等
returnJson是方法的返回值,可以利用
3.在方法上加入注解

package com.ruoyi.web.controller.common;

import com.ruoyi.common.annotation.NeedTest;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/test")
public class TestController1 {

    @GetMapping("needTest/{id}/{name}")
    @NeedTest
    public String test(@PathVariable("id") String id,@PathVariable("name") String name){
        return id+"-a-a-a-a-a-"+name;
    }
}

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_43568790/article/details/128126161