• “高级Java注解的简介及应用“



    在这里插入图片描述

    引言

    在Java开发中,注解是一种非常重要的语言特性,它们可以为代码提供额外的信息和元数据。本文将介绍Java注解的基本概念,并深入探讨自定义注解和AOP自定义注解的应用。

    1. Java注解简介

    1.1 什么是注解

    注解是一种用于为程序代码添加元数据的方式。它们可以用于描述类、方法、字段等程序元素的特性和行为。Java注解使用@符号作为前缀,并可以包含参数和值。

    1.2 注解的作用

    提供额外的元数据:注解可以为代码提供额外的信息,如作者、版本号、创建日期等。
    编译时检查:注解可以在编译时对代码进行静态检查,以确保代码的正确性和一致性。
    运行时处理:注解可以在运行时通过反射机制获取和处理,以实现一些特定的功能。

    1.3 常见的Java注解

    @Override:用于标识方法覆盖父类的方法。
    @Deprecated:用于标识已过时的方法或类。
    @SuppressWarnings:用于抑制编译器警告。
    @FunctionalInterface:用于标识函数式接口。

    • Java注解分类
    JDK基本注解
    JDK元注解
    自定义注解
    
    • 1
    • 2
    • 3
    • JDK基本注解
    @Override
    重写
    
    @SuppressWarnings(value = "unchecked")
    压制编辑器警告
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 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工具提取成文档.
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 自定义注解
    注解分类(根据Annotation是否包含成员变量,可以把Annotation分为两类):
    
    标记Annotation:
    没有成员变量的Annotation; 这种Annotation仅利用自身的存在与否来提供信息
    
    元数据Annotation:
    包含成员变量的Annotation; 它们可以接受(和提供)更多的元数据;
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 如何自定义注解?
    使用@interface关键字, 其定义过程与定义接口非常类似, 需要注意的是:
       Annotation的成员变量在Annotation定义中是以无参的方法形式来声明的, 其方法名和返回值类型定义了该成员变量的名字和类型,
       而且我们还可以使用default关键字为这个成员变量设定默认值;
    
    • 1
    • 2
    • 3

    2. 自定义注解案例

    • 案例一

    demo1

    package com.yuan.annotation.demo1;
    
    /**
     *
     * 获取类与方法上的注解值
     */
    @MyAnnotation1(name = "abc")
    public class Demo1 {
    
        @MyAnnotation1(name = "xyz")
        private Integer age;
    
        @MyAnnotation2(model = TranscationModel.Read)
        public void list() {
            System.out.println("list");
        }
    
        @MyAnnotation3(models = {TranscationModel.Read, TranscationModel.Write})
        public void edit() {
            System.out.println("edit");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    Demo1Test

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

    MyAnnotation1

    package com.yuan.annotation.demo1;
    
    import java.lang.annotation.*;
    
    /**
     * MyAnnotation1注解可以用在类、接口、属性、方法上
     * 注解运行期也保留
     * 不可继承
     */
    @Target({ElementType.TYPE, ElementType.FIELD,ElementType.METHOD})
    @Retention(RetentionPolicy.RUNTIME)
    @Inherited
    @Documented
    public @interface MyAnnotation1 {
        String name();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    MyAnnotation2

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

    MyAnnotation3

    package com.yuan.annotation.demo1;
    
    import java.lang.annotation.*;
    
    /**
     * MyAnnotation3注解可以用在方法上
     * 注解运行期也保留
     * 可继承
     */
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    @Inherited
    @Documented
    public @interface MyAnnotation3 {
        TranscationModel[] models() default TranscationModel.ReadWrite;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    TranscationModel

    package com.yuan.annotation.demo1;
    
    public enum  TranscationModel {
        Read, Write, ReadWrite
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    测试结果
    在这里插入图片描述

    在这里插入图片描述

    • 案例二
      Demo2
    package com.yuan.annotation.demo2;
    
    /**
     * 获取类属性上的注解属性值
     */
    public class Demo2 {
        @TestAnnotation(value = "这就是value对应的值_msg1", what = "这就是what对应的值_msg1")
        private static String msg1;
    
        @TestAnnotation("这就是value对应的值1")
        private static String msg2;
    
        @TestAnnotation(value = "这就是value对应的值2")
        private static String msg3;
    
        @TestAnnotation(what = "这就是what对应的值")
        private static String msg4;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    Demo2Test

    package com.yuan.annotation.demo2;
    
    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());
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    TestAnnotation

    package com.yuan.annotation.demo2;
    
    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属性对应的值";
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 案例三
    • IsNotNull
    package com.yuan.annotation.demo3;
    
    import java.lang.annotation.*;
    
    /**
     * 非空注解:使用在方法的参数上,false表示此参数可以为空,true不能为空
     */
    @Documented
    @Target({ElementType.PARAMETER})
    @Retention(RetentionPolicy.RUNTIME)
    public @interface IsNotNull {
        boolean value() default false;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    Demo3

    package com.yuan.annotation.demo3;
    
    /**
     *
     * 获取参数修饰注解对应的属性值
     */
    public class Demo3 {
    
        public void hello1(@IsNotNull(true) String name) {
            System.out.println("hello:" + name);
        }
    
        public void hello2(@IsNotNull String name) {
            System.out.println("hello:" + name);
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    Demo3Test

    package com.yuan.annotation.demo3;
    
    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(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(annotation.value());//false
                }
            }
        }
    
        @Test
        public void hello3() throws Exception {
    //        模拟浏览器传递到后台的参数 解读@requestParam
            String name = "zs";
            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);
                    }
                }
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

    3. AOP自定义注解的应用

    3.1 AOP简介

    AOP(面向切面编程)是一种编程范式,它通过将横切关注点(如日志记录、事务管理)从业务逻辑中分离出来,以提高代码的模块化和可维护性。

    3.2 AOP自定义注解

    我们可以结合AOP和自定义注解,实现在特定方法或类上添加切面逻辑的功能。通过定义一个切面类,并在目标方法上添加自定义注解,可以在运行时动态地执行切面逻辑。
    MyLog

    package com.yuan.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();
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    MyLogAspect

    package com.yuan.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);
    
        /**
         * 只要用到了MyLog这个注解的,就是目标类
         */
        @Pointcut("@annotation(com.yuan.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());
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    LogController

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

    applicationContext.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">
        <!--1. 注解式开发 -->
        <!-- 注解驱动 -->
        <context:annotation-config/>
        <!-- 用注解方式注入bean,并指定查找范围:com.javaxl.ssh2及子子孙孙包-->
        <context:component-scan base-package="com.yuan"/>
        <!--开启动态代理-->
        <aop:aspectj-autoproxy />
    
    </beans>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    在这里插入图片描述

    总结

    本文介绍了Java注解的基本概念,并详细讨论了自定义注解和AOP自定义注解的应用。通过合理使用注解,我们可以为代码添加更多的元数据,并实现一些特定的功能。注解是Java开发中不可或缺的一部分,希望本文对您有所帮助。
    以上是本文的内容,希望能够对您理解高级Java注解的应用有所帮助。感谢阅读!

  • 相关阅读:
    HTML简单介绍
    CDH6.3.2之Kafka配置和命令
    基于Expression Lambda表达式树的通用复杂动态查询构建器——《构思篇二》已开源
    git 上传大文件
    Abnova丨ACTN4 DNA 探针解决方案
    Ansible自动化部署
    读《大话数据结构》溢彩加强版
    Go语言 并发与通道
    【技术追踪】SAM(Segment Anything Model)代码解析与结构绘制之Mask Decoder
    vue实现全屏screenfull-封装组件
  • 原文地址:https://blog.csdn.net/2201_75869073/article/details/132900785