SpringBoot自定义注解的实现与使用

Java自定义注解的实现与使用

之前十分好奇,Spring中的那些注解为什么那么神奇,一个注解就能帮我们做很多事情,那么它是怎么实现的呢?

Java 注解(Annotation)又称 Java 标注,是 JDK5.0 引入的一种注释机制。他是代码里的特殊标记,这些标记可以在编译,类加载,运行时被读取,并执行相应操作。通过使用注解可以在不改变原有逻辑的情况下,在源文件中添加补充信息,代码分析工具,开发工具,部署工具,可以更具这些信息进行验证和部署.

自定义注解的定义

首先建一个包名为annotation,然后新建注解AutoIdempotent

package com.yabiao.idempotent.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
 * <p>
 *  Springboot 自定义注解
 * @author: zhangyb
 * @create: 2020-09-13
 **/
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface AutoIdempotent {

    boolean required() default true;
}

是不是很简单,其中有两个注解需要了解以下:
@Target表示注解可以使用到哪些地方,可以是类,方法,或者是属性上,定义在ElementType枚举中:

package java.lang.annotation;

public enum ElementType {
    TYPE,				/* 类、接口(包括注释类型)或枚举声明  */
    FIELD,				/* 字段声明(包括枚举常量)  */
    METHOD,				/* 方法声明  */
    PARAMETER,	 		/* 形式参数声明  */
    CONSTRUCTOR,		/* 构造方法声明  */
    LOCAL_VARIABLE,		/* 局部变量声明  */
    ANNOTATION_TYPE,	/* 注释类型声明  */
    PACKAGE,			/* 包声明  */
    TYPE_PARAMETER,		/* 类型参数声明 @since 1.8*/
    TYPE_USE			/* 任何类型声明 @since 1.8*/
}

@Retention作用是定义被它所注解的注解保留多久,一共有三种策略,定义在RetentionPolicy枚举中:

package java.lang.annotation;

public enum RetentionPolicy {

    SOURCE,	/* 注释将被编译器丢弃。*/

    CLASS,	/* 注释由编译器记录在类文件中,但不需要在运行时由VM保留。默认。*/

    RUNTIME	/*注释将由编译器记录在类文件中,并在运行时由VM保留,因此可以反射性地读取它们。*/
}

自定义注解的解析

注解定义起来十分的简单,关键是怎么去使用它,那么就首先我们得对注解进行解析,有两种方式:

  • 1.通过拦截器解析。
    当注解被用在接口请求的方法上时,我们可以用拦截器的方式进行去解析自定义的注解,方法如下:
package com.yabiao.idempotent.interceptor;

import com.yabiao.idempotent.annotation.AutoIdempotent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * <p>
 *  注解拦截器
 * </p>
 *
 * @author: zhangyb
 * @create: 2020-09-13
 **/
@Component
public class IdempotentInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("执行了拦截器……");
        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        Method method = ((HandlerMethod) handler).getMethod();
        AutoIdempotent annotation = method.getAnnotation(AutoIdempotent.class);

        if (annotation != null){
            boolean required = annotation.required();
            if (required) {
                //业务逻辑处理
                //……
            }
        }

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
  • 2.通过AOP进行解析。
    当然AOP解析也是一种常见的解析方法:
package com.yabiao.idempotent.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
* <p>
*  通过AOP的方式来解析注解
* </p>
*
* @author: zhangyb
* @create: 2020-09-13
**/
@Component
@Aspect
public class IdempotentAspect {

   @Pointcut("@annotation(com.yabiao.idempotent.annotation.AutoIdempotent)")
   private void pointCut(){ }
   
   @Before("pointCut()")
   public void before(JoinPoint joinPoint) throws IdempotentException {
       System.out.println("执行了切面……");
       //业务逻辑处理……
   }
}

总结

完整代码:
码云:https://gitee.com/zybCode/idempotent

参考:
Java 注解(Annotation)
注解
java元注解 @Target注解用法
江南一点雨-Spring Boot自定义注解一键处理请求幂等性
分布式系统中实现幂等性的几种方式

  • 13
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值