如何在Spring的@Valid上配置直接字段访问?

时间:2019-01-10 11:50:24

标签: java spring spring-mvc spring-web

如何无需使用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() {
        //...
    }

2 个答案:

答案 0 :(得分:2)

您必须将Spring DataBinder配置为使用直接字段访问。

@ControllerAdvice    
public class ControllerAdviceConfiguration {
    @InitBinder
    private void initDirectFieldAccess(DataBinder dataBinder) {
        dataBinder.initDirectFieldAccess();
    }
}

答案 1 :(得分:0)

尝试这样的事情:

@Access(AccessType.FIELD)
public String name;