我有以下课程来验证:
@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方法,但它没有调用。
我错了什么?
答案 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
方法并验证结果。