JSR-303 非Controller验证

2018-08-01  本文已影响0人  rarexixi

自定义切面

ResultVo 自行定义

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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.*;

@Component
@Aspect
public class ValidateAspect {

    @Autowired
    Validator validator;

    /**
     * 设置标识
     */
    @Pointcut("execution(public * xxx.*.*(..))")
    public void invoke() {
    }


    /**
     * 环绕方法执行,proceedingJoinPoint.proceed()是执行环绕的方法
     *
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("invoke()")
    public Object Test(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {

        String methodName = "";
        try {
            MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
            Method method = methodSignature.getMethod();
            Parameter[] parameters = method.getParameters();
            Object[] args = proceedingJoinPoint.getArgs();

            List<String> messages = new LinkedList<>();
            for (int i = 0; i < parameters.length; i++) {
                Parameter parameter = parameters[i];
                Validated validated = parameter.getAnnotation(Validated.class);
                if (validated == null) continue;
                Set<ConstraintViolation<Object>> validateResults = validator.validate(args[i], validated.value());
                for(ConstraintViolation<Object> constraintViolation : validateResults) {
                    String message = constraintViolation.getMessage();
                    messages.add(message);
                }
            }
            if (!messages.isEmpty()) {
                return new ResultVo<>(messages);
            }

            return proceedingJoinPoint.proceed();
        } catch (Exception e) {
            // log
        }

        return new ResultVo<>("系统错误");
    }
}
上一篇下一篇

猜你喜欢

热点阅读