服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - 详解Java中自定义注解的使用

详解Java中自定义注解的使用

2023-03-21 14:32刘架构 Java教程

Annontation是Java5开始引入的新特征,中文名称叫注解,它提供了一种安全的类似注释的机制,用来将任何的信息或元数据(metadata)与程序元素(类、方法、成员变量等)进行关联。本文主要介绍了自定义注解的使用,希望对大家有

什么是注解

在早期的工作的时候 ,自定义注解写的比较多,可大多都只是因为 这样看起来 不会存在一堆代码耦合在一起的情况,所以使用了自定义注解,这样看起来清晰些,

Annontation是Java5开始引入的新特征,中文名称叫注解。

它提供了一种安全的类似注释的机制,用来将任何的信息或元数据(metadata)与程序元素(类、方法、成员变量等)进行关联。为程序的元素(类、方法、成员变量)加上更直观、更明了的说明,这些说明信息是与程序的业务逻辑无关,并且供指定的工具或框架使用。Annontation像一种修饰符一样,应用于包、类型、构造方法、方法、成员变量、参数及本地变量的声明语句中。

Java注解是附加在代码中的一些元信息,用于一些工具在编译、运行时进行解析和使用,起到说明、配置的功能。注解不会也不能影响代码的实际逻辑,仅仅起到辅助性的作用。

一般我们自定义一个注解的操作是这样的:

?
1
2
public @interface MyAnnotation {
}

如果说我们需要给他加上参数,那么大概是这样的

?
1
2
3
4
5
6
7
8
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@Documented
public @interface MyAnnotation {
    public int age() default 18;
    String name() ;
    String [] books();
}

我们可以关注到上面有些我们不曾见过的注解,而这类注解,统称为元注解 ,我们可以大概来看一下

@Document

是被用来指定自定义注解是否能随着被定义的java文件生成到JavaDoc文档当中。

@Target

是专门用来限定某个自定义注解能够被应用在哪些Java元素上面的,不定义说明可以放在任何元素上。

上面这个 Target这玩意有个枚举,可以清晰的看出来,他的 属性

使用枚举类ElementType来定义

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
public enum ElementType {
    /** 类,接口(包括注解类型)或枚举的声明 */
    TYPE,
    /** 属性的声明 */
    FIELD,
    /** 方法的声明 */
    METHOD,
    /** 方法形式参数声明 */
    PARAMETER,
    /** 构造方法的声明 */
    CONSTRUCTOR,
    /** 局部变量声明 */
    LOCAL_VARIABLE,
    /** 注解类型声明 */
    ANNOTATION_TYPE,
    /** 包的声明 */
    PACKAGE
}

@Retention

即用来修饰自定义注解的生命周期。

使用了RetentionPolicy枚举类型定义了三个阶段

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public enum RetentionPolicy {
    /**
     * Annotations are to be discarded by the compiler.
     * (注解将被编译器丢弃)
     */
    SOURCE,
 
    /**
     * Annotations are to be recorded in the class file by the compiler
     * but need not be retained by the VM at run time.  This is the default
     * behavior.
     * (注解将被编译器记录在class文件中,但在运行时不会被虚拟机保留,这是一个默认的行为)
     */
    CLASS,
 
    /**
     * Annotations are to be recorded in the class file by the compiler and
     * retained by the VM at run time, so they may be read reflectively.
     * (注解将被编译器记录在class文件中,而且在运行时会被虚拟机保留,因此它们能通过反射被读取到)
     * @see java.lang.reflect.AnnotatedElement
     */
    RUNTIME
}

@Inherited

允许子类继承父类中的注解

 

注解的注意事项

1.访问修饰符必须为public,不写默认为public;

2.该元素的类型只能是基本数据类型、String、Class、枚举类型、注解类型(体现了注解的嵌套效果)以及上述类型的一位数组;

3.该元素的名称一般定义为名词,如果注解中只有一个元素,请把名字起为value(后面使用会带来便利操作);

4.()不是定义方法参数的地方,也不能在括号中定义任何参数,仅仅只是一个特殊的语法;

5.default代表默认值,值必须和第2点定义的类型一致;

6.如果没有默认值,代表后续使用注解时必须给该类型元素赋值。

 

注解的本质

