SpringBoot项目自定义注解实现拦截类及其内部方法

1.引入AOP依赖

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-aop</artifactId>
  4. </dependency>

2.编写注解

  1. import java.lang.annotation.*;
  2. /**
  3. * @ClassName: ApiAuth
  4. * @Description: 自定义注解
  5. * @Author: luzihao
  6. * @Email: 458243101@qq.com
  7. * @Date: 2020/9/22 16:33
  8. */
  9. // 适用于类、方法
  10. @Target({ElementType.TYPE, ElementType.METHOD})
  11. // 注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在
  12. @Retention(RetentionPolicy.RUNTIME)
  13. public @interface ApiAuth {
  14. }

@Target:说明注解所修饰的范围

  • ElementType.TYPE:类
  • ElementType.METHOD:方法

@Retention:说明注解的生命力

  • RetentionPolicy.RUNTIME:运行时有效

    3.编写拦截器

    ```java import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component;

/**

  • @ClassName: ApiAuthAspect
  • @Description: 自定义拦截器
  • @Author: luzihao
  • @Email: 458243101@qq.com
  • @Date: 2020/9/23 9:53 */ @Aspect @Component public class ApiAuthAspect {

    //切点 @Pointcut(“@annotation(com.你的注解路径.annotation.ApiAuth) || @within(com.你的注解路径.annotation.ApiAuth)”) public void cut() {}

    //前置 @Before(“cut()”) public void beforePointcut(JoinPoint joinPoint) {

    1. System.out.println(joinPoint.getArgs()[0]); //所有参数,这里输出第一个
    2. System.out.println(joinPoint.getSignature()); //拦截到的方法信息
    3. System.out.println(joinPoint.getTarget()); //被代理对象
    4. System.out.println(joinPoint.getThis()); //代理对象

    }

    //后置 @After(“cut()”) public void afterPointcut(JoinPoint joinPoint) {}

    //环绕 @Around(“cut()”) public void aroundPointcut(JoinPoint joinPoint) {}

    //返回之后 @AfterReturning(“cut()”) public void afterReturningPointcut(JoinPoint joinPoint) {}

    //报错时 @AfterThrowing(“cut()”) public void afterThrowingPointcut(JoinPoint joinPoint) {} } ``` @Aspect:标注当前类为切面容器

    4.使用

  • 编写测试Controller ```java import com.你的注解路径.annotation.ApiAuth; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import java.util.Map;

//用于测试注解 @ApiAuth //可直接在类上使用,亦可在方法上 @Controller @RequestMapping(“/test”) public class TestController {

  1. @GetMapping
  2. public String test(String s) {
  3. return "hello";
  4. }

}

  1. - 浏览器访问
  2. ![image.png](https://cdn.nlark.com/yuque/0/2020/png/292947/1600830594478-b47c4fef-d4aa-4b25-bc92-7a0e910352ff.png#align=left&display=inline&height=103&margin=%5Bobject%20Object%5D&name=image.png&originHeight=103&originWidth=513&size=9647&status=done&style=none&width=513)
  3. - 控制台输出

444 String com.test.controller.TestController.test(String) com.test.controller.TestController@44b58a5e com.test.controller.TestController@44b58a5e ```