AOP实现参数的判空问题
不想每次都去判断必传的参数是否为空,写代码太繁琐了,正好最近用了AOP实现权限控制,依葫芦画瓢,现在用它实现参数的判空,至于AOP的原理之类,自己百度了解一下吧
1. NullDisable注解
@Documented @Retention(RUNTIME) @Target({ TYPE, METHOD, PARAMETER }) public @interface NullDisable { }
2. ParamException
public class ParamException extends RuntimeException{ private static final long serialVersionUID = -4993447045204262508L; public ParamException(){ super("参数不能为空"); } public ParamException(String message){ super(message); } }
3. ValidParameter
import java.lang.reflect.Method; import java.lang.reflect.Parameter; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.stereotype.Component; import com.test.exception.ParamException; @Aspect @Component public class ValidParameter { //com.test.controller包下所有的类 @Pointcut("execution(* com.test.controller..*.*(..)))") public void valid() {}; @Around("valid()") public Object check(ProceedingJoinPoint joinPoint) throws Exception{ MethodSignature signature = (MethodSignature) joinPoint.getSignature(); Method method = signature.getMethod(); //获得参数类型 final Parameter[] parameters = method.getParameters(); //参数值 final Object[] args = joinPoint.getArgs(); //参数名称 String[] names = signature.getParameterNames(); for(int i = 0; i < parameters.length; i++) { Parameter parameter = parameters[i]; Object annotation = parameter.getAnnotation(NullDisable.class); //含有不为空的注解的参数 if (null != annotation) { if (null == args[i]) { throw new ParamException(String.format("参数:%s,不能为空", names[i])); } } }
return joinPoint.proceed(); } }
2. controller
@GetMapping("test") @PermissionSetter public Object test( @RequestParam(value = "name") String name, @NullDisable @RequestParam(value = "date") @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") LocalDateTime date ){ return ""; }
postman测试