• SpringMVC自定义注解和使用


    一.引言

    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:重写

    应用:一般出现在接口实现类里面

    1. @Target(ElementType.METHOD)
    2. @Retention(RetentionPolicy.SOURCE)
    3. public @interface Override {
    4. }

    @SuppressWarnings(value = "unchecked") 

    应用:压制编辑器警告

    1. @Target({TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE})
    2. @Retention(RetentionPolicy.SOURCE)
    3. public @interface SuppressWarnings {
    4. String[] value();
    5. }

    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工具提取成文档.

     3、自定义注解

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

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

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

    4、如何自定义注解 ?

    使用@interface关键字, 其定义过程与定义接口非常类似, 需要注意的是:
       Annotation的成员变量在Annotation定义中是以无参的方法形式来声明的, 其方法名和返回值类型定义了该成员变量的名字和类型,
       而且我们还可以使用default关键字为这个成员变量设定默认值;

     三.使用自定义注解

    1.配置pom.XMl

    1. "1.0" encoding="UTF-8"?>
    2. "http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4. 4.0.0
    5. org.springframework.boot
    6. spring-boot-starter-parent
    7. 2.3.7.RELEASE
    8. com.xzs
    9. spboottest01
    10. 0.0.1-SNAPSHOT
    11. spboottest01
    12. Demo project for Spring Boot
    13. 8
    14. org.springframework.boot
    15. spring-boot-starter-web
    16. org.springframework.boot
    17. spring-boot-starter-test
    18. org.springframework.boot
    19. spring-boot-maven-plugin

    2.了解什么是枚举?

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

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

    1. package com.xzs.annotation;
    2. public enum TranscationModel {
    3. Read, Write, ReadWrite
    4. }

     3、自定义注解类

    1.MyAnnotation1 
    1. package com.xzs.annotation.pi;
    2. import java.lang.annotation.*;
    3. @Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD})
    4. @Retention(RetentionPolicy.RUNTIME)
    5. @Documented
    6. public @interface MyAnnotation1 {
    7. int id();
    8. String name();
    9. }

    2、MyAnnotation2

    1. package com.xzs.annotation.pi;
    2. import com.xzs.annotation.TranscationModel;
    3. import java.lang.annotation.*;
    4. /**
    5. * MyAnnotation2注解可以用在方法上
    6. * 注解运行期也保留
    7. * 不可继承
    8. */
    9. @Target(ElementType.METHOD)
    10. @Retention(RetentionPolicy.RUNTIME)
    11. @Documented
    12. public @interface MyAnnotation2 {
    13. TranscationModel model() default TranscationModel.ReadWrite;
    14. }

     .3、MyAnnotation3

    1. package com.xzs.annotation.pi;
    2. import com.xzs.annotation.TranscationModel;
    3. import java.lang.annotation.*;
    4. @Target(ElementType.METHOD)
    5. @Retention(RetentionPolicy.RUNTIME)
    6. @Inherited
    7. @Documented
    8. public @interface MyAnnotation3 {
    9. TranscationModel[] models() default TranscationModel.ReadWrite;
    10. }

    .4、TestAnnotation

    1. package com.xzs.annotation.pi;
    2. import java.lang.annotation.ElementType;
    3. import java.lang.annotation.Retention;
    4. import java.lang.annotation.RetentionPolicy;
    5. import java.lang.annotation.Target;
    6. //@Retention(RetentionPolicy.SOURCE)
    7. @Retention(RetentionPolicy.RUNTIME)
    8. @Target(ElementType.FIELD)
    9. public @interface TestAnnotation {
    10. String value() default "默认value值";
    11. String what() default "这里是默认的what属性对应的值";
    12. }

    案例1:

    1.创建一个测试类

    1. package com.xzs.annotation.pi;
    2. import com.xzs.annotation.TranscationModel;
    3. @MyAnnotation1(id = 1, name = "lei")
    4. public class DemoTest {
    5. @MyAnnotation1(id = 2, name = "sx")
    6. private Integer age;
    7. @MyAnnotation2(model = TranscationModel.ReadWrite)
    8. public void select() {
    9. System.out.println("select");
    10. }
    11. @MyAnnotation3(models = {TranscationModel.Read, TranscationModel.Write, TranscationModel.ReadWrite})
    12. public void up() {
    13. System.out.println("up");
    14. }
    15. }

     2、获取类上的注解

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

     3.获取方法上的注解

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

     

    4. 获取属性上的注解

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

     .5、遍历方法上的注解

    1. @Test
    2. public void edit() throws Exception {
    3. MyAnnotation3 myAnnotation3 = DemoTest.class.getMethod("up").getAnnotation(MyAnnotation3.class);
    4. for (TranscationModel model : myAnnotation3.models()
    5. ) {
    6. System.out.println(model);
    7. }
    8. }

    案例2:

     1.测试类:

    1. package com.xzs.annotation.p2;
    2. import com.xzs.annotation.pi.TestAnnotation;
    3. public class Demo2 {
    4. @TestAnnotation(value = "这就是value对应的值_msg1", what = "这就是what对应的值_msg1")
    5. private static String msg1;
    6. @TestAnnotation("这就是value对应的值1:msg2")
    7. private static String msg2;
    8. @TestAnnotation(value = "这就是value对应的值2:msg3")
    9. private static String msg3;
    10. @TestAnnotation(what = "这就是what对应的值:msg4")
    11. private static String msg4;
    12. }

    1. package com.xzs.annotation.p2;
    2. import com.xzs.annotation.pi.TestAnnotation;
    3. import org.junit.jupiter.api.Test;
    4. public class Demo2Test {
    5. @Test
    6. public void test1() throws Exception {
    7. TestAnnotation msg1 = Demo2.class.getDeclaredField("msg1").getAnnotation(TestAnnotation.class);
    8. System.out.println(msg1.value());
    9. System.out.println(msg1.what());
    10. }
    11. @Test
    12. public void test2() throws Exception{
    13. TestAnnotation msg2 = Demo2.class.getDeclaredField("msg2").getAnnotation(TestAnnotation.class);
    14. System.out.println(msg2.value());
    15. System.out.println(msg2.what());
    16. }
    17. @Test
    18. public void test3() throws Exception{
    19. TestAnnotation msg3 = Demo2.class.getDeclaredField("msg3").getAnnotation(TestAnnotation.class);
    20. System.out.println(msg3.value());
    21. System.out.println(msg3.what());
    22. }
    23. @Test
    24. public void test4() throws Exception{
    25. TestAnnotation msg4 = Demo2.class.getDeclaredField("msg4").getAnnotation(TestAnnotation.class);
    26. System.out.println(msg4.value());
    27. System.out.println(msg4.what());
    28. }
    29. }

     

     

     

     案例3:

    自定义注解

    1. package com.xzs.annotation.p3;
    2. import java.lang.annotation.*;
    3. @Documented
    4. @Target({ElementType.PARAMETER})
    5. @Retention(RetentionPolicy.RUNTIME)
    6. public @interface IsNotNull {
    7. boolean value() default false;
    8. }

    测试类

    1. package com.xzs.annotation.p3;
    2. import org.junit.jupiter.api.Test;
    3. import java.lang.reflect.Method;
    4. import java.lang.reflect.Parameter;
    5. public class Demo3Test {
    6. @Test
    7. public void hello1() throws Exception {
    8. Demo3 demo3 = new Demo3();
    9. for (Parameter parameter : demo3.getClass().getMethod("hello1", String.class).getParameters()) {
    10. IsNotNull annotation = parameter.getAnnotation(IsNotNull.class);
    11. if (annotation != null) {
    12. System.out.println("hello1:" + annotation.value());//true
    13. System.out.println(("-----------hello1----------"));
    14. }
    15. }
    16. }
    17. @Test
    18. public void hello2() throws Exception {
    19. Demo3 demo3 = new Demo3();
    20. for (Parameter parameter : demo3.getClass().getMethod("hello2", String.class).getParameters()) {
    21. IsNotNull annotation = parameter.getAnnotation(IsNotNull.class);
    22. if (annotation != null) {
    23. System.out.println("hello2:" + annotation.value());//false
    24. System.out.println(("-----------hello2----------"));
    25. }
    26. }
    27. }
    28. @Test
    29. public void hello3() throws Exception {
    30. // 模拟浏览器传递到后台的参数 解读@requestParam
    31. String name = "tqg";
    32. Demo3 demo3 = new Demo3();
    33. Method method = demo3.getClass().getMethod("hello1", String.class);
    34. for (Parameter parameter : method.getParameters()) {
    35. IsNotNull annotation = parameter.getAnnotation(IsNotNull.class);
    36. if (annotation != null) {
    37. System.out.println(annotation.value());//true
    38. if (annotation.value() && !"".equals(name)) {
    39. method.invoke(demo3, name);
    40. }
    41. System.out.println(("-----------hello3----------")); }
    42. }
    43. }}

     

    四、Aop自定义注解应用

    1、自定义注解

    1. package com.xzs.annotation.aop;
    2. import java.lang.annotation.ElementType;
    3. import java.lang.annotation.Retention;
    4. import java.lang.annotation.RetentionPolicy;
    5. import java.lang.annotation.Target;
    6. @Target(ElementType.METHOD)
    7. @Retention(RetentionPolicy.RUNTIME)
    8. public @interface MyLog {
    9. String desc();
    10. }

     2、配置spring-context.xml

    1. "1.0" encoding="UTF-8"?>
    2. "http://www.springframework.org/schema/beans"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xmlns:context="http://www.springframework.org/schema/context"
    5. xmlns:tx="http://www.springframework.org/schema/tx"
    6. xmlns:aop="http://www.springframework.org/schema/aop"
    7. xsi:schemaLocation="http://www.springframework.org/schema/beans
    8. http://www.springframework.org/schema/beans/spring-beans.xsd
    9. http://www.springframework.org/schema/context
    10. http://www.springframework.org/schema/context/spring-context.xsd
    11. http://www.springframework.org/schema/tx
    12. http://www.springframework.org/schema/tx/spring-tx.xsd
    13. http://www.springframework.org/schema/aop
    14. http://www.springframework.org/schema/aop/spring-aop.xsd">
    15. <import resource="spring-mybatis.xml">import>
    16. package="com.xzs"/>

    3、应用注解

    1. package com.xzs.annotation.aop;
    2. import org.aspectj.lang.JoinPoint;
    3. import org.aspectj.lang.annotation.Aspect;
    4. import org.aspectj.lang.annotation.Before;
    5. import org.aspectj.lang.annotation.Pointcut;
    6. import org.aspectj.lang.reflect.MethodSignature;
    7. import org.slf4j.Logger;
    8. import org.slf4j.LoggerFactory;
    9. import org.springframework.stereotype.Component;
    10. @Component
    11. @Aspect
    12. public class MyLogAspect {
    13. private static final Logger logger = LoggerFactory.getLogger(MyLogAspect.class);
    14. @Pointcut("@annotation(com.xzs.annotation.aop.MyLog)")
    15. private void MyValid() {
    16. }
    17. @Before("MyValid()")
    18. public void before(JoinPoint joinPoint) {
    19. MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    20. logger.debug("[" + signature.getName() + " : start.....]");
    21. System.out.println("[" + signature.getName() + " : start.....]");
    22. MyLog myLog = signature.getMethod().getAnnotation(MyLog.class);
    23. logger.debug("【目标对象方法被调用时候产生的日志,记录到日志表中】:" + myLog.desc());
    24. System.out.println("【目标对象方法被调用时候产生的日志,记录到日志表中】:" + myLog.desc());
    25. }
    26. }

     4、Controller层代码

    1. package com.xzs.web;
    2. import com.xzs.annotation.aop.MyLog;
    3. import org.springframework.stereotype.Component;
    4. import org.springframework.web.bind.annotation.RequestMapping;
    5. @Component
    6. @RequestMapping("/log")
    7. public class LogController {
    8. @RequestMapping("/log")
    9. @MyLog(desc = "这是结合spring aop知识,讲解自定义注解应用的一个案例")
    10. public void testLogAspect() {
    11. System.out.println("这里随便来点啥,最好是唱跳rap");
    12. }
    13. }

     结果:

  • 相关阅读:
    Linux UWB Stack实现——MCPS通道访问
    还不会小程序开发?适用于新手、前端、后端、全栈的小程序开发保姆级教程!
    Set集合源码分析
    安卓手机浏览器怎么选择?多御浏览器有什么功能
    地球的某一片红薯地中秋圆《乡村振兴战略下传统村落文化旅游设计》——旅行季许少辉八月新书辉少许想象和世界一样宽广
    【Linux】动态库与静态库的底层比较
    利用CGI (C)及HTML实现PC本地文件的上传功能
    汽车工况电量计算-转速扭矩图
    WWW2022|京东提出变分embedding学习框架VELF解决CTR预估冷启动问题
    nginx配置详解
  • 原文地址:https://blog.csdn.net/weixin_72997875/article/details/132914153