所有的Java注解都基于Annotation接口。但是,手动定义一个继承自Annotation接口的接口无效。要定义一个有效的Java注解,需要使用@interface关键字来声明注解。Annotation接口本身只是一个普通的接口,并不定义任何注解类型。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
public interface Annotation { 
    boolean equals(Object obj);
    /**
    * 获取hashCode
    */
    int hashCode();
    
    String toString();
    /**
     *获取注解类型
     */
    Class<? extends Annotation> annotationType();
}

在Java中,所有的注解都是基于Annotation接口的,但是手动定义一个继承自Annotation接口的接口并不会创建一个有效的注解。要定义有效的注解,需要使用特殊的关键字@interface来声明注解类型。Annotation接口本身只是一个普通的接口,而不是一个定义注解的接口。因此,使用@interface声明注解是定义Java注解的标准方法。

?
1
2
3
4
public @interface MyAnnotation1 {
}
public interface MyAnnotation2 extends Annotation  {
}
?
1
2
3
4
5
6
7
// javap -c TestAnnotation1.class
Compiled from "MyAnnotation1.java"                                                                
public interface com.spirimark.corejava.annotation.MyAnnotation1 extends java.lang.annotation.Annotation {}
// javap -c TestAnnotation2.class
Compiled from "MyAnnotation2.java"                                                                
public interface com.spirimark.corejava.annotation.MyAnnotation2 extends java.lang.annotation.Annotation {}

虽然Java中的所有注解都是基于Annotation接口,但即使接口本身支持多继承,注解的定义仍无法使用继承关键字来实现。定义注解的正确方式是使用特殊的关键字@interface声明注解类型。

同时需要注意的是,通过@interface声明的注解类型不支持继承其他注解或接口。任何尝试继承注解类型的操作都会导致编译错误。

?
1
2
3
4
5
6
7
8
public @interface MyAnnotation1 {
}
/** 错误的定义,注解不能继承注解 */
@interface MyAnnotation2 extends MyAnnotation1 {
}
/** 错误的定义,注解不能继承接口 */
@interface MyAnnotation3 extends Annotation {
}

 

自定义注解使用

 

使用方式 1

自定义注解的玩法有很多,最常见的莫过于

  • 声明注解
  • 通过反射读取

但是上面这种一般现在在开发中不怎么常用,最常用的就是,我们通过 切面去在注解的前后进行加载

创建注解

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface BussinessLog {
 
    /**
     * 功能
     */
    BusinessTypeEnum value();
 
    /**
     * 是否保存请求的参数
     */
    boolean isSaveRequestData() default true;
 
    /**
     * 是否保存响应的参数
     */
    boolean isSaveResponseData() default true;
}

设置枚举

?
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
public enum BusinessTypeEnum {
    /**
     * 其它
     */
    OTHER,
 
    /**
     * 新增
     */
    INSERT,
 
    /**
     * 修改
     */
    UPDATE,
 
    /**
     * 删除
     */
    DELETE,
 
    /**
     * 授权
     */
    GRANT,
 
    /**
     * 导出
     */
    EXPORT,
 
    /**
     * 导入
     */
    IMPORT,
}

