此方式并不是特别友好:
如果掌握程度可以的话可以看看我的另外一篇配置化方式:
校验规则引擎设计-校验中心化(改进版)_haohaounique的博客-CSDN博客_校验规则 设计
场景:自定义注解校验参数,写在类上的注解;针对某类型的校验
1.自定义注解,注解放在方法上:ElementType.METHOD,如果需要放在类上可以点进去看看枚举
2.自定义拦截器或者使用appliacatonContext做一些处理
import java.lang.annotation.*;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface UserIdAnnotation {
String userId();
}
拦截器:
import com.check.utils.UserIdAnnotation;
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;
/**
* description:userId拦截器
*/
@Component
@Slf4j
public class UserIdInterceptHandler implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (handler instanceof HandlerMethod) {
UserIdAnnotation methodAnnotation = ((HandlerMethod) handler).getMethodAnnotation(UserIdAnnotation.class);
if (methodAnnotation != null) {
String userId = request.getParameter(methodAnnotation.userId());
/**
* 判断redis缓存中是否存在,存在放行,不存在则拦截
*/
log.info("userId:{}", userId);
}
}
return HandlerInterceptor.super.preHandle(request, response, handler);
}
}
使拦截器生效
import com.check.intercept.UserIdInterceptHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* description:
*/
@Component
public class WebConfig implements WebMvcConfigurer {
@Autowired
private UserIdInterceptHandler handler;
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(handler);
}
}
测试
@UserIdAnnotation(userId = "uuid") @RequestMapping(value = "addOrderInfo") public Map<String, Object> addOrderInfo(Map<String, Object> map) { return null; }
结果
2022-03-22 19:16:20.257 INFO 21672 --- [nio-9002-exec-1] c.c.intercept.UserIdInterceptHandler : userId:null