用于检测get请求的时候对其进行判空处理
1、新建两个注解
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface NotNullGetRequest {
String value();
}
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Inherited
public @interface CheckParamController {
}
2、写aop,可以根据自己的需要,再写判断长度的
@Slf4j
@Aspect
@Component
public class NotNullGetRequestAop {
@Pointcut("@annotation(com.richstonedt.cmgde2eas.commons.annotation.CheckParamController)")
public void paramCheck(){}
@Before("paramCheck())")
public void doBefore(JoinPoint joinPoint) {
if(joinPoint.getArgs().length > 0){
Object target = joinPoint.getArgs()[0];
Field[] declaredFields = target.getClass().getDeclaredFields();
Class<?> aClass = target.getClass();
Arrays.stream(declaredFields).forEach(field->{
if (field.isAnnotationPresent(NotNullGetRequest.class)){
Object invoke = null;
try {
invoke = aClass.getDeclaredMethod("get" + BasicUtils.getFirstToUpperCase(field.getName()))
.invoke(target);
} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) {
log.error(ex.getMessage());
}
if (invoke instanceof List && ((List) invoke).isEmpty()){
throw new BusinessException(field.getAnnotation(NotNullGetRequest.class).value());
}
if (invoke == null || invoke.equals("")){
throw new BusinessException(field.getAnnotation(NotNullGetRequest.class).value());
}
}
});
}
}
}
3、用法,现在实体类标记,之后再到controller中标记就好了
@Schema(title = "开始时间")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@NotNullGetRequest("开始时间不能为空")
private LocalDateTime beginTime;
@Schema(title = "结束时间")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@NotNullGetRequest("结束时间不能为空")
private LocalDateTime endTime;
@GetMapping("/getData")
@CheckParamController
public ResponseResult<PageInfo<User>> getData(UserParams params){
return ResponseResult.ok(service.page(params));
}
测试