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() {
//...
}
you have to configure Spring DataBinder to use direct field access.
@ControllerAdvice
public class ControllerAdviceConfiguration {
@InitBinder
private void initDirectFieldAccess(DataBinder dataBinder) {
dataBinder.initDirectFieldAccess();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With