spring的aop如何获取方法中带注解的参数然后进行统一验证

我要进行service层参数的统一验证, 我的service层的方法中参数类型不固定, 数量也不固定, 如下:

int createUser(@ParamValid User user){}

int createGroup(@ParamValid Group group, OtherParam param);

@ParamValid是我的自定义注解, 以上2个需要验证的参数的实现如下:

public class User {
    @NotNull(message = "姓名不能为空")
    @Length(min=1, max = 5, message = "名字长度必须是1~5")
    private String name;

    @NotNull(message = "age不能为空")
    @Max(value = 100, message = "年龄不能大于100岁")
    private int age;
}

//Group ........

我想通过AOP获取service层的所有方法中加@MyValid的参数, 然后进行统一验证改如何弄呢

@Aspect
@Component
public class ValidWebParamAspect {
    private final Logger logger = Logger.getLogger(getClass());

    @Pointcut("@args(com.surdoc.common.validation.ParamValid)") //对嘛
    public void validWebParam(){}

    /**
     * 在执行切点前执行
     * @param joinPoint
     */
    @Before("validWebParam()")
    public void validWebParamBefore(JoinPoint joinPoint){
        // 获取方法中只有 @ParamValid的参数
        // 执行 验证, 验证失败抛出异常
        // 怎么获取上面的 @ParamValid User user 和  @ParamValid Group group
    }
}
阅读 14.5k
2 个回答

MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Annotation[][] methodAnnotations = method.getParameterAnnotations();

我也遇到这个问题,不知道楼主有没有解决,但我知道 @args 注解在 Pointcut 声明中,不是这样用的,详情可见 Spring Docs

@args - limits matching to join points (the execution of methods when using Spring AOP) where the runtime type of the actual arguments passed have annotations of the given type(s)

它也给出了一个例子:

any join point (method execution only in Spring AOP) which takes a single parameter, and where the runtime type of the argument passed has the @Classified annotation:

@args(com.xyz.security.Classified)

另外,我找到一篇介绍 PointCut 表达式的博客,供楼主参考 链接

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题