java如何自定义注解

 更新时间:2024年02月19日 14:28:31   作者:学、渣  
这篇文章主要介绍了java如何自定义注解问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

注解是一种能被添加到java源代码中的元数据,方法、类、参数和包都可以用注解来修饰。

注解可以看作是一种特殊的标记,可以用在方法、类、参数和包上,程序在编译或者运行时可以检测到这些标记而进行一些特殊的处理。

声明一个注解要用到的东西

  • 修饰符:访问修饰符必须为public,不写默认为pubic
  • 关键字:关键字为@interface
  • 注解名称:注解名称为自定义注解的名称,使用时还会用到
  • 注解类型元素:注解类型元素是注解中内容

其次,JDK中还有一些元注解,这些元注解可以用来修饰注解。

主要有:@Target,@Retention,@Document,@Inherited。

@Target 

作用:

用于描述注解的使用范围(即:被描述的注解可以用在什么地方)。

取值有:

@Retention

作用:

表示需要在什么级别保存该注释信息,用于描述注解的生命周期(即:被描述的注解在什么范围内有效)

即:注解的生命周期。

@Document    

作用:

表明该注解标记的元素可以被Javadoc 或类似的工具文档化

@Inherited

作用: 

表明使用了@Inherited注解的注解,所标记的类的子类也会拥有这个注解。

自定义注解中参数可支持的数据类型:

1.八大基本数据类型

2.String类型

3.Class类型

4.enum类型

5.Annotation类型

6.以上所有类型的数组

自定义一个注解,如下所示:

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OperationLog {
 
    String username() default "";
 
    OperationType type();
 
    String content() default "";
 
}

通过AOP加自定义注解简单实现一个操作日志的记录

自定义注解类:

package com.redistext.log;
 
import java.lang.annotation.*;
 
/**
 * @author: maorui
 * @description: TODO
 * @date: 2021/10/27 21:23
 * @description: V1.0
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface OperationLog {
 
    String username() default "admin";
 
    String type(); //记录操作类型
 
    String content() default ""; //记录操作内容
 
}

切面类:

package com.redistext.log;
 
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
 
import java.lang.reflect.Method;
 
/**
 * @author: maorui
 * @description: TODO
 * @date: 2021/10/27 21:29
 * @description: V1.0
 */
@Aspect
@Component("logAspect")
public class LogAspect {
 
    // 配置织入点
    @Pointcut("@annotation(OperationLog)")
    public void logPointCut() {
    }
 
    /**
     * 前置通知 用于拦截操作,在方法返回后执行
     *
     * @param joinPoint 切点
     */
    @AfterReturning(pointcut = "logPointCut()")
    public void doBefore(JoinPoint joinPoint) {
        handleLog(joinPoint, null);
    }
 
    /**
     * 拦截异常操作,有异常时执行
     *
     * @param joinPoint
     * @param e
     */
    @AfterThrowing(value = "logPointCut()", throwing = "e")
    public void doAfter(JoinPoint joinPoint, Exception e) {
        handleLog(joinPoint, e);
    }
 
    private void handleLog(JoinPoint joinPoint, Exception e){
        try {
            // 得到注解
            OperationLog operationLog = getAnnotationLog(joinPoint);
            System.out.println("---------------自定义注解:" + operationLog);
            if (operationLog == null) {
                return;
            }
            // 得到方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            String type = operationLog.type();
            String content = operationLog.content();
            String username = operationLog.username();
            // 打印日志
            System.out.println("操作类型:" + type);
            System.out.println("操作名称:" + content);
            System.out.println("操作人员:" + username);
            System.out.println("类名:" + className);
            System.out.println("方法名:" + methodName);
        } catch (Exception e1) {
            System.out.println("======前置通知异常======");
            e1.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;
    }
 
}

测试类:

package com.redistext.log;
 
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
/**
 * @author: maorui
 * @description: TODO
 * @date: 2021/10/27 21:40
 * @description: V1.0
 */
@RestController
@RequestMapping("/operationLog")
public class OperationLogController {
 
    @OperationLog(type = "add", content = "添加")
    @GetMapping(value = "/add")
    public String addOperation(){
        return "add";
    }
 
    @OperationLog(type = "update", username = "adminFather")
    @GetMapping(value = "/update")
    public String updateOperation(){
        return "update";
    }
 
    @OperationLog(type = "delete", content = "删除", username = "adminMother")
    @GetMapping(value = "/delete")
    public String deleteOperation(){
        return "delete";
    }
 
    @OperationLog(type = "find")
    @GetMapping(value = "/find")
    public String findOperation(){
        return "find";
    }
}

依次调用测试类各个接口,记录的操作日志信息如下:

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

相关文章

  • java判断class子类或父类的实例方法

    java判断class子类或父类的实例方法

    在本篇文章里小编给大家整理的是关于java判断class子类或父类的实例方法,需要的朋友们可以参考学习下。
    2020-02-02
  • Java 详解分析链表的中间节点

    Java 详解分析链表的中间节点

    链表是基本的数据结构之一,面试题中链表占很大一部分,可见链表操作是非常重要的。本篇文章我们来探究一下如何获取链表的中间节点
    2022-01-01
  • Groovy的规则脚本引擎实例解读

    Groovy的规则脚本引擎实例解读

    这篇文章主要介绍了Groovy的规则脚本引擎实例解读,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2023-03-03
  • SpringBoot快速搭建web项目详细步骤总结

    SpringBoot快速搭建web项目详细步骤总结

    这篇文章主要介绍了SpringBoot快速搭建web项目详细步骤总结 ,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-12-12
  • 解决springboot+thymeleaf视图映射报错There was an unexpected error (type=Not Found, status=404)

    解决springboot+thymeleaf视图映射报错There was an unexpected erro

    这篇文章主要介绍了解决springboot+thymeleaf视图映射报错There was an unexpected error (type=Not Found, status=404)问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
    2023-12-12
  • idea进程结束但是项目页面正常运行怎么办

    idea进程结束但是项目页面正常运行怎么办

    这篇文章主要介绍了idea进程结束但是项目页面正常运行怎么办,很多朋友遇到这样的情况不知道该如何解决了,下面小编给大家带来了idea进程结束但是项目页面正常运行的解决方法,需要的朋友可以参考下
    2023-03-03
  • JAVA生成pdf文件的实操指南

    JAVA生成pdf文件的实操指南

    最近项目需要实现PDF下载的功能,由于没有这方面的经验,从网上花了很长时间才找到相关的资料,下面这篇文章主要给大家介绍了关于JAVA生成pdf文件的相关资料,文中通过实例代码介绍的非常详细,需要的朋友可以参考下
    2022-10-10
  • Spring整合Mybatis实操分享

    Spring整合Mybatis实操分享

    这篇文章主要介绍了Spring整合Mybatis实操分享,文章首先通过介绍Mybatis的工作原理展开Spring整合Mybatis的详细内容,需要的小伙伴可以参考一下
    2022-04-04
  • SpringBoot整合EasyExcel的完整过程记录

    SpringBoot整合EasyExcel的完整过程记录

    easyexcel是阿里巴巴旗下开源项目,主要用于Excel文件的导入和导出处理,下面这篇文章主要给大家介绍了关于SpringBoot整合EasyExcel的完整过程,需要的朋友可以参考下
    2021-12-12
  • 深入理解Java中的装箱和拆箱

    深入理解Java中的装箱和拆箱

    这篇文章主要介绍了深入理解Java中的装箱和拆箱,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-09-09

最新评论