aspectjrt
1.8.9
com.alibaba
fastjson
1.2.58
org.springframework.boot
spring-boot-starter-web
新建自定义注解,ParamCheck.java :
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
-
@Author : JCccc
-
@CreateTime : 2020/5/14
-
@Description :
**/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface ParamCheck {
/**
- 是否非空,默认不能为空
*/
boolean notNull() default true;
/**
-
默认值
-
@return
*/
String defaultValue() default “”;
}
简单描述:
ElementType.PARAMETER 使用于参数
boolean notNull() default true; 要求参数不为空,默认开启,可以自己传
String defaultValue() default “”; 默认值,默认设置 “”,可以自己传
接下来新建 参数校验的AOP实现类,ParamValidAop.java:
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
/**
-
@Author : JCccc
-
@CreateTime : 2020/5/14
-
@Description :
**/
@Component
@Aspect
public class ParamValidAop {
/**
- 定义有一个切入点,范围为web包下的类
*/
@Pointcut(“execution(public * com.bsapple.vshop.controller….(…))”)
public void checkParam() {
}
@Before(“checkParam()”)
public void doBefore(JoinPoint joinPoint) {
}
/**
- 检查参数是否为空
*/
@Around(“checkParam()”)
public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
MethodSignature signature = ((MethodSignature) pjp.getSignature());
//得到拦截的方法
Method method = signature.getMethod();
//获取方法参数注解,返回二维数组是因为某些参数可能存在多个注解
Annotation[][] parameterAnnotations = method.getParameterAnnotations();
if (parameterAnnotations == null || parameterAnnotations.length == 0) {
return pjp.proceed();
}
//获取方法参数名
String[] paramNames = signature.getParameterNames();
//获取参数值
Object[] paranValues = pjp.getArgs();
//获取方法参数类型
Class<?>[] parameterTypes = method.getParameterTypes();
for (int i = 0; i < parameterAnnotations.length; i++) {