springboot aop方式实现接口入参校验的示例代码
更新时间:2023年08月24日 14:58:06 作者:夜空下的星
在实际开发项目中,我们常常需要对接口入参进行校验,本文主要介绍了springboot aop方式实现接口入参校验的示例代码,具有一定的参考价值,感兴趣的可以了解一下
一、前言
在实际开发项目中,我们常常需要对接口入参进行校验,如果直接在业务代码中进行校验,则会显得代码非常冗余,也不够优雅,那么我们可以使用aop的方式校验,这样则会显得更优雅。
二、如何实现?
1.添加maven依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
2.定义一个工具类ValidationUtil
import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import javax.validation.ConstraintViolation; import javax.validation.Validation; import javax.validation.Validator; import javax.validation.ValidatorFactory; import java.util.ArrayList; import java.util.List; import java.util.Set; public class ValidationUtil { private static ValidationUtil util; private Validator validator; public ValidationUtil() { // TODO Auto-generated constructor stub ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); this.validator = factory.getValidator(); } /** * @return the validator */ public Validator getValidator() { return validator; } public static ValidationUtil getValidationUtil() { if (util == null) { util = new ValidationUtil(); } return util; } public static List<CheckErrorResultDto> validate(Object o) { Set<ConstraintViolation<Object>> set = ValidationUtil .getValidationUtil().getValidator().validate(o); List<CheckErrorResultDto> errorList = null; HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder .getRequestAttributes()).getRequest(); for (ConstraintViolation<Object> cv : set) { if (errorList == null) { errorList = new ArrayList<CheckErrorResultDto>(); } String message = MessageResolver.getMessage(request, cv.getMessage()); errorList.add(new CheckErrorResultDto(cv.getPropertyPath() .toString(), message)); } return errorList; } public static List<CheckErrorResultDto> validate(Object o,Class<?> ...c) { Set<ConstraintViolation<Object>> set = ValidationUtil .getValidationUtil().getValidator().validate(o,c); List<CheckErrorResultDto> errorList = null; HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder .getRequestAttributes()).getRequest(); for (ConstraintViolation<Object> cv : set) { if (errorList == null) { errorList = new ArrayList<CheckErrorResultDto>(); } String message = MessageResolver.getMessage(request, cv.getMessage()); errorList.add(new CheckErrorResultDto(cv.getPropertyPath() .toString(), message)); } return errorList; }
3.校验错误信息实体类。
import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; @Data @Builder @AllArgsConstructor @NoArgsConstructor public class CheckErrorResultDto { private String fieldName; private String msg; }
4.编写校验AOP
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.List; @Order(1) @Aspect @Component @EnableAspectJAutoProxy(exposeProxy=true) public class ValidAop { /** * 校验传入实体 * * @param pjp * @throws Throwable */ @Around("@annotation(com.smartcitysz.dp.dataasset.aop.annotation.Valid)") public Object aroundExec(ProceedingJoinPoint pjp) throws Throwable { MethodSignature ms = (MethodSignature) pjp.getSignature(); Method method = ms.getMethod(); Valid annotation = method.getAnnotation(Valid.class); if (annotation != null) { List<CheckErrorResultDto> errorList=new ArrayList<CheckErrorResultDto>(); Object[] args=pjp.getArgs(); Class<?>[] checkToken = annotation.value(); Class<?>[] group = annotation.group(); for (Class c : checkToken) { for (Object obj : args) { if (c == obj.getClass()) { List<CheckErrorResultDto> result=null; if(group.length<1){ result= ValidationUtil.validate(obj); }else{ result= ValidationUtil.validate(obj,group); } if(result!=null) errorList.addAll(result); } } } if(errorList.size()>0){ ResponseData vo=new ResponseData(); vo.setCode(ApiCodeEnum.ILLEGAL_PARAMETER.getCode()); vo.setMsg(ApiCodeEnum.ILLEGAL_PARAMETER.getMsg()); vo.setData(errorList); return vo; } } return pjp.proceed(); } }
5.定义一个校验注解Valid
import java.lang.annotation.*; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface Valid { Class<?>[] value() default {}; Class<?>[] group() default {}; }
6.最后在Controller定义的接口上加上注解指定要校验的对象即可。
到此这篇关于springboot aop方式实现接口入参校验的示例代码的文章就介绍到这了,更多相关springboot aop接口入参校验内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
相关文章
python pipreqs工具生成requirements.txt文件使用详解
这篇文章主要为大家介绍了python pipreqs工具生成requirements.txt文件使用详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-12-12
最新评论