我想在类中使用注释。我使用javax.validation.constrants.*进行注释。

public final class EmailCredential implements Serializable {

    private static final long serialVersionUID = -1246534146345274432L;

    @NotBlank(message = "Sender must not be empty.")
    @Email
    private final String sender;

    @NotBlank(message = "Subject must not be empty.")
    private final String subject;

/// getters setters

}


他们都没有按预期工作。这意味着当调用以下API时,如果带注释的字段无效,则注释应引发错误。似乎没有注释可以检查字段。如何在普通班级中正确使用注释?

控制器:

@PostMapping(value = "/email/credentials", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Map<String, Object> emailCredentials(@RequestBody EmailCredential emailCredential) {
        return emailService.setCredentials(emailCredential);
    }

最佳答案

在您的情况下,必须指定要触发验证。
因此,在要验证的参数上添加@Valid批注,例如:

import javax.validation.Valid;
// ...
@PostMapping(value = "/email/credentials", consumes = MediaType.APPLICATION_JSON_VALUE)
    public Map<String, Object> emailCredentials(@RequestBody @Valid EmailCredential emailCredential) {
        return emailService.setCredentials(emailCredential);
    }

07-24 12:47