如何无需使用getter / setter告诉spring-web
验证我的dto?
@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)"}
特殊要求:我仍然想在布尔型getter上添加@AssertTrue
以提供跨域验证,例如:
@AssertTrue
@XmlTransient
@JsonIgnore
public boolean isNameValid() {
//...
}
答案 0 :(得分:2)
您必须将Spring DataBinder配置为使用直接字段访问。
@ControllerAdvice
public class ControllerAdviceConfiguration {
@InitBinder
private void initDirectFieldAccess(DataBinder dataBinder) {
dataBinder.initDirectFieldAccess();
}
}
答案 1 :(得分:0)
尝试这样的事情:
@Access(AccessType.FIELD)
public String name;