Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure direct field access on @Valid in Spring?

How can I tell spring-web to validate my dto without having to use getter/setter?

@PostMapping(path = "/test")
public void test(@Valid @RequestBody WebDTO dto) {

}

public class WebDTO {
   @Valid //triggers nested validation
   private List<Person> persons;

   //getter+setter for person

   @JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
   public static class Person {
         @NotBlank
         public String name;
         public int age;
   }
}

Result:

"java.lang.IllegalStateException","message":"JSR-303 validated property 
    'persons[0].name' does not have a corresponding accessor for Spring data 
    binding - check your DataBinder's configuration (bean property versus direct field access)"}

Special requirement: I still want to add @AssertTrue on boolean getters to provide crossfield validation, like:

    @AssertTrue
    @XmlTransient
    @JsonIgnore
    public boolean isNameValid() {
        //...
    }
like image 966
membersound Avatar asked Jan 10 '19 11:01

membersound


1 Answers

you have to configure Spring DataBinder to use direct field access.

@ControllerAdvice    
public class ControllerAdviceConfiguration {
    @InitBinder
    private void initDirectFieldAccess(DataBinder dataBinder) {
        dataBinder.initDirectFieldAccess();
    }
}
like image 89
Elgayed Avatar answered Sep 20 '22 17:09

Elgayed