【SpringMVC】自定义注解和使用

本文涉及的产品
服务治理 MSE Sentinel/OpenSergo,Agent数量 不受限
可观测可视化 Grafana 版,10个用户账号 1个月
简介: 定义注解:使用注解语法,在相关的注解类上定义自定义注解,可以指定注解的目标范围和属性。标记使用:在控制器类、方法或者方法参数上使用自定义注解,标识需要应用自定义逻辑的地方。处理注解:通过Spring的AOP、拦截器等机制,对标记了特定自定义注解的类、方法或者参数进行处理,实现相关的功能。注解分类(根据Annotation是否包含成员变量,可以把Annotation分为两类)标记Annotation:没有成员变量的Annotation;这种Annotation仅利用自身的存在与否来提供信息。


一、引言

1、简介

在Spring MVC中,我们可以使用自定义注解来扩展和定制化我们的应用程序。自定义注解是一种通过Java的注解机制定义的特殊注解,可以应用于控制器类、方法或者方法参数上,以实现不同的功能和行为。

注解相关类都包含在java.lang.annotation包中。

2、可实现功能

    1. 路由映射:可以定义一个自定义注解来标注控制器方法,以指定该方法的URL映射路径。
    2. 权限控制:可以定义一个自定义注解,用于标记需要进行权限验证的方法,从而实现简单的权限控制逻辑。
    3. 参数验证:可以定义一个自定义注解,用于标记方法参数,然后结合AOP等技术,在方法执行前或后进行参数的验证和校验。
    4. 日志记录:可以定义一个自定义注解,用于标记需要进行日志记录的方法,从而实现日志的统一处理。
    5. 缓存控制:可以定义一个自定义注解,用于标记需要进行缓存管理的方法,从而实现缓存的自动化管理。

    3、使用自定义注解流程

      1. 定义注解:使用注解语法,在相关的注解类上定义自定义注解,可以指定注解的目标范围和属性。
      2. 标记使用:在控制器类、方法或者方法参数上使用自定义注解,标识需要应用自定义逻辑的地方。
      3. 处理注解:通过Spring的AOP、拦截器等机制,对标记了特定自定义注解的类、方法或者参数进行处理,实现相关的功能。

      二、Java注解分类

      1、JDK基本注解

      @Override:重写

      一般出现在接口实现类里面

      @Target(ElementType.METHOD)
      @Retention(RetentionPolicy.SOURCE)
      public @interface Override {
      }
      image.gif

      @SuppressWarnings(value = "unchecked"):压制编辑器警告

      @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
      @Retention(RetentionPolicy.SOURCE)
      public @interface SuppressWarnings {
          String[] value();
      }
      image.gif

      2、JDK元注解

      @Retention:定义注解的保留策略
      @Retention(RetentionPolicy.SOURCE)    //注解仅存在于源码中,在class字节码文件中不包含
      @Retention(RetentionPolicy.CLASS)     //默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得,
      @Retention(RetentionPolicy.RUNTIME)    //注解会在class字节码文件中存在,在运行时可以通过反射获取到
      @Target:指定被修饰的Annotation可以放置的位置(被修饰的目标)
      @Target(ElementType.TYPE)                      //接口、类
      @Target(ElementType.FIELD)                     //属性
      @Target(ElementType.METHOD)                    //方法
      @Target(ElementType.PARAMETER)                 //方法参数
      @Target(ElementType.CONSTRUCTOR)               //构造函数
      @Target(ElementType.LOCAL_VARIABLE)            //局部变量
      @Target(ElementType.ANNOTATION_TYPE)           //注解
      @Target(ElementType.PACKAGE)                   //包
      注:可以指定多个位置,例如:
      @Target({ElementType.METHOD, ElementType.TYPE}),也就是此注解可以在方法和类上面使用
      @Inherited:指定被修饰的Annotation将具有继承性
      @Documented:指定被修饰的该Annotation可以被javadoc工具提取成文档.
      image.gif

      3、自定义注解

       

      注解分类(根据Annotation是否包含成员变量,可以把Annotation分为两类):

      标记Annotation:没有成员变量的Annotation; 这种Annotation仅利用自身的存在与否来提供信息

      元数据Annotation:

      包含成员变量的Annotation; 它们可以接受(和提供)更多的元数据;

      4、如何自定义注解

      使用@interface关键字, 其定义过程与定义接口非常类似, 需要注意的是:

             Annotation的成员变量在Annotation定义中是以无参的方法形式来声明的, 其方法名和返回值类型定义了该成员变量的名字和类型,而且我们还可以使用default关键字为这个成员变量设定默认值;

      三、自定义注解应用

      1、准备工作

      1.1、定义枚举类

      什么是枚举类及作用?

             枚举类是Java中一种特殊的数据类型,用于定义一组固定的命名常量。枚举类型提供了一种更强大、更安全和更易读的方式来表示一组相关的常量。在Java中,枚举类型是通过关键字enum来定义的。

             作用:枚举类的作用是提供一种类型安全的方式来表示一组固定的值,避免使用数字或字符串常量时可能出现的错误。通过使用枚举类型,可以限制变量只能取预定义的值,并且可以在代码中使用这些常量的名称来提高可读性和可维护性。

       

      package com.tgq.annotation;
      public enum  TranscationModel {
          Read, Write, ReadWrite
      }
      image.gif

      1.2、自定义注解类

      1.2.1、MyAnnotation1

      package com.tgq.annotation.pi;
      import java.lang.annotation.*;
      /**
       * MyAnnotation1注解可以用在类、接口、属性、方法上
       * 注解运行期也保留
       * 不可继承
       */
      @Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
      @Retention(RetentionPolicy.RUNTIME)
      @Documented
      public @interface MyAnnotation1 {
          int id();
          String name();
      }
      image.gif

      1.2.2、MyAnnotation2

      package com.tgq.annotation.pi;
      import com.tgq.annotation.TranscationModel;
      import java.lang.annotation.*;
      /**
       *  MyAnnotation2注解可以用在方法上
       *  注解运行期也保留
       *  不可继承
       */
      @Target(ElementType.METHOD)
      @Retention(RetentionPolicy.RUNTIME)
      @Documented
      public @interface MyAnnotation2 {
          TranscationModel model() default TranscationModel.ReadWrite;
      }
      image.gif

      1.2.3、MyAnnotation3

      package com.tgq.annotation.pi;
      /**
       * @软件包名 com.tgq.annotation.pi
       * @用户 tgq
       * @create 2023-09-15 下午6:07
       * @注释说明: MyAnnotation3注解可以用在方法上
       * * 注解运行期也保留
       * * 可继承
       */
      import com.tgq.annotation.TranscationModel;
      import java.lang.annotation.*;
      @Target(ElementType.METHOD)
      @Retention(RetentionPolicy.RUNTIME)
      @Inherited
      @Documented
      public @interface MyAnnotation3 {
          TranscationModel[] models() default TranscationModel.ReadWrite;
      }
      image.gif

      1.2.4、TestAnnotation

      package com.tgq.annotation.p2;
      import java.lang.annotation.ElementType;
      import java.lang.annotation.Retention;
      import java.lang.annotation.RetentionPolicy;
      import java.lang.annotation.Target;
      //@Retention(RetentionPolicy.SOURCE)
      @Retention(RetentionPolicy.RUNTIME)
      @Target(ElementType.FIELD)
      public @interface TestAnnotation {
          String value() default "默认value值";
          String what() default "这里是默认的what属性对应的值";
      }
      image.gif

      2、案例1

      2.1、测试类

      package com.tgq.annotation.pi;
      import com.tgq.annotation.TranscationModel;
      /**
       * @软件包名 com.tgq.annotation.pi
       * @用户 tgq
       * @create 2023-09-15 下午6:06
       * @注释说明:
       */
      @MyAnnotation1(id = 1, name = "lei")
      public class DemoTest {
          @MyAnnotation1(id = 2, name = "sx")
          private Integer age;
          @MyAnnotation2(model = TranscationModel.ReadWrite)
          public void select() {
              System.out.println("select");
          }
          @MyAnnotation3(models = {TranscationModel.Read, TranscationModel.Write, TranscationModel.ReadWrite})
          public void up() {
              System.out.println("up");
          }
      }

      image.gif

      2.2、获取类上的注解

      @Test
          public void list() throws Exception {
      //        获取类上的注解
              MyAnnotation1 annotation1 = DemoTest.class.getAnnotation(MyAnnotation1.class);
              System.out.println(annotation1.name() + "/" + annotation1.id());
      }

      image.gif

      image.gif编辑

      2.3、获取方法上的注解

      @Test
          public void list() throws Exception {
      //        获取方法上的注解
              MyAnnotation2 myAnnotation2 = DemoTest.class.getMethod("select").getAnnotation(MyAnnotation2.class);
              System.out.println(myAnnotation2.model());
      }

      image.gif

      image.gif编辑

      2.4、获取属性上的注解

      @Test
          public void list() throws Exception {
      //        获取属性上的注解
              MyAnnotation1 myAnnotation1 = DemoTest.class.getDeclaredField("age").getAnnotation(MyAnnotation1.class);
              System.out.println(myAnnotation1.name() + "/" + myAnnotation1.id());
      }

      image.gif

      image.gif编辑

      2.5、遍历方法上的注解

      @Test
          public void edit() throws Exception {
              MyAnnotation3 myAnnotation3 = DemoTest.class.getMethod("up").getAnnotation(MyAnnotation3.class);
              for (TranscationModel model : myAnnotation3.models()
              ) {
                  System.out.println(model);
              }
          }

      image.gif

      image.gif编辑

      3、案例2

      3.1、测试类

      package com.tgq.annotation.p2;
      public class Demo2 {
          @TestAnnotation(value = "这就是value对应的值_msg1", what = "这就是what对应的值_msg1")
          private static String msg1;
          @TestAnnotation("这就是value对应的值1:msg2")
          private static String msg2;
          @TestAnnotation(value = "这就是value对应的值2:msg3")
          private static String msg3;
          @TestAnnotation(what = "这就是what对应的值:msg4")
          private static String msg4;
      }

      image.gif

      package com.tgq.annotation.p2;
      import org.junit.Test;
      public class Demo2Test {
          @Test
          public void test1() throws Exception {
              TestAnnotation msg1 = Demo2.class.getDeclaredField("msg1").getAnnotation(TestAnnotation.class);
              System.out.println(msg1.value());
              System.out.println(msg1.what());
          }
          @Test
          public void test2() throws Exception{
              TestAnnotation msg2 = Demo2.class.getDeclaredField("msg2").getAnnotation(TestAnnotation.class);
              System.out.println(msg2.value());
              System.out.println(msg2.what());
          }
          @Test
          public void test3() throws Exception{
              TestAnnotation msg3 = Demo2.class.getDeclaredField("msg3").getAnnotation(TestAnnotation.class);
              System.out.println(msg3.value());
              System.out.println(msg3.what());
          }
          @Test
          public void test4() throws Exception{
              TestAnnotation msg4 = Demo2.class.getDeclaredField("msg4").getAnnotation(TestAnnotation.class);
              System.out.println(msg4.value());
              System.out.println(msg4.what());
          }
      }

      image.gif

      image.gif编辑

      image.gif编辑

      image.gif编辑

      image.gif编辑

      4、案例3

      4.1、自定义注解

      package com.tgq.annotation.p3;
      import java.lang.annotation.*;
      @Documented
      @Target({ElementType.PARAMETER})
      @Retention(RetentionPolicy.RUNTIME)
      public @interface IsNotNull {
          boolean value() default false;
      }

      image.gif

      4.2、测试类

      package com.tgq.annotation.p3;
      public class Demo3 {
          public void hello1(@IsNotNull(true) String name) {
              System.out.println("hello1:" + name);
          }
          public void hello2(@IsNotNull String name) {
              System.out.println("hello2:" + name);
          }
      }

      image.gif

      package com.tgq.annotation.p3;
      import org.junit.Test;
      import java.lang.reflect.Method;
      import java.lang.reflect.Parameter;
      public class Demo3Test {
          @Test
          public void hello1() throws Exception {
              Demo3 demo3 = new Demo3();
              for (Parameter parameter : demo3.getClass().getMethod("hello1", String.class).getParameters()) {
                  IsNotNull annotation = parameter.getAnnotation(IsNotNull.class);
                  if (annotation != null) {
                      System.out.println("hello1:" + annotation.value());//true
                  }
              }
          }
          @Test
          public void hello2() throws Exception {
              Demo3 demo3 = new Demo3();
              for (Parameter parameter : demo3.getClass().getMethod("hello2", String.class).getParameters()) {
                  IsNotNull annotation = parameter.getAnnotation(IsNotNull.class);
                  if (annotation != null) {
                      System.out.println("hello2:" + annotation.value());//false
                  }
              }
          }
          @Test
          public void hello3() throws Exception {
      //        模拟浏览器传递到后台的参数 解读@requestParam
              String name = "tqg";
              Demo3 demo3 = new Demo3();
              Method method = demo3.getClass().getMethod("hello1", String.class);
              for (Parameter parameter : method.getParameters()) {
                  IsNotNull annotation = parameter.getAnnotation(IsNotNull.class);
                  if (annotation != null) {
                      System.out.println(annotation.value());//true
                      if (annotation.value() && !"".equals(name)) {
                          method.invoke(demo3, name);
                      }
                  }
              }
          }
      }

      image.gif

      image.gif编辑

      image.gif编辑

      image.gif编辑

      四、Aop自定义注解应用

      1、自定义注解

      package com.tgq.annotation.aop;
      import java.lang.annotation.ElementType;
      import java.lang.annotation.Retention;
      import java.lang.annotation.RetentionPolicy;
      import java.lang.annotation.Target;
      @Target(ElementType.METHOD)
      @Retention(RetentionPolicy.RUNTIME)
      public @interface MyLog {
          String desc();
      }

      image.gif

      2、配置spring-context.xml

      <?xml version="1.0" encoding="UTF-8"?>
      <beans xmlns="http://www.springframework.org/schema/beans"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns:context="http://www.springframework.org/schema/context"
             xmlns:tx="http://www.springframework.org/schema/tx"
             xmlns:aop="http://www.springframework.org/schema/aop"
             xsi:schemaLocation="http://www.springframework.org/schema/beans
             http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/tx
      http://www.springframework.org/schema/tx/spring-tx.xsd
      http://www.springframework.org/schema/aop
      http://www.springframework.org/schema/aop/spring-aop.xsd">
          <!--    spring与mybatis整合的配置文件加载spring的上下文-->
          <import resource="classpath:spring-mybatis.xml"></import>
          <!--1. 注解式开发 -->
          <!-- 注解驱动 -->
          <context:annotation-config/>
          <!-- 用注解方式注入bean,并指定查找范围:com.javaxl.ssh2及子子孙孙包-->
          <context:component-scan base-package="com.tgq"/>
          <!--开启动态代理-->
          <aop:aspectj-autoproxy/>
      </beans>

      image.gif

      3、应用注解

      package com.tgq.annotation.aop;
      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.aspectj.lang.reflect.MethodSignature;
      import org.slf4j.Logger;
      import org.slf4j.LoggerFactory;
      import org.springframework.stereotype.Component;
      @Component
      @Aspect
      public class MyLogAspect {
          private static final Logger logger = LoggerFactory.getLogger(MyLogAspect.class);
          /**
           * 只要用到了com.tgq.p2.annotation.springAop.MyLog这个注解的,就是目标类
           */
          @Pointcut("@annotation(com.tgq.annotation.aop.MyLog)")
          private void MyValid() {
          }
          @Before("MyValid()")
          public void before(JoinPoint joinPoint) {
              MethodSignature signature = (MethodSignature) joinPoint.getSignature();
              logger.debug("[" + signature.getName() + " : start.....]");
              System.out.println("[" + signature.getName() + " : start.....]");
              MyLog myLog = signature.getMethod().getAnnotation(MyLog.class);
              logger.debug("【目标对象方法被调用时候产生的日志,记录到日志表中】:" + myLog.desc());
              System.out.println("【目标对象方法被调用时候产生的日志,记录到日志表中】:" + myLog.desc());
          }
      }

      image.gif

      4、Controller层代码

      package com.tgq.web;
      import com.tgq.annotation.aop.MyLog;
      import org.springframework.stereotype.Component;
      import org.springframework.web.bind.annotation.RequestMapping;
      @Component
      @RequestMapping("/log")
      public class LogController {
          @RequestMapping("/log")
          @MyLog(desc = "这是结合spring aop知识,讲解自定义注解应用的一个案例")
          public void testLogAspect() {
              System.out.println("这里随便来点啥");
          }
      }

      image.gif

      我们的访问地址:http://localhost:8080/log/log

      测试结果

      image.gif编辑


      相关实践学习
      日志服务之使用Nginx模式采集日志
      本文介绍如何通过日志服务控制台创建Nginx模式的Logtail配置快速采集Nginx日志并进行多维度分析。
      相关文章
      |
      7月前
      |
      前端开发 Java 编译器
      SpringMVC自定义注解---[详细介绍]
      SpringMVC自定义注解---[详细介绍]
      27 0
      |
      7月前
      |
      监控 Java 编译器
      SpringMVC之自定义注解
      SpringMVC之自定义注解
      36 0
      |
      8月前
      |
      前端开发 Java
      48SpringMVC - 参数绑定(自定义)
      48SpringMVC - 参数绑定(自定义)
      28 0
      |
      7月前
      |
      安全 Java 数据库连接
      【springMvc】自定义注解的使用方式
      【springMvc】自定义注解的使用方式
      68 0
      |
      20天前
      |
      前端开发 安全 Java
      解锁高级技巧:玩转 Spring MVC 自定义拦截器的神奇世界
      解锁高级技巧:玩转 Spring MVC 自定义拦截器的神奇世界
      80 0
      |
      20天前
      |
      缓存 安全 Java
      SpringMVC自定义注解和使用
      SpringMVC自定义注解和使用
      102 0
      |
      6月前
      |
      Java
      springmvc之自定义注解-->自定义注解简介,基本案例和aop自定义注解
      springmvc之自定义注解-->自定义注解简介,基本案例和aop自定义注解
      35 0
      |
      6月前
      |
      Java 开发者
      SpringMVC----自定义注解
      SpringMVC----自定义注解
      34 0
      |
      6月前
      |
      Java
      【SpringMVC】之自定义注解
      【SpringMVC】之自定义注解
      36 0
      |
      7月前
      |
      JSON 安全 Java
      SpringMVC之自定义注解(这期博客带你领略自定义注解的魅力)
      SpringMVC之自定义注解(这期博客带你领略自定义注解的魅力)
      47 0
      SpringMVC之自定义注解(这期博客带你领略自定义注解的魅力)