java - 如何在Spring中配置对@Valid的直接字段访问?

标签 java spring spring-mvc spring-web

如何告诉 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/

相关文章:

java - 在 Neo4j 中如何创建触发器?

Java - 在 GUI 中构建从输入到输出的数据流

java - 如何在 grails 中查询特定对象类型的继承对象集合?

EntityManager 中的 spring jpa NullPointerException

java - Spring 4 - 资源映射 - 未找到处理程序方法

java - spring mvc mongodb 中请求的资源()不可用

java - 不知道无限循环在哪里

Java Spring 类路径 :Spring does not find properties file in the class path

java - 运行 spring 应用程序时出错( org.h2.jdbc.JdbcSQLNonTransientConnectionException : URL format error)

java - Spring MVC XML View