• SpringMVC自定义注解---[详细介绍]


    一,对于SpringMVC自定义注解概念

           是一种特殊的 Java 注解,它允许开发者在代码中添加自定义的元数据,并且可以在运行时使用反射机制来获取和处理这些信息。在 Spring MVC 中,自定义注解通常用于定义控制器、请求处理方法、参数或者其他相关组件的行为

    创建和使用由开发者自行编写,可以根据具体需求定义注解元素,并编写相应的注解处理器和逻辑来处理注解可用于标记特定的类、方法或参数

    1.2 java注解的分类(主三种)

    基本注解:

    @Override:用于标记一个方法覆盖了父类或接口的方法。

    @Deprecated用于标记一个类、方法或字段已经过时,不推荐使用。

    @SuppressWarnings(value = "unchecked")用于抑制编译器产生的警告信息

    元注解:

    @Retention指定注解的生命周期,包括 RetentionPolicy.SOURCERetentionPolicy.CLASS 和 RetentionPolicy.RUNTIME

    @Target指定注解的应用目标,包括 ElementType.TYPEElementType.FIELD

    ElementType.METHOD 等。

    @Documented指示注解是否包含在 Java 文档中。

    @Inherited指示注解是否可以被继承。

    @Repeatable指示注解可以多次应用于同一元素。

    注:可以指定多个位置,例如:
    @Target({ElementType.METHOD, ElementType.TYPE}),也就是此注解可以在方法和类上面使用

    @Inherited:指定被修饰的Annotation将具有继承性

    @Documented:指定被修饰的该Annotation可以被javadoc工具提取成文档.

    自定义注解:

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

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

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

    注意:自定义注解只是一种提供元数据的机制,具体的处理逻辑需要通过注解处理器来实现。在使用自定义注解时,需要编写注解处理器来解析注解,并执行相应的行为。

    1.3 如何使用自定义注解

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

    二,使用自定义注解

    案例一(获取类与方法上的注解值)

    定义一个Package名为annotation包定义TranscationModel类

    1. package com.Bingzy.annotation;
    2. public enum TranscationModel {
    3. Read, Write, ReadWrite;
    4. private Integer id;
    5. private String name;
    6. public void init1(){
    7. Read.id=1;
    8. Read.name="zs";
    9. }
    10. public void init2(){
    11. Write.id=2;
    12. Write.name="lisi";
    13. }
    14. public void init3(){
    15. ReadWrite.id=3;
    16. ReadWrite.name="wangwu";
    17. }
    18. }

    在annotation包下再创建测试类test01:

    1. package com.Bingzy.annotation;
    2. /**
    3. * @Name BingBing
    4. * @company zking cy
    5. * @create 2023-09-14-19:43
    6. */
    7. public class Test01 {
    8. public static void main(String[] args) {
    9. System.out.println(TranscationModel.Read);
    10. System.out.println(TranscationModel.Write);
    11. System.out.println(TranscationModel.ReadWrite);
    12. }
    13. }

    在annotation包下再创建一个Package包Demo01 方便测试案例一:

    创建三个注解类:

    MyAnnotation1类:

    1. @Target({ElementType.TYPE, ElementType.FIELD,ElementType.METHOD})
    2. @Retention(RetentionPolicy.RUNTIME)
    3. @Documented
    4. public @interface MyAnnotation1 {
    5. String name();
    6. }

    MyAnnotation2类:

    1. @Target(ElementType.METHOD)
    2. @Retention(RetentionPolicy.RUNTIME)
    3. @Documented
    4. public @interface MyAnnotation2 {
    5. TranscationModel model() default TranscationModel.ReadWrite;
    6. }

    MyAnnotation3类:

    1. @Target(ElementType.METHOD)
    2. @Retention(RetentionPolicy.RUNTIME)
    3. @Inherited
    4. @Documented
    5. public @interface MyAnnotation3 {
    6. TranscationModel[] models() default TranscationModel.ReadWrite;
    7. }

    在Demo01包下创建测试类代码

    Demo1:

    1. @MyAnnotation1(name = "abc")
    2. public class Demo1 {
    3. @MyAnnotation1(name = "xyz")
    4. private Integer age;
    5. @MyAnnotation2(model = TranscationModel.Read)
    6. public void list() {
    7. System.out.println("list");
    8. }
    9. @MyAnnotation3(models = {TranscationModel.Read, TranscationModel.Write})
    10. public void edit() {
    11. System.out.println("edit");
    12. }
    13. }

    Demo1Test:

    1. public class Demo1Test {
    2. @Test
    3. public void list() throws Exception {
    4. // 获取类上的注解
    5. MyAnnotation1 annotation1 = Demo1.class.getAnnotation(MyAnnotation1.class);
    6. System.out.println(annotation1.name());//abc
    7. // 获取方法上的注解
    8. MyAnnotation2 myAnnotation2 = Demo1.class.getMethod("list").getAnnotation(MyAnnotation2.class);
    9. System.out.println(myAnnotation2.model());//Read
    10. // 获取属性上的注解
    11. MyAnnotation1 myAnnotation1 = Demo1.class.getDeclaredField("age").getAnnotation(MyAnnotation1.class);
    12. System.out.println(myAnnotation1.name());// xyz
    13. }
    14. @Test
    15. public void edit() throws Exception {
    16. MyAnnotation3 myAnnotation3 = Demo1.class.getMethod("edit").getAnnotation(MyAnnotation3.class);
    17. for (TranscationModel model : myAnnotation3.models()) {
    18. System.out.println(model);//Read,Write
    19. }
    20. }
    21. }

    测试结果:

    案例二(获取类属性上的注解属性值)

    注解类:

    1. @Retention(RetentionPolicy.RUNTIME)
    2. @Target(ElementType.FIELD)
    3. public @interface TestAnnotation {
    4. String value() default "默认value值";
    5. String what() default "这里是默认的what属性对应的值";
    6. }

    测试类Demo2类

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

    Demo2Test:

    1. public class Demo2Test {
    2. @Test
    3. public void test1() throws Exception {
    4. TestAnnotation msg1 = Demo2.class.getDeclaredField("msg1").getAnnotation(TestAnnotation.class);
    5. System.out.println("test1");
    6. System.out.println(msg1.value());
    7. System.out.println(msg1.what());
    8. }
    9. @Test
    10. public void test2() throws Exception{
    11. TestAnnotation msg2 = Demo2.class.getDeclaredField("msg2").getAnnotation(TestAnnotation.class);
    12. System.out.println("test2");
    13. System.out.println(msg2.value());
    14. System.out.println(msg2.what());
    15. }
    16. @Test
    17. public void test3() throws Exception{
    18. TestAnnotation msg3 = Demo2.class.getDeclaredField("msg3").getAnnotation(TestAnnotation.class);
    19. System.out.println("test3");
    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("test4");
    27. System.out.println(msg4.value());
    28. System.out.println(msg4.what());
    29. }
    30. }

    总结:如果我们注解上没有指定是value还是what默认就是value,如果只想转递一个参数又不想默认是value那就需要指定what=""即可。 

     案例三(获取参数修饰注解对应的属性值)

    注解类:

    1. @Documented
    2. @Target({ElementType.PARAMETER})
    3. @Retention(RetentionPolicy.RUNTIME)
    4. public @interface IsNotNull {
    5. boolean value() default false;
    6. }

    测试类Demo3:

    1. public class Demo3 {
    2. public void hello1(@IsNotNull(true) String name) {
    3. System.out.println("hello:" + name);
    4. }
    5. public void hello2(@IsNotNull String name) {
    6. System.out.println("hello:" + name);
    7. }
    8. }

    测试类DemoTest3:

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

    运行结果: 

     

    总结:这个案例像不像我们的注解@RequestParam必须传递参数,除非指定required为false就可与不传参数,我们这个案例也是如此。 

    三,Aop自定义注解

    定义一个注解类:

    1. @Target(ElementType.METHOD)
    2. @Retention(RetentionPolicy.RUNTIME)
    3. public @interface MyLog {
    4. String desc();
    5. }

    切面类:

    1. @Component
    2. @Aspect
    3. public class MyLogAspect {
    4. private static final Logger logger = LoggerFactory.getLogger(MyLogAspect.class);
    5. /**
    6. * 只要用到了com.javaxl.p2.annotation.springAop.MyLog这个注解的,就是目标类
    7. */
    8. @Pointcut("@annotation(com.Bingzy.annotation.aop.MyLog)")
    9. private void MyValid() {
    10. }
    11. @Before("MyValid()")
    12. public void before(JoinPoint joinPoint) {
    13. MethodSignature signature = (MethodSignature) joinPoint.getSignature();
    14. logger.debug("[" + signature.getName() + " : start.....]");
    15. System.out.println("[" + signature.getName() + " : start.....]");
    16. MyLog myLog = signature.getMethod().getAnnotation(MyLog.class);
    17. logger.debug("【目标对象方法被调用时候产生的日志,记录到日志表中】:"+myLog.desc());
    18. System.out.println("【目标对象方法被调用时候产生的日志,记录到日志表中】:" + myLog.desc());
    19. }
    20. }

    Controller层:

    1. @Controller
    2. public class LogController {
    3. @RequestMapping("/mylog")
    4. @MyLog(desc = "这是结合spring aop知识,讲解自定义注解应用的一个案例")
    5. public void testLogAspect(){
    6. System.out.println("这里随便来点啥");
    7. }
    8. }

    运行结果:

  • 相关阅读:
    20240309web前端_第四次作业_完成随机点名程序
    Java代码中如何将一个String转int呢?
    C语言实现http请求器
    机器学习西瓜书+南瓜书吃瓜教程学习笔记第五章神经网络
    mysql 触发器
    还在拼冗长的WhereIf吗?100行代码解放这个操作
    C++——多态底层原理
    内存与IO访问原理
    【JavaWeb】-- Servlet优化(dispatcherServlet)
    1、Spring IOC的理解要点
  • 原文地址:https://blog.csdn.net/m0_73192864/article/details/132888045