Java如何自定义注解及在SpringBoot中的应用

注解

注解(Annotation),也叫元数据。一种代码级别的说明。它是JDK1.5及以后版本引入的一个特性,与类、接口、枚举是在同一个层次。它可以声明在包、类、字段、方法、局部变量、方法参数等的前面,用来对这些元素进行说明,注释。注解相关类都包含在java.lang.annotation包中。
注解可以看作是一种特殊的标记,可以用在方法、类、参数和包上,程序在编译或者运行时可以检测到这些标记而进行一些特殊的处理。

Java注解分类:基本注解,元注解,自定义注解
JDK基本注解:

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

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注解的注解,所标记的类的子类也会拥有这个注解。
@Inherited:指定被修饰的Annotation将具有继承性

//表明该注解标记的元素可以被Javadoc 或类似的工具文档化
@Documented:指定被修饰的该Annotation可以被javadoc工具提取成文档.

在这里插入图片描述
由此可见生命周期关系:SOURCE < CLASS < RUNTIME,我们一般用RUNTIME

其中最重要的是:

@Retention(RetentionPolicy.RUNTIME)
@Target:指定被修饰的Annotation可以放置的位置(被修饰的目标)

自定义注解

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

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

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

反射机制

反射最重要的就是类,一切反射的基础是类
静态语言 VS 动态语言

动态语言
是一类在运行时可以改变其结构的原因:例如新的函数、对象、甚至代码可以被引进,已有的函数可以被删除或是其他结构上的变化。通俗点说就是在运行时代码可以根据某些条件改变自身结构
主要动态语言:Object-c、C#、JavaScript、php、Python等

静态语言
与动态语言相对应的,运行时结构不可变的语言就是静态语言。如Java、C、C++。
Java不是动态语言,但Java可以称之为"准动态语言"。即Java有一定的动态性,我们可以利用反射机制获得类似语言的特性。Java的动态性让编程的时候更加灵活!

自定义注解参数可以支持的类型

1.八大基本数据类型

2.String类型

3.Class类型

4.enum类型

5.Annotation类型

6.以上所有类型的数组

如何处理注解

注解可以分两个主要阶段进行处理:
编译时处理
在编译时,注解可以由注解处理器处理 - 这些是特殊的类,可以读取注解信息并生成附加源代码、文档或其他资源。注解处理器是 Java 注解处理工具 (APT) 的一部分。

编译时处理的一个示例是@Override注解,Java 编译器使用它来验证某个方法确实覆盖了超类中的方法。

运行时处理
保留策略为RUNTIME 的注解在运行时可供 JVM 使用。这允许运行时反射——代码可以检查自己的注解,并根据这些注解的存在和配置执行不同步骤。

Java 中的注解是通过动态代理和接口实现的。当您查询元素上的注解时,返回的不是注解接口的直接实例,而是实现注解接口的代理。

自定义注解

定义注解:

要创建自定义注解,从@interface关键字开始。这向 Java 编译器发出信号,表明正在声明注解。以下是定义基本自定义注解的方法:

package com.wsl.annotitiondemo.annotation;

import java.lang.annotation.*;

/**
 * packageName com.wsl.annotitiondemo.annotation  OperationLog
 *
 * @author victor
 * @version JDK 8
 * @date 2024/7/9
 * @description
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OperationLog {

    String username() default "";
    OperationType type();
    String content() default "";

}

package com.wsl.annotitiondemo.annotation;

/**
 * packageName com.wsl.annotitiondemo.annotation  OperationType
 *
 * @author victor
 * @version JDK 8
 * @date 2024/7/9
 * @description
 */
public enum OperationType {
    //
    FIND(0,"find") ,
    //
    ADD(1,"add") ,
    //
    UPDATE(2,"update"),
    //
    DELETE(3,"delete");

    private final int number;
    private final String description;

    OperationType(int number,String description){
        this.number = number;
        this.description = description;
    }

    public int getNumber() {
        return number;
    }

    public String getDescription() {
        return description;
    }
}

在这个定义中:

@Retention(RetentionPolicy.RUNTIME)指定该注解在运行时可用于反射。
@Target({ElementType.METHOD, ElementType.TYPE})表明该注解既可以用于类声明,也可以用于方法声明。

应用注解:

定义注解后,您可以将其应用到代码中。例如:

package com.wsl.annotitiondemo.annotation;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Optional;

/**
 * packageName com.wsl.annotitiondemo.annotation  ComLogAspect
 *
 * @author victor
 * @version JDK 8
 * @date 2024/7/9
 * @description TODO
 */
