Home > front end >  Java injection on parameter validation (without REST API call)
Java injection on parameter validation (without REST API call)

Time:12-01

I have a class A and I want to validate that the "id" is not more than 15 chars, so I am using @Size(min = 1, max = 15, message = "Error"):

public final class A {

    @Size(min = 1, max = 15, message = "Error")
    private final String id;
    private final String anotherString;
  ....
}

And I am using A like this below, with @Valid:

  public final class C {
    
    void methodThatUsesA(@Valid final A a, final B b)  {
    ...
    }
  }

Moreover if I call methodThatUsesA like this below, with a string that have more than 15 chars, the validation is not triggered and I don't know why:

 methodThatUsesA(new A("AZERTYUIOPQSDFGDFG", 'a'), new B()){}

Any help is accepted :)

CodePudding user response:

First, you need to create and provide a MethodValidationPostProcessor Spring-managed bean as follows:

@Configuration
public class MethodValidationConfig {

    @Bean
    public MethodValidationPostProcessor methodValidationPostProcessor() {
        return new MethodValidationPostProcessor();
    }
}

And then you need to add @Validated to your class as follows:

@Validated
public final class A {

    @Size(min = 1, max = 15, message = "Error")
    private final String id;
    private final String anotherString;
    
    ....
}

Keep in mind that this will only work if both A and C are Spring-managed beans.

  • Related