Spring validator + AOP 实现自动参数校验

背景:

使用Spring validator做Controller的参数校验的时候,每次都要手动在Controller方法中加入BlindingResult blindingResult参数来获取校验结果,然后对校验结果做处理。如果使用AOP则可以自动校验。

 

解决方案:

package com.example.aspect;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import javax.annotation.Resource;
import javax.validation.ConstraintViolation;
import java.util.Iterator;
import java.util.Set;

/**
 * FileName: ValidatorAspect
 * DESCRIPTION: Controller层入参校验切面
 *
 * @author: SLY
 * @create: 2019/3/25
 */
@Component
@Aspect
@Slf4j
public class ValidatorAspect {

    @Resource
    private LocalValidatorFactoryBean localValidatorFactoryBean;

    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)" +
            "||@annotation(org.springframework.web.bind.annotation.GetMapping)" +
            "||@annotation(org.springframework.web.bind.annotation.PostMapping)" +
            "||@annotation(org.springframework.web.bind.annotation.PutMapping)")
    public void paramValidatePointCut(){};

    @Before("paramValidatePointCut() && args(request,..)")
    public void validateParam(JoinPoint joinPoint, Request request) {
        Set> validErrs = localValidatorFactoryBean.validate(request);
        Iterator> iterator = validErrs.iterator();
        StringBuilder sb = new StringBuilder();
        while (iterator.hasNext()) {
            ConstraintViolation constraintViolation = iterator.next();
            String error = constraintViolation.getMessage();
            sb.append(iterator.hasNext() ? error + ";" : error);
        }
        if (!validErrs.isEmpty()) {
            throw new BussinessException(ResultEnum.ERROR.getCode(), sb.toString());
        }
    }

}

 

你可能感兴趣的:(Spring临床经验)