在存在 @Valid 注释的嵌套对象内部使用 @AssertTrue 时会出现 JSR-303 问题

Aka*_*ari 4 java spring-mvc bean-validation spring-boot

我的自定义 DTO 类如下:

public class TestDto1 {

private String key;
private String val;

@AssertTrue
private boolean isValid() {
    return key !=null || val !=null;
}public class TestDto1 {

private String key;
private String val;

@AssertTrue
private boolean isValid() {
    return key !=null || val !=null;
}
Run Code Online (Sandbox Code Playgroud)

我的家长 DTO 课程:

public class TestDto {


private String id;

@Valid
private TestDto1 tes;

public TestDto1 getTes() {
    return tes;
}

public void setTes(TestDto1 tes) {
    this.tes = tes;
}

public String getId() {
    return id;
Run Code Online (Sandbox Code Playgroud)

运行应用程序并使用以下 JSON 访问 api 时,出现以下错误:

{
"id":"1234",
"tes":{
    
}
Run Code Online (Sandbox Code Playgroud)

}

  JSR-303 validated property 'tes.valid' does not have a corresponding accessor for Spring data binding - check your DataBinder's configuration (bean property versus direct field access)] with root cause

org.springframework.beans.NotReadablePropertyException: Invalid property 'tes.valid' of bean class [com.example.thirdparty.controller.TestDto]: Bean property 'tes.valid' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
Run Code Online (Sandbox Code Playgroud)

请让我知道这里需要做什么

Pan*_*kos 6

这不是一个经过验证的字段,而是一种从该方法中作为虚拟字段读取的方法。

我认为该方法必须声明为公共才能进行验证

 @AssertTrue
 public boolean isValid() {
     return key !=null || val !=null;
 }
Run Code Online (Sandbox Code Playgroud)

  • 通过公开该方法,它起作用了:)。谢谢 (2认同)