西瓜の

-人类是因为记录才进入文明-

2019/06/15
20:51
technology

spring boot使用aop进行入参回参打印和bean参数校验

由于在项目中controller层频繁用到log打印入参和回参以及入参的DTO校验,存在很多的重复操作。
最近了解到了aop相关的知识,决定写一个切面来替代这些重复操作。
因为我这里是spring boot 项目,所以加入依赖:

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

创建自定义注解@BeanValidated:

/**
 * BeanValidated
 * V1.0
 * 用于方法的参数校验(第一个参数)以及入参和回参的打印
 *
 * @Author watermelon
 * @CreateDate 2019/5/17
 * @Description BeanValidated
 */
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface BeanValidated {
    Class<?>[] value() default {};
}

创建切面处理类:

/**
 * AOPValidation
 *
 * @Author watermelon
 * @CreateDate 2019/5/17
 * @Description AOPValidation
 */
@Aspect
@Configuration
@Slf4j
public class AOPValidation {

 //切点
@Pointcut("@annotation(com.watermelon.basic.bean.annotation.BeanValidated)")
    public void execute() {

    }

    //环绕
    @Around("execute() && @annotation(validated)")
    public Object around(ProceedingJoinPoint pjp, BeanValidated validated) throws Throwable {

        Signature signature = pjp.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        //方法名
        String methodName = signature.getName();
        //类名
        String className = signature.getDeclaringTypeName();
        //获取所有参数名
        String[] parameterNames = methodSignature.getParameterNames();
        log.info("{}.{}:入参{}={}", className, methodName, Arrays.toString(parameterNames), Arrays.toString(pjp.getArgs()));
        try {
            //注解中填入的class
            Class<?>[] value = validated.value();
            if (value.length > 0) {
                Object o = pjp.getArgs()[0];
                if (o != null) {
                    //校验Util
                    BeanValidation.validate(o, value);
                }
            }
        } catch (ArrayIndexOutOfBoundsException e) {
            log.info("{}.{}:该方法入参为空!", className, methodName);
        } catch (ClassCastException e) {
            log.info("{}.{}:参数对象未继承于校验指定的BaseDTO!", className, methodName);
        } catch (IllegalArgumentException e) {
            log.info("{}.{}:参数校验出错={}", className, methodName, e.getMessage());
            //这里可以不做判断直接返回你已知或者确定的返回类型
            //下面的ResultBase、successMvView、failView是自己封装的返回Util
            Class returnType = methodSignature.getReturnType();
            //根据返回值类型返回错误信息
            if (ResultBase.class.isAssignableFrom(returnType)) {//判断returnType是否是ResultBase的子类
                return ResultBase.fail(e.getMessage());
            } else if (returnType == ModelAndView.class) {
                return BaseController.successMvView("404", "error", e.getMessage());
            } else {
                return BaseController.failView(e.getMessage());
            }
        } catch (ConstraintViolationException e) {
            log.info("{}.{}:参数校验失败={}", className, methodName, e.getMessage());
        }
        //执行方法
        Object proceed = pjp.proceed();
        log.info("{}.{}:返回{}", className, methodName, proceed);
        return proceed;
    }
}

ps:

使用@Slf4j注解需要导入lombok注解,以及在idea中开启lombok,或者也可以自己获取logger

 <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
             <version>1.18.2</version>
        </dependency>

BeanValidation:

/**
 * bean验证
 *
 * @Author watermelon
 * @CreateDate 2019/1/17
 * @Description bean验证
 */
public class BeanValidation {

    /**
     * 默认propertyPath与message分隔符.
     */
    public static final String DEFAULT_SEPARATOR = "";

    /**
     * 默认错误消息间分隔符.
     */
    public static final String ERRORMESSAGES_SEPARATOR = ", ";
    private static ValidatorFactory validatorFactory;

    static {
        validatorFactory = Validation.buildDefaultValidatorFactory();
    }

    /**
     * 调用JSR303的validate方法, 验证失败时抛出ConstraintViolationException, 而不是返回constraintViolations.
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static void validate(Object object, Class<?>... groups) throws ConstraintViolationException {
        String errorMessages = null;
        Set constraintViolations = getValidator().validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            errorMessages = extractPropertyAndMessageAsString(constraintViolations);
            // 有错误信息则抛出IllegalArgumentException异常.
            if (isNotBlank(errorMessages)) {
                System.out.println("校验返回信息errorMessages=" + errorMessages);
                throw new IllegalArgumentException(errorMessages);
            }
        }
    }

    /**
     * 辅助方法, 转换Set<ConstraintViolations>为String.
     */
    @SuppressWarnings("rawtypes")
    public static String extractPropertyAndMessageAsString(Set<? extends ConstraintViolation> constraintViolations) {
        return extractPropertyAndMessageAsString(constraintViolations, DEFAULT_SEPARATOR);
    }

    /**
     * 辅助方法, 转换Set<ConstraintViolation>为String.
     */
    @SuppressWarnings("rawtypes")
    public static String extractPropertyAndMessageAsString(Set<? extends ConstraintViolation> constraintViolations, String separator) {
        StringBuilder errorMessages = new StringBuilder();

        int index = 0;
        for (ConstraintViolation violation : constraintViolations) {
            if (0 != index) {
                errorMessages.append(ERRORMESSAGES_SEPARATOR);
            }

            errorMessages.append(violation.getPropertyPath()).append(separator).append(violation.getMessage());
            index++;
        }
        return errorMessages.toString();
    }

    public static Validator getValidator() {
        return validatorFactory.getValidator();
    }

    private static boolean isNotBlank(String str) {
        int len;
        if (str != null && (len = str.length()) != 0) {
            for (int i = 0; i < len; ++i) {
                if (!Character.isWhitespace(str.charAt(i))) {
                    return true;
                }
            }
            return false;
        } else {
            return false;
        }
    }
}

运用切面还可以完成权限验证等功能,大家可以自己试着写一下。