创建切面操作

  1. @Slf4j 
  2. @Aspect 
  3. @Component 
  4. public class LogConfig { 
  5.   
  6.     @Autowired 
  7.     private IUxmLogService uxmLogService; 
  8.   
  9.    /** 
  10.     * 后置通过,⽬标⽅法正常执⾏完毕时执⾏ 
  11.     * 
  12.     */ 
  13.     @AfterReturning(pointcut = "@annotation(controllerLog)", returning = "jsonResult"
  14.     public void doAfterReturning(JoinPoint joinPoint, Log controllerLog, Object jsonResult) { 
  15.         handleLog(joinPoint, controllerLog, null, jsonResult); 
  16.     } 
  17.   
  18.    /** 
  19.     * 异常通知,⽬标⽅法发⽣异常的时候执⾏ 
  20.     * 
  21.     */ 
  22.     @AfterThrowing(value = "@annotation(controllerLog)", throwing = "e"
  23.     public void doAfterThrowing(JoinPoint joinPoint, Log controllerLog, Exception e) { 
  24.         handleLog(joinPoint, controllerLog, e, null); 
  25.     } 
  26.   
  27.     protected void handleLog(final JoinPoint joinPoint, Log controllerLog, final Exception e, Object jsonResult) { 
  28.         try { 
  29.             MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature(); 
  30.             String title = methodSignature.getMethod().getAnnotation(ApiOperation.class).value(); 
  31.             // 获取当前的用户 
  32.             String userName = CurrentUser.getCurrentUserName(); 
  33.   
  34.             // *========数据库日志=========*// 
  35.             UxmLog uxmLog = new UxmLog(); 
  36.             uxmLog.setStatus(BaseConstant.YES); 
  37.             // 请求的地址 
  38.             ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); 
  39.             assert requestAttributes != null
  40.             HttpServletRequest request = requestAttributes.getRequest(); 
  41.             String ip = getIpAddr(request); 
  42.             // 设置标题 
  43.             uxmLog.setTitle(title); 
  44.             uxmLog.setOperIp(ip); 
  45.             uxmLog.setOperUrl(request.getRequestURI()); 
  46.             uxmLog.setOperName(userName); 
  47.   
  48.             if (e != null) { 
  49.                 uxmLog.setStatus(BaseConstant.NO); 
  50.                 uxmLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000)); 
  51.             } 
  52.             // 设置方法名称 
  53.             String className = joinPoint.getTarget().getClass().getName(); 
  54.             String methodName = joinPoint.getSignature().getName(); 
  55.             uxmLog.setMethod(className + "." + methodName + "()"); 
  56.             // 设置请求方式 
  57.             uxmLog.setRequestMethod(request.getMethod()); 
  58.             // 处理设置注解上的参数 
  59.             getControllerMethodDescription(joinPoint, controllerLog, uxmLog, jsonResult, request); 
  60.             // 保存数据库 
  61.             uxmLog.setOperTime(new Date()); 
  62.             uxmLogService.save(uxmLog); 
  63.         } catch (Exception exp) { 
  64.             // 记录本地异常日志 
  65.             log.error("==前置通知异常=="); 
  66.             log.error("异常信息:{}", exp.getMessage()); 
  67.             exp.printStackTrace(); 
  68.         } 
  69.     } 
  70.   
  71.     public static String getIpAddr(HttpServletRequest request) { 
  72.         if (request == null) { 
  73.             return "unknown"
  74.         } 
  75.         String ip = request.getHeader("x-forwarded-for"); 
  76.         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
  77.             ip = request.getHeader("Proxy-Client-IP"); 
  78.         } 
  79.         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
  80.             ip = request.getHeader("X-Forwarded-For"); 
  81.         } 
  82.         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
  83.             ip = request.getHeader("WL-Proxy-Client-IP"); 
  84.         } 
  85.         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
  86.             ip = request.getHeader("X-Real-IP"); 
  87.         } 
  88.   
  89.         if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
  90.             ip = request.getRemoteAddr(); 
  91.         } 
  92.         return ip; 
  93.     } 
  94.   
  95.     public void getControllerMethodDescription(JoinPoint joinPoint, Log log, UxmLog uxmLog, Object jsonResult, HttpServletRequest request) throws Exception { 
  96.         // 设置action动作 
  97.         uxmLog.setBusinessType(log.value().ordinal()); 
  98.         // 是否需要保存request,参数和值 
  99.         if (log.isSaveRequestData()) { 
  100.             // 获取参数的信息,传入到数据库中。 
  101.             setRequestValue(joinPoint, uxmLog, request); 
  102.         } 
  103.         // 是否需要保存response,参数和值 
  104.         if (log.isSaveResponseData()) { 
  105.             uxmLog.setJsonResult(StringUtils.substring(JSON.toJSONString(jsonResult), 0, 2000)); 
  106.         } 
  107.     } 
  108.   
  109.     private void setRequestValue(JoinPoint joinPoint, UxmLog uxmLog, HttpServletRequest request) throws Exception { 
  110.         String requestMethod = uxmLog.getRequestMethod(); 
  111.         if (RequestMethod.PUT.name().equals(requestMethod) || RequestMethod.POST.name().equals(requestMethod)) { 
  112.             String params = argsArrayToString(joinPoint.getArgs()); 
  113.             uxmLog.setOperParam(StringUtils.substring(params, 0, 2000)); 
  114.         } else { 
  115.             Map<?, ?> paramsMap = (Map<?, ?>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE); 
  116.             uxmLog.setOperParam(StringUtils.substring(paramsMap.toString(), 0, 2000)); 
  117.         } 
  118.     } 
  119.   
  120.     private String argsArrayToString(Object[] paramsArray) { 
  121.         StringBuilder params = new StringBuilder(); 
  122.         if (paramsArray != null && paramsArray.length > 0) { 
  123.             for (Object o : paramsArray) { 
  124.                 if (ObjectUtil.isNotNull(o) && !isFilterObject(o)) { 
  125.                     try { 
  126.                         Object jsonObj = JSON.toJSON(o); 
  127.                         params.append(jsonObj.toString()).append(" "); 
  128.                     } catch (Exception e) { 
  129.                         log.error(e.getMessage()); 
  130.                     } 
  131.                 } 
  132.             } 
  133.         } 
  134.         return params.toString().trim(); 
  135.     } 
  136.   
  137.     @SuppressWarnings("rawtypes"
  138.     public boolean isFilterObject(final Object o) { 
  139.         Class<?> clazz = o.getClass(); 
  140.         if (clazz.isArray()) { 
  141.             return clazz.getComponentType().isAssignableFrom(MultipartFile.class); 
  142.         } else if (Collection.class.isAssignableFrom(clazz)) { 
  143.             Collection collection = (Collection) o; 
  144.             for (Object value : collection) { 
  145.                 return value instanceof MultipartFile; 
  146.             } 
  147.         } else if (Map.class.isAssignableFrom(clazz)) { 
  148.             Map map = (Map) o; 
  149.             for (Object value : map.entrySet()) { 
  150.                 Map.Entry entry = (Map.Entry) value; 
  151.                 return entry.getValue() instanceof MultipartFile; 
  152.             } 
  153.         } 
  154.         return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse 
  155.                 || o instanceof BindingResult; 
  156.     } 

这样的话,我们就可以 在 项目当中 去在标注注解的前后去进行输出 日志

详解Java中自定义注解的使用

 

使用方式 2

我们可能还会在每次请求的时候去输出日志,所以 我们也可以去定义一个 请求的 注解

@HttpLog 自动记录Http日志

在很多时候我们要把一些接口的Http请求信息记录到日志里面。通常原始的做法是利用日志框架如log4j,slf4j等,在方法里面打日志log.info(“xxxx”)。但是这样的工作无疑是单调而又重复的,我们可以采用自定义注解+切面的来简化这一工作。通常的日志记录都在Controller里面进行的比较多,我们可以实现这样的效果:
我们自定义@HttpLog注解,作用域在类上,凡是打上了这个注解的Controller类里面的所有方法都会自动记录Http日志。实现方式也很简单,主要写好切面表达式:

日志切面

下面代码的意思,就是当标注了注解,我们通过 @Pointcut 定义了切入点, 当标注了注解,我们会在标注注解的 前后进行输出 ,当然也包含了 Spring 官方 自带的注解 例如 RestController

?
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
// 切面表达式,描述所有所有需要记录log的类,所有有@HttpLog 并且有 @Controller 或 @RestController 类都会被代理
    @Pointcut("@within(com.example.spiritmark.annotation.HttpLog) && (@within(org.springframework.web.bind.annotation.RestController) || @within(org.springframework.stereotype.Controller))")
    public void httpLog() {
    }
 
    @Before("httpLog()")
    public void preHandler(JoinPoint joinPoint) {
        startTime.set(System.currentTimeMillis());
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest httpServletRequest = servletRequestAttributes.getRequest();
        log.info("Current Url: {}", httpServletRequest.getRequestURI());
        log.info("Current Http Method: {}", httpServletRequest.getMethod());
        log.info("Current IP: {}", httpServletRequest.getRemoteAddr());
        Enumeration<String> headerNames = httpServletRequest.getHeaderNames();
        log.info("=======http headers=======");
        while (headerNames.hasMoreElements()) {
            String nextName = headerNames.nextElement();
            log.info(nextName.toUpperCase() + ": {}", httpServletRequest.getHeader(nextName));
        }
        log.info("======= header end =======");
        log.info("Current Class Method: {}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        log.info("Parms: {}", null != httpServletRequest.getQueryString() ? JSON.toJSONString(httpServletRequest.getQueryString().split("&")) : "EMPTY");
 
    }
 
    @AfterReturning(returning = "response", pointcut = "httpLog()")
    public void afterReturn(Object response) {
        log.info("Response: {}", JSON.toJSONString(response));
        log.info("Spend Time: [ {}", System.currentTimeMillis() - startTime.get() + " ms ]");
 
    }

@TimeStamp 自动注入时间戳

如果我们想通过自定义注解,在我们每次保存数据的时候,自动的帮我们将标注注解的方法内的时间戳字段转换成 正常日期,我们就需要

我们的很多数据需要记录时间戳,最常见的就是记录created_at和updated_at,通常我们可以通常实体类中的setCreatedAt()方法来写入当前时间,然后通过ORM来插入到数据库里,但是这样的方法比较重复枯燥,给每个需要加上时间戳的类都要写入时间戳很麻烦而且不小心会漏掉。

另一个思路是在数据库里面设置默认值,插入的时候由数据库自动生成当前时间戳,但是理想很丰满,现实很骨感,在MySQL如果时间戳类型是datetime里即使你设置了默认值为当前时间也不会在时间戳为空时插入数据时自动生成,而是会在已有时间戳记录的情况下更新时间戳为当前时间,这并不是我们所需要的,比如我们不希望created_at每次更改记录时都被刷新,另外的方法是将时间戳类型改为timestamp,这样第一个类型为timestamp的字段会在值为空时自动生成,但是多个的话,后面的均不会自动生成。再有一种思路是,直接在sql里面用now()函数生成,比如created_at = now()。

但是这样必须要写sql,如果使用的不是主打sql流的orm不会太方便,比如hibernate之类的,并且也会加大sql语句的复杂度,同时sql的可移植性也会降低,比如sqlServer中就不支持now()函数。为了简化这个问题,我们可以自定义@TimeStamp注解,打上该注解的方法的入参里面的所有对象或者指定对象里面要是有setCreatedAt、setUpdatedAt这样的方法,便会自动注入时间戳,而无需手动注入,同时还可以指定只注入created_at或updated_at。实现主要代码如下:

?
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
50
51
52
53
54
@Aspect
@Component
public class TimeStampAspect {
 
    @Pointcut("@annotation(com.example.spiritmark.annotation.TimeStamp)")
    public void timeStampPointcut() {}
 
    @Before("timeStampPointcut() && @annotation(timeStamp)")
    public void setTimestamp(JoinPoint joinPoint, TimeStamp timeStamp) {
        Long currentTime = System.currentTimeMillis();
        Class<?> type = timeStamp.type();
        Object[] args = joinPoint.getArgs();
 
        for (Object arg : args) {
            if (type.isInstance(arg)) {
                setTimestampForArg(arg, timeStamp);
            }
        }
    }
 
    private void setTimestampForArg(Object arg, TimeStamp timeStamp) {
        Date currentDate = new Date(System.currentTimeMillis());
        TimeStampRank rank = timeStamp.rank();
        Method[] methods = arg.getClass().getMethods();
 
        for (Method method : methods) {
            String methodName = method.getName();
            if (isSetter(methodName) && isRelevantSetter(methodName, rank)) {
                try {
                    method.invoke(arg, currentDate);
                } catch (IllegalAccessException | InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
    }
 
    private boolean isSetter(String methodName) {
        return methodName.startsWith("set") && methodName.length() > 3;
    }
 
    private boolean isRelevantSetter(String methodName, TimeStampRank rank) {
        if (rank.equals(TimeStampRank.FULL)) {
            return methodName.endsWith("At");
        }
        if (rank.equals(TimeStampRank.UPDATE)) {
            return methodName.startsWith("setUpdated");
        }
        if (rank.equals(TimeStampRank.CREATE)) {
            return methodName.startsWith("setCreated");
        }
        return false;
    }
}

1.使用@Aspect和@Component注解分别标注切面和切面类,更符合AOP的实现方式。

2.将pointCut()和before()方法分别改名为timeStampPointcut()和setTimestamp(),更能表达它们的作用。

3.通过Class.isInstance(Object obj)方法,将原先的流操作改为了一个简单的for循环,使代码更加简洁。

4.将原先的setCurrentTime()方法改名为setTimestampForArg(),更能表达它的作用。

5.新增了两个私有方法isSetter()和isRelevantSetter(),将原先在setTimestampForArg()中的逻辑分离出来,提高了代码的可读性和可维护性

到此这篇关于详解Java中自定义注解的使用的文章就介绍到这了,更多相关Java自定义注解内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/qq_42897427/article/details/129659897

延伸 · 阅读

精彩推荐