| | |
| | | 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.ArrayList; |
| | | import java.util.List; |
| | | import java.util.Set; |
| | | |
| | | /** |
| | | * 参数检查AOP |
| | | */ |
| | | @Aspect |
| | | @Component |
| | | public class LuckyParamsCheckAspect { |
| | | private static Validator validator; |
| | | |
| | |
| | | } |
| | | |
| | | @Pointcut("@annotation(org.springframework.validation.annotation.Validated))") |
| | | private void validateMethod() { |
| | | public void validateMethod() { |
| | | } |
| | | |
| | | @Before("validateMethod()") |
| | |
| | | MethodSignature signature = (MethodSignature) joinPoint.getSignature(); |
| | | // 执行方法参数的校验 |
| | | Set<ConstraintViolation<Object>> constraintViolations = validator.forExecutables().validateParameters(joinPoint.getThis(), signature.getMethod(), args); |
| | | List<String> messages = Lists.newArrayList(); |
| | | List<String> messages = new ArrayList<>(); |
| | | for (ConstraintViolation<Object> error : constraintViolations) { |
| | | messages.add(error.getMessage()); |
| | | } |
| | | if (!messages.isEmpty()) { |
| | | throw new ParamsException(ParamsException.CODE_PARAMS_NOT_ENOUGH, new Gson().toJson(messages)); |
| | | throw new ParamsException(ParamsException.CODE_PARAMS_NOT_ENOUGH, new Gson().toJson(messages.get(0))); |
| | | } |
| | | } |
| | | |