How validate method parameters are NotNull by default in spring method validation?

4.5k views Asked by At

Here is example about method validation. So check method paramerter as not null I have to write the follolwing:

import org.springframework.validation.annotation.Validated

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

Is there a way to setup spring bean validation to make all parameters validated as @NotNull by default? E.g. the following will fail when p1 is null:

import org.springframework.validation.annotation.Validated

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

Any ideas?

2

There are 2 answers

0
Rostyslav Barmakov On

You can write your own @NotNullArgs annotation as an option

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

And aspect:

@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();
     }
  }
}

Then you can use it like this:

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

It's just a draft, but you can use this code as a point to start

2
Adam Siemion On

If you would like Spring to automatically validate method arguments do this:

  1. add org.hibernate.validator:hibernate-validator to your dependencies
  2. mark the required method arguments with @javax.validation.constraints.NotNull

then when you call such method and do not provide the required argument you will get a javax.validation.ConstraintViolationException exception.

another approach, a lot easier, is to use Lombok's: just mark the method argument with @lombok.NonNull and Lombok will do the rest.