如何告诉 spring-web
验证我的 dto 而不必使用 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;
}
}
结果:
"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)"}
特殊要求:我仍然想在 boolean getter 上添加 @AssertTrue
以提供跨域验证,例如:
@AssertTrue
@XmlTransient
@JsonIgnore
public boolean isNameValid() {
//...
}
最佳答案
您必须配置 Spring DataBinder 以使用直接字段访问。
@ControllerAdvice
public class ControllerAdviceConfiguration {
@InitBinder
private void initDirectFieldAccess(DataBinder dataBinder) {
dataBinder.initDirectFieldAccess();
}
}
关于java - 如何在Spring中配置对@Valid的直接字段访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54128075/