SpringBoot(十七)自定义注解

客官°小女子只卖身不卖艺 2024-03-22 06:20 177阅读 0赞

目录

自定义注解

前置知识:Java注解之 @Target、@Retention、@Documented简介

@Target({ElementType.TYPE}) 注解

@Retention({RetentionPolicy.Runtime}) 注解

@Documented注解

自定义注解案例

1、pom依赖

2、自定义注解类

3、切面类

4、应用

5、测试


自定义注解

在SpringBoot中,我们可以通过自定义注解来简化代码的编写和提高代码的可读性。下面是使用自定义注解的步骤:

前置知识:Java注解之 @Target、@Retention、@Documented简介

@Target({ElementType.TYPE}) 注解

表示当前注解(@CheckToken)可以打在什么东西上面,此处可以放在类上与方法上

ElementType 这个枚举类型的常量提供了一个简单的分类:注解可能出现在Java程序中的语法位置(这些常量与元注解类型(@Target)一起指定在何处写入注解的合法位置)

  1. package java.lang.annotation;
  2. /**
  3. * The constants of this enumerated type provide a simple classification of the
  4. * syntactic locations where annotations may appear in a Java program. These
  5. * constants are used in {@link Target java.lang.annotation.Target}
  6. * meta-annotations to specify where it is legal to write annotations of a
  7. * given type.
  8. * @author Joshua Bloch
  9. * @since 1.5
  10. * @jls 9.6.4.1 @Target
  11. * @jls 4.1 The Kinds of Types and Values
  12. */
  13. public enum ElementType {
  14. /** 类, 接口 (包括注解类型), 或 枚举 声明 */
  15. TYPE,
  16. /** 字段声明(包括枚举常量) */
  17. FIELD,
  18. /** 方法声明(Method declaration) */
  19. METHOD,
  20. /** 正式的参数声明 */
  21. PARAMETER,
  22. /** 构造函数声明 */
  23. CONSTRUCTOR,
  24. /** 局部变量声明 */
  25. LOCAL_VARIABLE,
  26. /** 注解类型声明 */
  27. ANNOTATION_TYPE,
  28. /** 包声明 */
  29. PACKAGE,
  30. /**
  31. * 类型参数声明
  32. *
  33. * @since 1.8
  34. */
  35. TYPE_PARAMETER,
  36. /**
  37. * 使用的类型
  38. *
  39. * @since 1.8
  40. */
  41. TYPE_USE
  42. }
  43. 字段声明(包括枚举常量) */
  44. FIELD,
  45. /** 方法声明(Method declaration) */
  46. METHOD,
  47. /** 正式的参数声明 */
  48. PARAMETER,
  49. /** 构造函数声明 */
  50. CONSTRUCTOR,
  51. /** 局部变量声明 */
  52. LOCAL_VARIABLE,
  53. /** 注解类型声明 */
  54. ANNOTATION_TYPE,
  55. /** 包声明 */
  56. PACKAGE,
  57. /**
  58. * 类型参数声明
  59. *
  60. * @since 1.8
  61. */
  62. TYPE_PARAMETER,
  63. /**
  64. * 使用的类型
  65. *
  66. * @since 1.8
  67. */
  68. TYPE_USE
  69. }

@Retention({RetentionPolicy.Runtime}) 注解

RetentionPolicy这个枚举类型的常量描述保留注解的各种策略,它们与元注解(@Retention)一起指定注释要保留多长时间

  1. package java.lang.annotation;
  2. /**
  3. * Annotation retention policy. The constants of this enumerated type
  4. * describe the various policies for retaining annotations. They are used
  5. * in conjunction with the {@link Retention} meta-annotation type to specify
  6. * how long annotations are to be retained.
  7. *
  8. * @author Joshua Bloch
  9. * @since 1.5
  10. */
  11. public enum RetentionPolicy {
  12. /**
  13. * 注解只在源代码级别保留,编译时被忽略
  14. */
  15. SOURCE,
  16. /**
  17. * 注解将被编译器在类文件中记录
  18. * 但在运行时不需要JVM保留。这是默认的
  19. * 行为.
  20. */
  21. CLASS,
  22. /**
  23. *注解将被编译器记录在类文件中
  24. *在运行时保留VM,因此可以反读。
  25. * @see java.lang.reflect.AnnotatedElement
  26. */
  27. RUNTIME
  28. }
  29. 注解将被编译器在类文件中记录
  30. * 但在运行时不需要JVM保留。这是默认的
  31. * 行为.
  32. */
  33. CLASS,
  34. /**
  35. *注解将被编译器记录在类文件中
  36. *在运行时保留VM,因此可以反读。
  37. * @see java.lang.reflect.AnnotatedElement
  38. */
  39. RUNTIME
  40. }

