Springboot 拦截器 + 自定义注解

1,837 阅读7分钟

Springboot 拦截器 + 自定义注解

自定义注解

  • 注解的概念

    • 注解是一种能被添加到java代码中的元数据,类、方法、变量、参数和包都可以用注解来修饰。注解对于它所修饰的代码并没有直接的影响。

    • 通过官方描述得出以下结论:

      • 注解是一种元数据形式。即注解是属于java的一种数据类型,和类、接口、数组、枚举类似。
      • 注解用来修饰,类、方法、变量、参数、包。
      • 注解不会对所修饰的代码产生直接的影响。
  • 如何自定义注解

    • 第一步,定义注解——相当于定义标记;
    • 第二步,配置注解——把标记打在需要用到的程序代码中;
    • 第三步,解析注解——在编译期或运行时检测到标记,并进行特殊操作。
  • 基本语法

    • 注解类型的声明部分:

      • 注解在Java中,与类、接口、枚举类似,因此其声明语法基本一致,只是所使用的关键字有所不同@interface在底层实现上,所有定义的注解都会自动继承java.lang.annotation.Annotation接口

        public @interface CherryAnnotation {
        }
        
    • 注解类型的实现部分:

      • 根据我们在自定义类的经验,在类的实现部分无非就是书写构造、属性或方法。但是,在自定义注解中,其实现部分只能定义一个东西:注解类型元素(annotation type element) 。咱们来看看其语法:

      • public @interface CherryAnnotation {
            public String name();
            int age();
            int[] array();
        }
        
      • 也许你会认为这不就是接口中定义抽象方法的语法嘛?别着急,咱们看看下面这个:

        public @interface CherryAnnotation {
            public String name();
            int age() default 18;
            int[] array();
        }
        
      • 注解里面定义的是:注解类型元素!

        定义注解类型元素时需要注意如下几点:

        1. 访问修饰符必须为public,不写默认为public;
        2. 该元素的类型只能是基本数据类型、String、Class、枚举类型、注解类型(体现了注解的嵌套效果)以及上述类型的一位数组;
        3. 该元素的名称一般定义为名词,如果注解中只有一个元素,请把名字起为value(后面使用会带来便利操作);
        4. ()不是定义方法参数的地方,也不能在括号中定义任何参数,仅仅只是一个特殊的语法;
        5. default代表默认值,值必须和第2点定义的类型一致;
        6. 如果没有默认值,代表后续使用注解时必须给该类型元素赋值。

        可以看出,注解类型元素的语法非常奇怪,即又有属性的特征(可以赋值),又有方法的特征(打上了一对括号)。但是这么设计是有道理的,我们在后面的章节中可以看到:注解在定义好了以后,使用的时候操作元素类型像在操作属性,解析的时候操作元素类型像在操作方法

  • 常用的元注解

    • @Target

      @Target注解,是专门用来限定某个自定义注解能够被应用在哪些Java元素上面的。它使用一个枚举类型定义如下:

      public enum ElementType {
          /** 类,接口(包括注解类型)或枚举的声明 */
          TYPE,
          /** 属性的声明 */
          FIELD,
          /** 方法的声明 */
          METHOD,
          /** 方法形式参数声明 */
          PARAMETER,
          /** 构造方法的声明 */
          CONSTRUCTOR,
          /** 局部变量声明 */
          LOCAL_VARIABLE,
          /** 注解类型声明 */
          ANNOTATION_TYPE,
          /** 包的声明 */
          PACKAGE
      }
      
      /@CherryAnnotation被限定只能使用在类、接口或方法上面
      @Target(value = {ElementType.TYPE,ElementType.METHOD})
      public @interface CherryAnnotation {
          String name();
          int age() default 18;
          int[] array();
      }
      
    • @Retention

      @Retention注解,翻译为持久力、保持力。即用来修饰自定义注解的生命力。 注解的生命周期有三个阶段:1、Java源文件阶段;2、编译到class文件阶段;3、运行期阶段。同样使用了RetentionPolicy枚举类型定义了三个阶段: 一般使用RUNTIME

      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
      }
      

      我们再详解一下:

      1. 如果一个注解被定义为RetentionPolicy.SOURCE,则它将被限定在Java源文件中,那么这个注解即不会参与编译也不会在运行期起任何作用,这个注解就和一个注释是一样的效果,只能被阅读Java文件的人看到;
      2. 如果一个注解被定义为RetentionPolicy.CLASS,则它将被编译到Class文件中,那么编译器可以在编译时根据注解做一些处理动作,但是运行时JVM(Java虚拟机)会忽略它,我们在运行期也不能读取到;
      3. 如果一个注解被定义为RetentionPolicy.RUNTIME,那么这个注解可以在运行期的加载阶段被加载到Class对象中。那么在程序运行阶段,我们可以通过反射得到这个注解,并通过判断是否有这个注解或这个注解中属性的值,从而执行不同的程序代码段。我们实际开发中的自定义注解几乎都是使用的RetentionPolicy.RUNTIME
      4. 在默认的情况下,自定义注解是使用的RetentionPolicy.CLASS。
    • @Documented

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

    • @Inherited

      @Inherited注解,是指定某个自定义注解如果写在了父类的声明部分,那么子类的声明部分也能自动拥有该注解。@Inherited注解只对那些@Target被定义为ElementType.TYPE的自定义注解起作用。

  • 在具体的java实体类中使用

    • 首先,定义一个注解、和一个供注解修饰的简单Java类

      @Retention(RetentionPolicy.RUNTIME)
      @Target(value = {ElementType.METHOD})
      @Documented
      public @interface CherryAnnotation {
          String name();
          int age() default 18;
          int[] score();
      }
      
      public class Student{
          public void study(int times){
              for(int i = 0; i < times; i++){
                  System.out.println("Good Good Study, Day Day Up!");
              }
          }
      }
      

      简单分析下:

      1. CherryAnnotation的@Target定义为ElementType.METHOD,那么它书写的位置应该在方法定义的上方,即:public void study(int times)之上;

      2. 由于我们在CherryAnnotation中定义的有注解类型元素,而且有些元素是没有默认值的,这要求我们在使用的时候必须在标记名后面打上(),并且在()内以“元素名=元素值“的形式挨个填上所有没有默认值的注解类型元素(有默认值的也可以填上重新赋值),中间用“,”号分割;最终

        public class Student {
            @CherryAnnotation(name = "cherry-peng",age = 23,score = {99,66,77})
            public void study(int times){
                for(int i = 0; i < times; i++){
                    System.out.println("Good Good Study, Day Day Up!");
                }
            }
        }
        
  • 特殊语法

    • 特殊语法一:如果注解本身没有注解类型元素,那么在使用注解的时候可以省略(),直接写为:@注解名,它和标准语法@注解名()等效!

      @Retention(RetentionPolicy.RUNTIME)
      @Target(value = {ElementType.TYPE})
      @Documented
      public @interface FirstAnnotation {
      }
      
      //等效于@FirstAnnotation()
      @FirstAnnotation
      public class JavaBean{
          //省略实现部分
      }
      
    • 特殊语法二:如果注解本本身只有一个注解类型元素,而且命名为value,那么在使用注解的时候可以直接使用:@注解名(注解值),其等效于:@注解名(value = 注解值)

      @Retention(RetentionPolicy.RUNTIME)
      @Target(value = {ElementType.TYPE})
      @Documented
      public @interface SecondAnnotation {
          String value();
      }
      
      //等效于@ SecondAnnotation(value = "this is second annotation")
      @SecondAnnotation("this is annotation")
      public class JavaBean{
          //省略实现部分
      }
      
    • 特殊用法三:如果注解中的某个注解类型元素是一个数组类型,在使用时又出现只需要填入一个值的情况,那么在使用注解时可以直接写为:@注解名(类型名 = 类型值),它和标准写法:@注解名(类型名 = {类型值})等效!

      @Retention(RetentionPolicy.RUNTIME)
      @Target(value = {ElementType.TYPE})
      @Documented
      public @interface ThirdAnnotation {
          String[] name();
      }
      
      //等效于@ ThirdAnnotation(name = {"this is third annotation"})
      @ ThirdAnnotation(name = "this is third annotation")
      public class JavaBean{
          //省略实现部分
      }
      
  • 反射操作获取注解

    public class TestAnnotation {
        public static void main(String[] args){
            try {
                //获取Student的Class对象
                Class stuClass = Class.forName("pojos.Student");
    ​
                //说明一下,这里形参不能写成Integer.class,应写为int.class
                Method stuMethod = stuClass.getMethod("study",int.class);
    ​
                if(stuMethod.isAnnotationPresent(CherryAnnotation.class)){
                    System.out.println("Student类上配置了CherryAnnotation注解!");
                    //获取该元素上指定类型的注解
                    CherryAnnotation cherryAnnotation = stuMethod.getAnnotation(CherryAnnotation.class);
                    System.out.println("name: " + cherryAnnotation.name() + ", age: " + cherryAnnotation.age()
                        + ", score: " + cherryAnnotation.score()[0]);
                }else{
                    System.out.println("Student类上没有配置CherryAnnotation注解!");
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            }
        }
    }
    

 

springboot 拦截器

  • 过滤器和拦截器的区别

    • 过滤器(Filter):当你有一堆东西的时候,你只希望选择符合你要求的某一些东西。定义这些 要求的工具,就是过滤器。
    • 拦截器(Interceptor):在一个流程正在进行的时候,你希望干预它的进展,甚至终止它进行, 这是拦截器做的事情。
    • 相同点:都是aop编程思想的体现,可以在程序执行前后做一些操作
    • 不同点:过滤器依赖于servlet容器,拦截器不依赖 过滤器的执行由Servlet容器回调完成,而拦截器通常通过动态代理的方式来执行。 触发时机不一样,过滤器是在请求进入Tomcat容器后,而进入servlet前进行预处理的;拦 截器是在进入servlet之后,而进入controller之前处理的。 拦截器可以获取IOC容器中的各个bean,而过滤器就不行,拦截器归Spring管理。
  • package com.duing.filter;
    ​
    import javax.servlet.*;
    import java.io.IOException;
    ​
    public class CustomFilter implements Filter {
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
            System.out.println(".............CustomFilter init............");
        }
        @Override
        public void doFilter(ServletRequest servletRequest,
                             ServletResponse servletResponse,
                             FilterChain filterChain)
                throws IOException, ServletException {
            System.out.println(".............CustomFilter doFilter............");
            filterChain.doFilter(servletRequest,servletResponse);
        }
        @Override
        public void destroy() {
            System.out.println(".............CustomFilter destroy............");
        }
    }
    
  • 过滤器配置类

    @Configuration
    public class FilterConfig {
    ​
        @Bean
        public FilterRegistrationBean<CustomFilter> filterRegistrationBean(){
            FilterRegistrationBean<CustomFilter> filterFilterRegistrationBean=
                    new FilterRegistrationBean<>();
            filterFilterRegistrationBean.setFilter(new CustomFilter());
            filterFilterRegistrationBean.addUrlPatterns("/*");
    //        filterFilterRegistrationBean.setOrder(0); //决定注册的优先级
            return filterFilterRegistrationBean;
        }
    }
    
  • 拦截器

    @Service
    public class CustomInterceptor implements HandlerInterceptor {
    ​
        @Override
        public boolean preHandle(HttpServletRequest request,
                          HttpServletResponse response, Object handler)
                throws Exception {
            System.out.println("...........CustomInterceptor prehandle...........");
            return true;
        }
    ​
        @Override
        public void postHandle(HttpServletRequest request,
                        HttpServletResponse response, Object handler,
                        @Nullable ModelAndView modelAndView) throws Exception {
    ​
            System.out.println("...........CustomInterceptor postHandle...........");
        }
    ​
        @Override
        public void afterCompletion(HttpServletRequest request,
                                    HttpServletResponse response, Object handler,
                                     @Nullable Exception ex) throws Exception {
    ​
            System.out.println("...........CustomInterceptor afterCompletion...........");
    ​
        }
    ​
    }
    

