简体   繁体   English

不调用标记为@AssertTrue的方法

[英]method marked with @AssertTrue is not invoked

I have following class to validate: 我有以下课程来验证:

@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;
    }
}

and following controller: 并跟随控制器:

@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());
   }
}

I didn't find expected errors and put breakpoint into assertTrue method but it doesn't invoke. 我没有找到预期的错误并将断点放入assertTrue方法但它没有调用。

What do I wrong? 我错了什么?

assertTrue method does not follow JavaBean convention and you are not doing method validation, hence it is never called and you don't get the violation you are expecting. assertTrue方法不遵循JavaBean约定,并且您没有进行方法验证,因此它永远不会被调用,并且您不会得到您期望的违规。 So for example if you change your Setting class to something like 例如,如果您将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;
    }
}

you should get this Settings#isAssertTrue method called and result validated. 你应该调用这个Settings#isAssertTrue方法并验证结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM