【问题标题】:How validate method parameters are NotNull by default in spring method validation?spring方法验证中如何验证方法参数默认为NotNull?
【发布时间】:2019-04-22 23:15:09
【问题描述】:

Here 是有关方法验证的示例。所以检查方法参数是否为空我必须编写以下内容:

import org.springframework.validation.annotation.Validated

@Validated
public class SomeClass {
    public void myMethod(@NotNull Object p1, @Nullable Object p2) {}
}

有没有办法设置spring bean验证以使所有参数默认验证为@NotNull?例如。当p1null 时,以下将失败:

import org.springframework.validation.annotation.Validated

@Validated
public class SomeClass {
    public void myMethod(Object p1, @Nullable Object p2) {}
}

有什么想法吗?

【问题讨论】:

  • 你到底想达到什么目标?
  • 减少方法参数的注解。

标签: java spring jsr380


【解决方案1】:

如果您希望 Spring 自动验证方法参数,请执行以下操作:

  1. org.hibernate.validator:hibernate-validator 添加到您的依赖项中
  2. @javax.validation.constraints.NotNull标记所需的方法参数

那么当你调用这样的方法并且没有提供所需的参数时,你会得到一个javax.validation.ConstraintViolationException 异常。

另一种更简单的方法是使用 Lombok 的:只需用 @lombok.NonNull 标记方法参数,Lombok 将完成剩下的工作。

【讨论】:

  • mark the required methods with 这是我想跳过的内容,不管是 spring 还是 hgibernate 验证。
  • @Cherry 你希望所有方法参数都默认是必需的吗?
【解决方案2】:

您可以编写自己的@NotNullArgs 注解作为选项

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface NotNullArgs {
}

和方面:

@Aspect
@Component
public class ArgumentMatcher {

  @Around(value = "@annotation(NotNullArgs)")
  public Object verifyAuthorities(ProceedingJoinPoint joinPoint) throws Throwable {
     final Optional<Object> nullArg = Arrays.stream(joinPoint.getArgs())
       .filter(Objects::isNull)
       .findFirst();

     if (nullArg.isPresent() && joinPoint.getArgs().length > 0) {
       throw new IllegalArgumentException(); // or NPE
     } else {
       return joinPoint.proceed();
     }
  }
}

那么你可以这样使用它:

@NotNullArgs
void methodToCall(Obj arg1, Obj arg2) { .... }

这只是一个草稿,但您可以以此代码为起点

【讨论】:

    猜你喜欢
    • 2019-01-07
    • 2014-08-13
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-26
    相关资源
    最近更新 更多