• SpringMVC之定义注解强势来袭!!!


    目录

    一.原生注解

            1.1原生注解的分类

    二.注解的案例

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

            2.2  案例二(获取类属性上的注解属性值,默认值的赋予)

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

    三.AOP结合自定义注解案例⭐⭐


    一.原生注解

            Java注解是一种元数据,它提供了在Java代码中插入附加信息的方式。注解可以用于类、方法、变量、参数等的声明上,用于描述、标记或配置程序代码,而不改变代码的实际逻辑。

            Java注解使用@符号作为前缀,紧跟着注解名称,并可以包含一系列的参数。注解可以通过编译器处理或在运行时解析。

            1.1原生注解的分类

                            1.1 .1JDK基本注解:                                         

                @Override:用于标记方法覆盖了父类的方法。

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

                @SuppressWarnings:用于抑制编译器警告。

                 ⭐⭐  1.1.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)                 方法参数

                                            。。。。。


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

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

                            1.1.3 自定义注解:

    1.  标记注解:没有成员变量的Annotation; 这种Annotation仅利用自身的存在与否来提供信息
    2. 元数据注解:包含成员变量的Annotation; 它们可以接受(和提供)更多的元数据;

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

    二.注解的案例

            先来导入自定义注解的pom依赖:

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <project xmlns="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. <modelVersion>4.0.0</modelVersion>
    5. <parent>
    6. <groupId>org.springframework.boot</groupId>
    7. <artifactId>spring-boot-starter-parent</artifactId>
    8. <version>2.3.7.RELEASE</version>
    9. <relativePath/> <!-- lookup parent from repository -->
    10. </parent>
    11. <groupId>com.yinzi</groupId>
    12. <artifactId>spboottest01</artifactId>
    13. <version>0.0.1-SNAPSHOT</version>
    14. <name>spboottest01</name>
    15. <description>Demo project for Spring Boot</description>
    16. <properties>
    17. <java.version>8</java.version>
    18. </properties>
    19. <dependencies>
    20. <dependency>
    21. <groupId>org.springframework.boot</groupId>
    22. <artifactId>spring-boot-starter-web</artifactId>
    23. </dependency>
    24. <dependency>
    25. <groupId>org.springframework.boot</groupId>
    26. <artifactId>spring-boot-starter-test</artifactId>
    27. <!-- <scope>test</scope>-->
    28. </dependency>
    29. </dependencies>
    30. <build>
    31. <plugins>
    32. <plugin>
    33. <groupId>org.springframework.boot</groupId>
    34. <artifactId>spring-boot-maven-plugin</artifactId>
    35. </plugin>
    36. </plugins>
    37. </build>
    38. </project>

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

                    定义一个类:

    1. package com.yinzi.annotation;
    2. public enum TranscationModel {
    3. Read, Write, ReadWrite;//定义三个实例,可以将它看作类
    4. }

            写三个不同的注解:

    1. /**
    2. * MyAnnotation1注解可以用在类、接口、属性、方法上
    3. * 注解运行期也保留
    4. * 不可继承
    5. */
    6. @Target({ElementType.TYPE, ElementType.FIELD,ElementType.METHOD})//用在类、接口、属性、方法上
    7. @Retention(RetentionPolicy.RUNTIME)
    8. @Documented
    9. public @interface MyAnnotation1 {
    10. String name();
    11. }
    12. /**
    13. * MyAnnotation2注解可以用在方法上
    14. * 注解运行期也保留
    15. * 不可继承
    16. */
    17. @Target(ElementType.METHOD)
    18. @Retention(RetentionPolicy.RUNTIME)
    19. @Documented
    20. public @interface MyAnnotation2 {
    21. TranscationModel model() default TranscationModel.ReadWrite;
    22. }
    23. /**
    24. * MyAnnotation3注解可以用在方法上
    25. * 注解运行期也保留
    26. * 可继承
    27. */
    28. @Target(ElementType.METHOD)
    29. @Retention(RetentionPolicy.RUNTIME)
    30. @Inherited
    31. @Documented
    32. public @interface MyAnnotation3 {
    33. TranscationModel[] models() default TranscationModel.ReadWrite;
    34. }


     

          第三步,创建几个方法使用这些注解

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

                    最后,进行测试

     2.2  案例二(获取类属性上的注解属性值,默认值的赋予)

            自定义一个注解,并赋予默认值:

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

            建立类测试:

                    有些两个值都赋予了,有些只赋予了一个

    1. /**
    2. * 获取类属性上的注解属性值
    3. */
    4. public class Demo2 {
    5. @TestAnnotation(value = "这就是value对应的值_msg1", what = "这就是what对应的值_msg1")
    6. private static String msg1;
    7. @TestAnnotation("这就是value对应的值1")//没有指定,默认value
    8. private static String msg2;
    9. @TestAnnotation(value = "这就是value对应的值2")
    10. private static String msg3;
    11. @TestAnnotation(what = "这就是what对应的值")
    12. private static String msg4;
    13. }

            测试结果:

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

                    同样,先建立一个非空注解

    1. /**
    2. * 非空注解:使用在方法的参数上,false表示此参数可以为空,true不能为空
    3. */
    4. @Documented
    5. @Target({ElementType.PARAMETER})
    6. @Retention(RetentionPolicy.RUNTIME)
    7. public @interface IsNotNull {
    8. boolean value() default false;//默认为false
    9. }

                    建立方法,进行测试:

                测试


    三.AOP结合自定义注解案例⭐⭐

            配置相关AOP  pom文件

    1. <dependency>
    2. <groupId>org.springframework.boot</groupId>
    3. <artifactId>spring-boot-starter-aop</artifactId>
    4. </dependency>

             applicationContext.xml

    1. "1.0" encoding="UTF-8"?>
    2. <beans xmlns="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" xmlns:tx="http://www.springframework.org/schema/tx"
    5. xmlns:aop="http://www.springframework.org/schema/aop"
    6. 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">
    7. <context:annotation-config/>
    8. <context:component-scan base-package="com.yinzi"/>
    9. <aop:aspectj-autoproxy />
    10. beans>

                    定义一个标志日志的注解

    1. package com.yinzi.annotation;
    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. /**
    7. * @author yinzi
    8. * 日志注解
    9. */
    10. @Target(ElementType.METHOD)
    11. @Retention(RetentionPolicy.RUNTIME)
    12. public @interface MyLog {
    13. String desc();
    14. }

            然后,我们创建一个切面类 LogAspect,用于实现日志记录的逻辑。

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

                    在方法上运用日志注解

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

            运行结果: 这只是大概的模拟了一下

                    好啦,今天的分享就到这啦!!

  • 相关阅读:
    go语言基础之常量与itoa
    RNA-seq 详细教程:分析流程介绍(1)
    wangeditor5在vue3中的全使用过程(图片上传、附件上传、工具栏配置、编辑器配置)
    重磅!flink-table-store 将作为独立数据湖项目重新加入 Apache
    用HTML+CSS做一个漂亮简单的轻量级图片相册博客网站(web前端期末大作业)
    Linux | 文件描述符理解 | 系统级别的文件操作讲解 | 一切皆文件的由来 | 重定向dup2函数讲解
    Navigation 组件(一) Fragment 跳转
    scss
    多维表格平台盘点 Notion、FlowUs、Airtable、SeaTable、Vika
    第二章:ShardingSphere简介
  • 原文地址:https://blog.csdn.net/YZZdear/article/details/132887973