拦截器配置类

@Configuration
public class InterceptorConfig implements WebMvcConfigurer{
​
    @Autowired
    private CustomInterceptor customInterceptor;
​
​
    /**
     * 注册自定义的拦截器,并且定义拦截规则
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(customInterceptor).addPathPatterns("/**");
​
    }
}
  • 自己实现示例  打印出操作名称 路径 和时间

  • 拦截器

    @Slf4j
    @Component
    public class LogInterceptor extends HandlerInterceptorAdapter {
    ​
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            // 如果不是映射到方法直接通过
            if (!(handler instanceof HandlerMethod)) {
                return true;
            }
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            // 判断接口是否有Log注解
            Log logMethod = method.getAnnotation(Log.class);
            if(null != logMethod){
                Date date = new Date();
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                log.info("操作了"+logMethod.value()+ "方法!接口路径:"+request.getRequestURI() +"!时间:" + sf.format(date));
            }
            return true;
        }
    ​
    
  • 自定义注解

    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface Log {
        String value() default "";
    ​
        /**
         * 是否启用
         *
         * @return
         */
        boolean enable() default true;
    ​
        LogActionType type() default LogActionType.SELECT;
    }
    
  • Controller类

        @Log("获取验证码")
        @ApiOperation("获取验证码")
        @AnonymousGetMapping(value = "/code")
        public ResponseEntity<Object> getCode() {
            // 获取运算的结果
            Captcha captcha = loginProperties.getCaptcha();
            String uuid = properties.getCodeKey() + IdUtil.simpleUUID();
            // 保存
            redisUtils.set(uuid, captcha.text(), loginProperties.getLoginCode().getExpiration(), TimeUnit.MINUTES);
            // 验证码信息
            Map<String, Object> imgResult = new HashMap<String, Object>(2) {{
                put("img", captcha.toBase64());
                put("uuid", uuid);
            }};
            return ResponseEntity.ok(imgResult);
        }
    

     

  • 配置类

    @Configuration
    @EnableWebMvc
    public class ConfigurerAdapter implements WebMvcConfigurer {
    ​
        /** 文件配置 */
        private final FileProperties properties;
    ​
        private final OssProperties ossProperties;
        @Autowired
        private LogInterceptor logInterceptor;
    ​
    ​
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            // 拦截所有请求,通过判断是否有 @LoginRequired 注解 决定是否需要登录
            registry.addInterceptor(logInterceptor).addPathPatterns("/**");
        }
    ​
    
  • 结果

    50 [http-nio-9292-exec-8] INFO  me.zhengjie.constant.LogInterceptor - 操作了查询用户方法!路径:/api/users 时间:2021-02-03 09:14:50
    elAdmin- 2021-02-03 09:14:50 [http-nio-9292-exec-6] INFO  me.zhengjie.constant.LogInterceptor - 操作了查询部门方法!路径:/api/dept 时间:2021-02-03 09:14:50
    
  • 作者原链接 www.cnblogs.com/hxzxy/p/143…