Spring Boot 结合自定义注解实现拦截器

该文章展示了如何在JavaSpringMVC环境中创建自定义注解,用于标记控制器方法,并实现一个拦截器来处理这些带有注解的方法。注解包含了多个属性如value、model、code等,同时使用了TimeUnit和Season枚举类。拦截器在preHandle方法中检查并打印出注解信息。
摘要由CSDN通过智能技术生成

自定义注解

package com.test.interceptor.config.annotion;
import com.test.interceptor.customannotation.Season;
import java.lang.annotation.*;
import java.util.concurrent.TimeUnit;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface AnnotationTst {
    String model() default "";
    String value() default "";
    String[] code() default "";
    TimeUnit timeUnit() default TimeUnit.SECONDS;
    Season season() default Season.SUMMER;
    Season[] enm() default {Season.SUMMER,Season.SPRING};
}

自定义拦截器

package com.test.interceptor.interceptor;
import com.test.interceptor.config.annotion.AnnotationTst;
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;
import java.util.Objects;

@Component
public class ProjectInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        // 判断 handler是否是HandlerMethod
        if(handler instanceof HandlerMethod) {
            HandlerMethod hm = (HandlerMethod)handler;
            Method method = hm.getMethod();
            // 判断要执行的方法是否包含自定义注解
            if(hm.hasMethodAnnotation(AnnotationTst.class)) {
                AnnotationTst annotationTst = method.getAnnotation(AnnotationTst.class);
                if(Objects.nonNull(annotationTst)) {
                    System.out.println(annotationTst);
                }
            }
        }
        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 {
    }
//     boolean isAnnotation = clazz.isAnnotationPresent(SysLog.class);
//        if (isAnnotation) {
//            SysLog sysLog = clazz.getAnnotation((SysLog.class));
//            String model = sysLog.model();
//            String name = sysLog.name();
//        }

//     // 方法
//        Method[] methods = clazz.getMethods();
//        for (Method method : methods) {
//            boolean isAnnotation = method.isAnnotationPresent(SysLog.class);
//            if (isAnnotation) {
//                System.out.println("方法:" + method.getName() + "存在自定义注解");
//                SysLog sysLog = method.getAnnotation((SysLog.class));
//                String model = sysLog.model();
//                String name = sysLog.name();
//            }
//        }

//    for (Field field : fields) {
//            boolean isAnnotation = field.isAnnotationPresent(SysLog.class);
//            if (isAnnotation) {
//                System.out.println("字段:" + field.getName() + "存在自定义注解");
//                SysLog sysLog = field.getAnnotation((SysLog.class));
//                String model = sysLog.model();
//                String name = sysLog.name();
//            }
//        }

//     Signature signature = proceedingJoinPoint.getSignature();
//        MethodSignature methodSignature = (MethodSignature) signature;
//        Method method = methodSignature.getMethod();
//        if (method != null) {
//            SysLog sysLog = method.getAnnotation(SysLog.class);
//            // 获取注解的属性值
//            String[] code = sysLog.code();
//            String name = sysLog.name();
//            String model = sysLog.model();
//            System.out.println("code:" + Arrays.toString(code));
//            System.out.println("name:" + name);
//            System.out.println("model:" + model);
//        }
//        return proceedingJoinPoint.proceed();
}

加载拦截器

package com.test.interceptor.config;

import com.test.interceptor.interceptor.ProjectInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class InterceptorConfigure implements WebMvcConfigurer {

    @Autowired
    private ProjectInterceptor projectInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(projectInterceptor).addPathPatterns("/student","/student/*");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
    }
}

枚举类

package com.test.interceptor.customannotation;

public enum Season {
    SPRING,SUMMER,AUTUMN,WINTER
}

MVC层

  /**
     * 查询所有数据
     *
     * @return 实例对象集合
     */
    @GetMapping
    @AnnotationTst(value="aa",model = "bb",code = {"1","2"},timeUnit = TimeUnit.DAYS,season = Season.SPRING,enm = {Season.AUTUMN,Season.WINTER})
    public ResponseEntity<List> queryAll() {
        return ResponseEntity.ok(this.studentService.queryAll());
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

最好的期待,未来可期

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值