pom依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
aop切面
import net.logstash.logback.encoder.org.apache.commons.lang.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
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 org.springframework.validation.annotation.Validated;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Objects;
import java.util.Set;
/**
* @author chunyang.leng
* @date 2021/1/26 9:09 上午
*/
@Aspect
@Component
public class ParamCheckAOP {
@Pointcut("execution(public * com.xxx.xxx.controller.*.*(..))")
public void pointcut() {
}
@Around(value = "pointcut()")
public Object validation(ProceedingJoinPoint joinPoint) throws Throwable {
Object[] args = joinPoint.getArgs();
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
Method declaredMethod = joinPoint.getTarget().getClass().getDeclaredMethod(method.getName(), method.getParameterTypes());
Annotation[][] parameterAnnotations = declaredMethod.getParameterAnnotations();
for (int i = 0; i < parameterAnnotations.length; i++) {
Object param = args[i];
int length = parameterAnnotations[i].length;
for (int j = 0; j < length; j++) {
Annotation annotation = parameterAnnotations[i][j];
if (annotation instanceof Validated) {
if (Objects.isNull(param)) {
// todo 自定义异常
throw new ParamCheckException("必填项不能为空");
}
Validated validated = (Validated) annotation;
Class<?>[] classList = validated.value();
String validResult = valid(param, classList);
if (StringUtils.isNotEmpty(validResult)) {
// todo 自定义异常
throw new ParamCheckException(validResult);
}
}
}
}
return joinPoint.proceed();
}
private String valid(Object obj, Class[] clazz) {
ValidatorFactory validatorFactory = Validation.buildDefaultValidatorFactory();
Validator validator = validatorFactory.getValidator();
Set<ConstraintViolation<Object>> validate = validator.validate(obj, clazz);
StringBuffer stringBuffer = new StringBuffer();
validate.forEach(o -> {
String message = o.getMessage();
if (StringUtils.isNotBlank(message)) {
stringBuffer.append(message).append("\n");
}
});
return stringBuffer.toString();
}
}
自定义异常
/**
* @author chunyang.leng
* @date 2021/1/26 9:47 上午
*/
public class ParamCheckException extends RuntimeException{
private String message;
/**
* Constructs a new runtime exception with {@code null} as its
* detail message. The cause is not initialized, and may subsequently be
* initialized by a call to {@link #initCause}.
*/
public ParamCheckException(String message) {
super(message);
this.message = message;
}
@Override
public String getMessage() {
return message;
}
}
统一异常处理
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* @author chunyang.leng
* @date 2021/1/26 9:48 上午
*/
@RestControllerAdvice
public class ParamCheckControllerAdvice {
@ExceptionHandler(value = ParamCheckException.class)
public JSONObject check(ParamCheckException e){
JSONObject jsonObject = new JSONObject();
jsonObject.put("code","error");
jsonObject.put("message",e.getMessage());
return jsonObject;
}
}