admin
2020-12-02 a2fe11f549f52e887937dbdb63d967a09d3a3f21
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package com.ks.lucky.aspect;
 
import com.beust.jcommander.internal.Lists;
import com.google.gson.Gson;
import com.ks.lib.common.exception.ParamsException;
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.aspectj.lang.reflect.MethodSignature;
import org.hibernate.validator.messageinterpolation.ResourceBundleMessageInterpolator;
import org.hibernate.validator.resourceloading.PlatformResourceBundleLocator;
import org.springframework.stereotype.Component;
 
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.List;
import java.util.Set;
 
/**
 * 参数检查AOP
 */
@Aspect
@Component
public class LuckyParamsCheckAspect {
    private static Validator validator;
 
    static {
        validator = Validation.byDefaultProvider().configure()
                .messageInterpolator(new ResourceBundleMessageInterpolator(
                        new PlatformResourceBundleLocator("validationMessages"))) //手动指定校验提示资源(默认在resource目录下ValidationMessages.properties)
                .buildValidatorFactory().getValidator();
    }
 
    @Pointcut("@annotation(org.springframework.validation.annotation.Validated))")
    public void validateMethod() {
    }
 
    @Before("validateMethod()")
    public void before(JoinPoint joinPoint) throws ParamsException {
        Object[] args = joinPoint.getArgs();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        // 执行方法参数的校验
        Set<ConstraintViolation<Object>> constraintViolations = validator.forExecutables().validateParameters(joinPoint.getThis(), signature.getMethod(), args);
        List<String> messages = Lists.newArrayList();
        for (ConstraintViolation<Object> error : constraintViolations) {
            messages.add(error.getMessage());
        }
        if (!messages.isEmpty()) {
            throw new ParamsException(ParamsException.CODE_PARAMS_NOT_ENOUGH, new Gson().toJson(messages.get(0)));
        }
    }
 
 
}