不调用标记为@AssertTrue的方法

时间:2017-12-27 16:35:57

标签: java spring validation bean-validation hibernate-validator

我有以下课程来验证:

@Document(collection = "settings")
public class Settings {
    @NotEmpty
    private String[] allowableExtensions;
    ...
    @AssertTrue(message = "Each extension must be alphanumeric string with length {2,4}")
    public boolean assertTrue() {
        for (String extension : allowableExtensions) {
            if (extension == null || extension.matches("^[a-zA-Z0-9]{2,6}$")) {
                return false;
            }
        }
        return true;
    }
}

并跟随控制器:

@PostMapping(value = "/settings/update", consumes = "application/json")
public ResponseEntity<?> updateSettings(@RequestBody @Valid Settings settings, BindingResult bindingResult) {
   if(bindingResult.hasErrors()){
        return ResponseEntity.badRequest().body(bindingResult.getAllErrors().get(0).getDefaultMessage());
   }
}

我没有找到预期的错误,并将断点放入assertTrue方法,但它没有调用。

我错了什么?

1 个答案:

答案 0 :(得分:2)

assertTrue方法不遵循JavaBean约定,并且您没有进行方法验证,因此它永远不会被调用,并且您不会得到您期望的违规。例如,如果您将Setting类更改为类似

public class Settings {

    @NotEmpty
    private String[] allowableExtensions;

    @AssertTrue(message = "Each extension must be alphanumeric string with length {2,4}")
    public boolean isAssertTrue() {
        for ( String extension : allowableExtensions ) {
            if ( extension == null || extension.matches( "^[a-zA-Z0-9]{2,6}$" ) ) {
                return false;
            }
        }
        return true;
    }
}

您应该调用此Settings#isAssertTrue方法并验证结果。