@Component
@Aspect
public class ComLogAspect {

    //配置织入点
    @Pointcut("@annotation(com.wsl.annotitiondemo.annotation.OperationLog)")
    public void logPointCut(){

    }

    //@Before: 前置通知, 在方法执行之前执行,这个通知不能阻止连接点前的执行(除非它抛出一个异常)

    @Before("logPointCut()")
    public  void doBefore(JoinPoint joinPoint){
        System.out.println("dobefore");
        handleLog(joinPoint,null);
    }
//
//    //@After: 后置通知, 在方法执行之后执行(不论是正常返回还是异常退出)。
//    @After(value = "logPointCut() && @annotation(operationLog)")
//    public  void doAfter(OperationLog operationLog){
//
//    }

    /**
     * @Around: 包围一个连接点(join point)的通知,如方法调用。这是最强大的一种通知类型。
     * 环绕通知可以在方法调用前后完成自定义的行为。
     * 它也会选择是否继续执行连接点或直接返回它们自己的返回值或抛出异常来结束执行。
     * */
    @Around("logPointCut()")
    public  Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object[] args = pjp.getArgs();
        System.out.println(Arrays.toString(args));
        Object ob = pjp.proceed();   // ob 为方法的返回值
        System.out.println("耗时 : " + (System.currentTimeMillis() - startTime) + "ms");
        return ob;
    }


    //@AfterRunning:返回通知, 在方法正常返回结果之后执行
    @AfterReturning(pointcut = "logPointCut()")
    public  void doAfterRunning(JoinPoint joinPoint){
        System.out.println("方法执行完执行...afterRunning");
        handleLog(joinPoint,null);
    }

    //@AfterThrowing: 异常通知, 在方法抛出异常之后。
    @AfterThrowing(value = "logPointCut()",throwing = "e")
    public  void doAfterThrowing(JoinPoint joinPoint,Exception e){
        handleLog(joinPoint,e);
    }



    private void handleLog(JoinPoint joinPoint,Exception ex){
        try {
            OperationLog operationLog = getAnnotationLog(joinPoint);
            if (operationLog==null){
                return ;
            }
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            OperationType type = operationLog.type();
            String content = operationLog.content();
            String username = operationLog.username();
            System.out.println("==className=="+className);
            System.out.println("==methodName=="+methodName);
            System.out.println("==content=="+content);
            System.out.println("==username=="+username);

        }catch (Exception es){
            es.printStackTrace();
        }
    }

    private static OperationLog getAnnotationLog(JoinPoint joinPoint) throws Exception{
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature= (MethodSignature)signature;
        Method method = methodSignature.getMethod();
        if (method!=null){
            return method.getAnnotation(OperationLog.class);
        }
        return null;
    }




}

处理注解

自定义注解可以通过两种方式处理:在编译时使用注解处理器或在运行时使用反射。

编译时处理
要在编译时处理注解,通常会使用 Java 注解处理 API。注解处理器是一种检查和处理 Java 代码中注解类型的工具。这是注解处理器的骨架结构:

import javax.annotation.processing.AbstractProcessor; 
import javax.annotation.processing.RoundEnvironmentimport javax.lang.model.element.TypeElement; 
import javax.lang.model.element.Element; 
import java.util.Setpublic  class  MyAnnotationProcessor  extends  AbstractProcessor { 

    @Override 
    public  boolean  process (Set<? extends TypeElement> comments, RoundEnvironment roundEnv) { 
        for (TypeElement comment : comments) { 
            for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) { 
                // 处理
            } 
        }
        返回 true} 
}

运行时处理
对于运行时处理,您将使用反射,如上一节所示。这是一个重点关注我们的自定义注解的简短示例:

import java.lang.reflect.Methodpublic  class  AnnotationRuntimeProcessor { 

    public  static  void  processAnnotations (Class<?> clazz)  throws Exception { 
        if (clazz.isAnnotationPresent(MyCustomAnnotation.class)) { 
            // 类级注解
            MyCustomAnnotation  classAnnotation  = clazz.getAnnotation(MyCustomAnnotation.class); } 
            System.out.println( "Class " + clazz.getSimpleName() + " 注解为: " + classAnnotation.author()); 
        } 

        for (Method method : clazz.getDeclaredMethods()) { 
            if (method.isAnnotationPresent(MyCustomAnnotation.class)) { 
                // 方法级注解
                MyCustomAnnotation  methodAnnotation  = method.getAnnotation(MyCustomAnnotation.class); 
                System.out.println( "方法 " + method.getName() + " 注解为: " + methodAnnotation.author()); 
            } 
        } 
    } 

    public  static  void  main (String[] args)  throws Exception { 
        processAnnotations(SomeClass.class); 
    } 
}