@Documented注解

Documented注解表明这个注解是由 javadoc记录的,在默认情况下也有类似的记录工具。 如果一个类型声明被注解了文档化,它的注解成为公共API的一部分。

自定义注解案例

本文以案例验证token为目的开发注解

1、pom依赖

  1. <!--aop启动器-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-aop</artifactId>
  5. </dependency>

2、自定义注解类

  1. /**
  2. * 自定义注解类
  3. */
  4. //表示当前注解(@CheckToken)可以打在什么东西上面,此处可以放在类上与方法上
  5. @Target({ElementType.METHOD, ElementType.TYPE})
  6. @Retention(RetentionPolicy.RUNTIME) //运行时执行
  7. @Documented//指定被修饰的该Annotation可以被javadoc工具提取成文档
  8. public @interface CheckToken {
  9. // String value() default "";
  10. }

3、切面类

  1. /**
  2. * 切面类
  3. */
  4. @Aspect//切面注解
  5. @Component
  6. @SuppressWarnings({"unused"})
  7. public class CheckTokenAspect {
  8. //日志对象
  9. public static final Logger logger = LoggerFactory.getLogger(CheckTokenAspect.class);
  10. //切入点到自定义注解
  11. @Pointcut("@annotation(com.yka.annotation.CheckToken)")
  12. public void annotationPointcut() {
  13. }
  14. //前置通知
  15. @Before("annotationPointcut()")
  16. public void beforePointcut(JoinPoint joinPoint) throws Exception {
  17. // 请求开始时间
  18. ServletRequestAttributes sra = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
  19. String token = sra.getRequest().getHeader("token");
  20. //控制台日志打印
  21. logger.info("token为:"+token);
  22. if (token == null || "".equals(token)) {
  23. throw new Exception("token为空");//报错打印
  24. }
  25. //校验token
  26. }
  27. @Around("annotationPointcut()")
  28. public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
  29. return joinPoint.proceed();
  30. }
  31. /**
  32. * 在切入点return内容之后切入内容(可以用来对处理返回值做一些加工处理)
  33. * @param joinPoint
  34. */
  35. @AfterReturning("annotationPointcut()")
  36. public void doAfterReturning(JoinPoint joinPoint) {
  37. }
  38. }

4、应用

  1. @RestController
  2. public class AopController {
  3. @PostMapping("/testPost")
  4. @CheckToken//自定义注解
  5. public String postTest(){
  6. return "aaaaaaaaaaaa";
  7. }
  8. }

5、测试

测试有token请求体,测试成功

666a5d5d199347bba00564123e473e7b.png

日志打印

c61df65a682b4efe9117fa1a5d62a2bf.png

测试没有token请求体,测试失败

67c4aa37551844549c15e6667b542545.png

日志打印:

801ec20cd32c413ab70e44f1fc4421a1.png

发表评论

表情:
评论列表 (有 0 条评论,177人围观)

还没有评论,来说两句吧...

相关阅读

    相关 springBoot定义注解

    1.自定义注解一般用拦截或者在处理业务逻辑之前进行的操作,比如我们需要在每次处理前端发出的请求时进行认证token的操作,这时就需要自定义注解 2.自定义注解的实现

    相关 springboot定义注解

    在我们使用springboot的时候,需要使用自定义的注解,如日志的获取及保存,权限的前期判断,都可以自定义注解来实现功能, 自定义注解的核心原理,还是使用了spring自身

    相关 SpringBoot定义注解

    文章目录 简介 demo(自定义用户信息注解) 简介 在很多业务场景中,我们一般会对重复的代码进行抽取注册成一个工具类,但是每次都要引入该方法,显然不