SpringBoot-自定义注解,拦截器

创建自定义注解和拦截器,并使用拦截器去拦截带有自定义注解的类或方法。

创建自定义注解

创建自定义注解并增加一些属性

java 复制代码
package com.shore.my_spring_demo.common.annoation;

import java.lang.annotation.*;

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Verification {
    int flag() default 0;
}

创建拦截器

创建拦截器拦截带有该注解的方法

java 复制代码
package com.shore.my_spring_demo.common.interceptor;

import com.shore.my_spring_demo.common.annoation.Verification;
import com.shore.my_spring_demo.common.enums.VerificationFlagEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Slf4j
@Component
public class VerificationInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        return HandlerInterceptor.super.preHandle(request, response, handler);
        if (handler instanceof HandlerMethod handlerMethod) {
            Method method = handlerMethod.getMethod();
            if (method.isAnnotationPresent(Verification.class)) {
                Verification annotation = method.getAnnotation(Verification.class);
                VerificationFlagEnum.getByCode(annotation.flag());
                switch (VerificationFlagEnum.getByCode(annotation.flag())) {
                    case NO_VER -> {
                        log.info("跳过校验");
                    }
                    case LOGIN_VER -> {
                        log.info("登陆校验");
                    }
                    case TOKEN_VER -> {
                        log.info("token校验");
                    }
                    case PERMISSION_VER -> {
                        log.info("权限校验");
                    }
                    default -> {
                    }
                }
                return true;
            }
        }
        return true;
    }
}
java 复制代码
package com.shore.my_spring_demo.common.enums;

import lombok.AllArgsConstructor;
import lombok.Getter;

@Getter
@AllArgsConstructor
public enum VerificationFlagEnum {
    LOGIN_VER(1, "登陆校验"),
    TOKEN_VER(2, "token 校验"),
    PERMISSION_VER(3, "权限校验"),

    NO_VER(0, "跳过校验"),
    UNKNOWN(999, "未知校验"),

    ;

    private final int code;
    private final String value;

    public static VerificationFlagEnum getByCode(int code) {
        for (VerificationFlagEnum flagEnum : VerificationFlagEnum.values()) {
            if (flagEnum.getCode() == code) {
                return flagEnum;
            }
        }
        return UNKNOWN;
    }
}

配置拦截器

将拦截器注册到 Spring Boot 的拦截链中

java 复制代码
package com.shore.my_spring_demo.common.configure;

import com.shore.my_spring_demo.common.interceptor.VerificationInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;

@Configuration
public class MyConfig implements WebMvcConfigurer {
    @Resource
    private VerificationInterceptor verificationInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(verificationInterceptor);
    }
}

验证

java 复制代码
@Verification(flag = 3)
    @PostMapping("/query")
    public ApiResponse<UserVO> queryUser(@RequestBody UserReq req) {
        System.out.println(req);
        return ApiResponse.success(userService.getUserById(req.getId()));
    }
相关推荐
二哈赛车手4 小时前
新人笔记---ApiFox的一些常见使用出错
java·笔记·spring
栗子~~5 小时前
JAVA - 二层缓存设计(本地缓冲+redis缓冲+广播所有本地缓冲失效) demo
java·redis·缓存
YDS8295 小时前
DeepSeek RAG&MCP + Agent智能体项目 —— RAG知识库的搭建和接口实现
java·ai·springboot·agent·rag·deepseek
candyTong6 小时前
Claude Code 的 Edit 工具是怎么工作的
javascript·后端·架构
未若君雅裁6 小时前
MyBatis 一级缓存、二级缓存与清理机制
java·缓存·mybatis
AI人工智能+电脑小能手7 小时前
【大白话说Java面试题 第65题】【JVM篇】第25题:谈谈对 OOM 的认识
java·开发语言·jvm
GetcharZp7 小时前
GitHub 2.4 万 Star!D2 正在重新定义程序员画图方式
后端
阿维的博客日记7 小时前
Nacos 为什么能让配置动态生效?(涉及 @RefreshScope 注解)
java·spring
雨辰AI7 小时前
SpringBoot3 + 人大金仓读写分离 + 分库分表 + 集群高可用 全栈实战
java·数据库·mysql·政务
辰海Coding9 小时前
MiniSpring框架学习-完成的 IoC 容器
java·spring boot·学习·架构