周凯,个人博客

  • 前端
  • 嵌入式
  • 工具
  • 后端
  • 随笔
个人记录
  1. 首页
  2. 后端
  3. java
  4. spring-boot
  5. 正文

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

2023年 2月 23日 690点热度 0人点赞 0条评论

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;
/**
 *  Springboot 自定义注解
 **/
@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;
@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 {
    }
}

如果发现 HandlerInterceptor 不生效

  • 看看是否为了解决跨域,实现了WebMvcConfigurationSupport或者WebMvcConfigurer
  • 如果实现了,需要重写addInterceptors

    @Override
    public  void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LdAuthVerificationHandlerInterceptor()).addPathPatterns("/**");
    }

    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;
    @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("执行了切面……");
       //业务逻辑处理……
    }
    }

    bing Chart提供的spring-boot AOP示例

    AOP 的优势是可以将一些与业务无关的功能(如日志、权限控制等)提取出来,降低代码的耦合度,增加代码的可重用性和可维护性。AOP 还可以实现动态代理,不需要修改原来的代码就可以改变执行结果。
    AOP 的缺点是可能会增加程序的复杂度,难以理解和调试。AOP 也可能会影响程序的性能,因为要进行额外的切面处理。AOP 还需要正确使用,否则可能会造成意想不到的后果。

    @Aspect // 声明这是一个切面类
    @Component // 让这个类被 Spring 容器管理
    public class LogAspects {
    
    // 定义一个切点表达式,指定要拦截的方法
    @Pointcut("execution(public int com.example.MathCalculator.*(..))")
    public void pointCut(){}
    
    // 前置通知,在目标方法执行之前执行
    @Before("pointCut()")
    public void logStart(JoinPoint joinPoint){
        System.out.println(joinPoint.getSignature().getName() + " 方法开始执行...");
    }
    
    // 后置通知,在目标方法执行之后执行(无论是否异常)
    @After("pointCut()")
    public void logEnd(JoinPoint joinPoint){
        System.out.println(joinPoint.getSignature().getName() + " 方法结束执行...");
    }
    
    // 返回通知,在目标方法正常返回之后执行
    @AfterReturning(value = "pointCut()", returning = "result")
    public void logReturn(JoinPoint joinPoint, Object result){
        System.out.println(joinPoint.getSignature().getName() + " 方法正常返回...结果是:" + result);
    }
    
    // 异常通知,在目标方法出现异常时执行
    @AfterThrowing(value = "pointCut()", throwing = "exception")
    public void logException(JoinPoint joinPoint, Exception exception){
        System.out.println(joinPoint.getSignature().getName() + " 方法出现异常...异常信息是:" + exception);
    }
    }

    参考

  • SpringBoot中使用Aspect实现切面,超详细
  • SpringBoot 自定义拦截器 HandlerInterceptor 方法没有生效

🎯 拓展阅读提示

本文涉及的内容已同步至公众号后台,我会在那里分享更多深度内容和实用技巧

→ 点击关注:一行梦境

公众号二维码
本作品采用 知识共享署名 4.0 国际许可协议 进行许可
标签: 暂无
最后更新:2023年 2月 28日

周凯

这个人很懒,什么都没留下

打赏 点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2022-现在 周凯,个人博客. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

蒙ICP备18004897号