Java实现自定义注解

在工作中写了一个用于超时的自定义注解,这里坐下简单的分析记录,首先简单介绍下注解:
1、注解
注解英文称 Annotaion,是Java从1.5开始支持加入源码的特殊语法元数据,作为程序的元数据嵌入到程序当中。注解实现有一个重要的接口Annotation接口,利用@interface关键字,将所有使用该关键字的注解类都实现Annotation接口。Annontation像一种修饰符一样,应用于包、类型、构造方法、方法、成员变量、参数及本地变量的声明语句中。

使用注解的好处:1、帮助代码编译检查,2、提高代码的识别度,比如 @override @Deprecated , 3、减少重复代码,简化代码、4、根据注解生成帮助文档,如 @Decument 等
2、元注解
注解的基本语法:

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AnnotationName{
 
}

元注解就是注解的注解,用来描述注解的。
(1)@Retention 定义该注解的生命周期
RetentionPolicy.SOURCE :作用于源码阶段,比如常见的 @Override, @SuppressWarnings;
RetentionPolicy.CLASS :作用于字节码阶段
RetentionPolicy.RUNTIME :作用于运行阶段
(2)@Target 定义该注解的作用范围
ElementType.TYPE :用于注解到类,接口、枚举类
ElementType.FIELD:字段,包括枚举类常量
ElementType.METHOD:方法声明
ElementType.PARAMETER:参数声明
ElementType.CONSTRUCTOR:构造器声明
ElementType.LOCAL_VARIABLE :局部变量声明
ElementType.ANNOTATION_TYPE :用于注解声明,即注解的注解,元注解
ElementType.PACKAGE :包声明
(3)
@Document 注解将生成到javadoc中
@Deprecated 表示过时的类
@Inherited 是否允许子类继承该注解
@SuppressWarnings 编译器忽略掉无法识别的警告名
@Override 标注的方法重载了父类的方法

接下来简单介绍下
AOP常用术语:
1、连接点(Joinpoint)
  增强程序执行的某个特定位置(要在哪个地方做增强操作)。Spring仅支持方法的连接点,既仅能在方法调用前,方法调用后,方法抛出异常时等这些程序执行点进行织入增强。

2、切点(Pointcut)
  切点是一组连接点的集合。AOP通过“切点”定位特定的连接点。通过数据库查询的概念来理解切点和连接点的关系再适合不过了:连接点相当于数据库中的记录,而切点相当于查询条件。

3、增强(Advice)
  增强是织入到目标类连接点上的一段程序代码。表示要在连接点上做的操作。

4、切面(Aspect)
  切面由切点和增强(引介)组成(可以包含多个切点和多个增强),它既包括了横切逻辑的定义,也包括了连接点的定义,SpringAOP就是负责实施切面的框架,它将切面所定义的横切逻辑织入到切面所指定的链接点中。

接下来直接上代码:
TimeLog.java
在这里
@Target定义了该注解作用于方法上,并且作用于运行阶段

package com.pousheng.user.rest.aop.timing;

import java.lang.annotation.*;

/**
 * 日志耗时注解
 * @author planetwalker
 * @date 2020-03-21 12:37 下午
 */
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface TimeLog {

    /**
     * 是否开启超时提醒
     */
    boolean openHandle() default false;

    /**
     * 超时提醒阀值 单位 ms
     */
    long limit() default Long.MAX_VALUE;

    /**
     * 是否显示参数
     */
    boolean showArgs() default false;

}

TimeLogAdvisor
这里就是注解的实现

package com.pousheng.user.rest.aop.timing;

import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * 耗时日志AOP
 * @author planetwalker
 * @date 2020-03-21 12:42 下午
 */
@Aspect
@Component
@Slf4j
public class TimeLogAdvisor {

    @Autowired(required = false)
    private OvertimeHandler overTimeHandler;

    @Pointcut("@annotation(com.pousheng.user.rest.aop.timing.TimeLog)")
    public void timeLogPointCut() {}

    @Around("timeLogPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        //通过反射的方式获取注解信息
        TimeLog timeLog = method.getAnnotation(TimeLog.class);
        boolean openHandle = timeLog.openHandle();
        long limit = timeLog.limit();
        boolean showArgs = timeLog.showArgs();
        Class<?> declaringClass = method.getDeclaringClass();
        String className = declaringClass.getName();
        String methodPath = className + "#" + method.getName();
        Object[] args = point.getArgs();

        Stopwatch stopwatch = Stopwatch.createStarted();
        Object result = point.proceed();
        long elapsed = stopwatch.elapsed(TimeUnit.MILLISECONDS);
        if (log.isDebugEnabled()) {
            if (showArgs) {
                log.debug("method {} execute with params {}, cost time {} ms", methodPath, args, elapsed);
            } else {
                log.debug("method {} finish, cost time {} ms", methodPath, elapsed);
            }
        }

        if (openHandle && elapsed >= limit && overTimeHandler != null) {
            OverTimeEvent overTimeEvent = OverTimeEvent.builder()
                    .args(args)
                    .elapsed(elapsed)
                    .methodPath(methodPath)
                    .build();
            overTimeHandler.handle(overTimeEvent);
        }
        return result;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值