在 Java 中创建和使用自定义注解是增强代码的有效方法。它允许更清晰、更具描述性的代码,并在编译时和运行时实现某些任务的自动化。通过定义、应用和处理自定义注解,您可以创建更具可读性、可维护性和表现力的 Java 应用程序。

测试:

package com.wsl.annotitiondemo.controller;

import com.wsl.annotitiondemo.annotation.OperationLog;
import com.wsl.annotitiondemo.annotation.OperationType;
import org.springframework.stereotype.Component;

/**
 * packageName com.wsl.annotitiondemo.controller  LogController
 *
 * @author victor
 * @version JDK 8
 * @date 2024/7/9
 * @description
 */
@Component
public class LogController {

    @OperationLog(username = "wsl",type = OperationType.ADD,content ="新增内容")
    public void testlog(){
        System.out.println("第一个测试");
    }
}

package com.wsl.annotitiondemo.controller;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;


/**
 * packageName com.wsl.annotitiondemo.controller  LogControllerTest
 *
 * @author victor
 * @version JDK 8
 * @date 2024/7/9
 * @description TODO
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class LogControllerTest {

    @Autowired
    private LogController logController;

    @Test
    public  void  test01(){
        logController.testlog();

    }
}

添加的pom文件:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.wsl</groupId>
    <artifactId>annotitiondemo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>annotitiondemo</name>
    <description>annotitiondemo</description>
    <url/>
    <licenses>
        <license/>
    </licenses>
    <developers>
        <developer/>
    </developers>
    <scm>
        <connection/>
        <developerConnection/>
        <tag/>
        <url/>
    </scm>
    <properties>
        <java.version>22</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-test</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

总结

注解是 Java 中的一项强大功能,它允许开发人员编写更清晰、更具表现力的代码。它们可用于多种目的,从向编译器提供提示,到启用复杂的运行时基于反射的逻辑。通过理解和利用自定义注解,Java 开发人员可以创建更健壮、可维护且防错的应用程序。

创建自定义注解涉及使用关键字定义注解、指定任何默认元素值以及使用和元注解@Retention,@Target,确定可以应用注解的位置。定义后,自定义注解可以在编译时或运行时使用反射进行处理,从而提供强大的机制来扩展 Java 语言的功能。

参考:
https://www.jb51.net/program/315875pzt.htm
https://zhuanlan.zhihu.com/p/668951448
https://www.jianshu.com/p/296272f4358f
@EnableAspectJAutoProxy(exposeProxy=true,proxyTargetClass=true)
https://blog.csdn.net/Lwcxz1006/article/details/132111786

  • 22
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
@JsonProperty 是 Jackson 库的注解,用于给 Java 对象的属性指定一个不同于属性名的别名,在序列化和反序列化过程起作用。 如果 @JsonProperty 注解不生效,可能有以下几个原因: 1. 未正确导入 Jackson 库:在使用 @JsonProperty 注解之前,需要确保已经正确导入了 Jackson 库的相关类。可以通过在项目的依赖管理工具(如 Maven 或 Gradle)添加正确的依赖项来解决此问题。 2. 忘记给属性添加 @JsonProperty 注解:在需要使用 @JsonProperty 注解的属性上,确保已经正确地添加了该注解。例如: ```java @JsonProperty("newPropertyName") private String oldPropertyName; ``` 3. 序列化或反序列化配置错误:Jackson 库提供了多种方式来配置序列化和反序列化行为,包括 ObjectMapper 的配置以及全局配置。如果没有正确配置 Jackson 库的相关参数,@JsonProperty 注解可能不会生效。可以通过检查配置并进行必要的更改来修复此问题。 4. 对象访问修饰符问题:Jackson 默认只序列化公共字段和 getter 方法,如果属性是私有的或者没有相应的 getter 方法,@JsonProperty 注解可能无法生效。可以尝试将属性设置为公共,或者添加相应的 getter 方法。 相关问题: 1. 除了 @JsonProperty 注解外,还有哪些 Jackson 注解可用于控制序列化和反序列化过程? 2. 如何在 Jackson 序列化过程忽略某个属性? 3. 如何自定义 Jackson 序列化和反序列化的行为? 4. 什么是 Jackson 的 Mixin 注解,如何使用它来修改序列化和反序列化行为? 5. 在 Spring Boot 如何配置 Jackson 库的属性和行为? 6. 除了 Jackson,还有哪些 Java 序列化库可供选择?它们之间有什么区别?
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值