• SpringMVC自定义注解


                                                                            目录

    一,Java注解简介

    1.java注解的定义

    2.Java注解分类

    2.1JDK基本注解

    2.2JDK元注解

    2.3自定义注解

    二,自定义注解 

    如何自定义注解?

    三,Aop自定义注解的应用

    四,总结


    一,Java注解简介

    1.java注解的定义

    Java注解是附加在代码中的一些元信息,用于一些工具在编译、

    运行时进行解析和使用,起到说明、配置的功能。 注解相关类都

    包含在java.lang.annotation包中。

    2.Java注解分类

    2.1JDK基本注解

    @Override(重写)

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

    2.2JDK元注解

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

    2.3自定义注解

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

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

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

    二,自定义注解 

    如何自定义注解?

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

    例如:SpringMVC已经定义好的:RequestMapping注解

    @interface 是修饰注解类

    @Target(决定自定义注解用在哪)

    //ElementType.TYPE 指注解可以用在类上面
    //ElementType.METHOD 指注解可以用在属性上面
    //ElementType.FIELD 指用在方法上面

    @Retention(定义注解的保留策略)
    //RetentionPolicy.SOURCE注解仅存在于源码中,在class字节码文件中不包含
    //RetentionPolicy.CLASS默认的保留策略,注解会在class字节码文件中存在,但运行时无法获得
    //RetentionPolicy.RUNTIME注解会在class字节码文件中存在,在运行时可以通过反射获取到
     

    在注解类中定义的属性方法,都称为注解类的属性,我们接下来使用我们自定义的注解进行属性的使用,其中注解的属性为value时是可以省略的一般都会给一个default默认值

    例如创建一个MyAnnotation1将其定义为可用在类、方法以及参数上:

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

    MyAnnotation2:可用在方法上:

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

    MyAnnotation3:注解可以用在方法上,相比较MyAnnotation2多了一个注解@Inherited(可继承)

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

    测试类:

    Demo1测试类:

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

    Demo1Test:

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

     Demo1目的:我们用来获取类注释上的类与方法上的注解值:

     运行list方法结果:

    运行edit方法结果:

     Demo2目的:我们用来展示获取类属性上的注解属性值

    Demo2测试类:

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

    Demo2Test:

    1. package com.liyongan.annotation.demo2;
    2. import org.junit.jupiter.api.Test;
    3. public class Demo2Test {
    4. @Test
    5. public void test1() throws Exception {
    6. TestAnnotation msg1 = Demo2.class.getDeclaredField("msg1").getAnnotation(TestAnnotation.class);
    7. System.out.println(msg1.value());
    8. System.out.println(msg1.what());
    9. }
    10. @Test
    11. public void test2() throws Exception{
    12. TestAnnotation msg2 = Demo2.class.getDeclaredField("msg2").getAnnotation(TestAnnotation.class);
    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(msg3.value());
    20. System.out.println(msg3.what());
    21. }
    22. @Test
    23. public void test4() throws Exception{
    24. TestAnnotation msg4 = Demo2.class.getDeclaredField("msg4").getAnnotation(TestAnnotation.class);
    25. System.out.println(msg4.value());
    26. System.out.println(msg4.what());
    27. }
    28. }

      运行test1方法结果:

     

     运行test2方法结果:

     

     运行test3方法结果:

      运行test4方法结果:

    Demo3目的:我们用来展示获得获得属性上自定义注释中的内容:

    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. }

    IsNotNull:

    1. package com.liyongan.annotation.demo3;
    2. import com.liyongan.annotation.demo3.Demo3;
    3. import java.lang.annotation.*;
    4. import java.lang.reflect.Method;
    5. import java.lang.reflect.Parameter;
    6. /**
    7. * 非空注解:使用在方法的参数上,false表示此参数可以为空,true不能为空
    8. */
    9. @Documented
    10. @Target({ElementType.PARAMETER})
    11. @Retention(RetentionPolicy.RUNTIME)
    12. public @interface IsNotNull {
    13. boolean value() default false;
    14. }

     Demo3Test:

    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. }

    运行test1方法结果:

     运行test2方法结果:

     运行test3方法结果:

    三,Aop自定义注解的应用

    MyLog自定义注解类

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

    MyLogAspect切面类

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

    Controller层

    1. @Controller
    2. public class LogController {
    3. @RequestMapping("/mylog")
    4. @MyLog(desc = "这是结合spring aop知识,讲解自定义注解应用的一个案例")
    5. public void testLogAspect(){
    6. System.out.println("Tomcat运行乱码解决了!!!!");
    7. }
    8. }

    运行结果:

    我们所编写的自定义注解类就可以走切面类。

    四,总结

    自定义注解可以用于多种场景。比如,我们可以创建一个自定义注解来限制请求的访问权限,或者用于数据验证、日志记录等。为了定义自定义注解,我们需要使用Java的@interface关键字,它表明我们正在定义一个注解。注解中可以定义属性,在使用注解时可以设置这些属性的值。

    在Spring MVC中,我们可以自定义注解并将其应用到控制器的处理方法上,以实现某些特定的功能。比如,我们可以定义一个自定义的权限注解,来限制用户访问某个特定的处理方法。我们可以通过在注解中定义相关属性,如角色名称、权限级别等,然后在控制器方法上使用该注解。

  • 相关阅读:
    回溯法就是学不会2 —— 括号生成问题
    Linux高性能服务器——定时器
    【C语言】转圈报数问题(三种方法--指针,数组)
    主存储器与CPU的连接
    AtomicInteger类简介说明
    Android 9.0 10.0 Launcher3 时钟动态图标的定制化(时钟动态图标)
    无涯教程-JavaScript - CONVERT函数
    K8S | Deployment应用编排
    DevChat助手:在数据库及数据分析上面的应用实践
    工业机器人“智能制造产线6”教学案例
  • 原文地址:https://blog.csdn.net/m0_73647713/article/details/132889113