ValidationMessages.properties 未使用 BindException 解决

ValidationMessages.properties not resolving with BindException

我可能只是没有做对,但我是这样的。

我有一个 Spring 引导应用程序,我已将 Hibernate Validator 添加到其中,并且我有一个看起来像这样的命令对象:

public class SignupCommand {

  @Pattern(regexp = "^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$")
  private String someDate;

  // getters/setters omitted for brevity

}

控制器中的 @RequestMapping 如下所示:

@RequestMapping(method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public AuthToken signUp(@Valid @RequestBody SignupCommand signupCommand,
                        BindingResult bindingResult) throws BindException {
  if (bindingResult.hasErrors()) {
    throw new BindException(bindingResult);
  }
  return accountService.signUp(signupCommand);
}

这 returns 我期望的 JSON,带有错误代码,如下所示:

{
  "timestamp" : 1440256315621,
  "status" : 400,
  "error" : "Bad Request",
  "exception" : "org.springframework.validation.BindException",
  "errors" : [ {
    "codes" : [ "Pattern.signupCommand.someDate", "Pattern.someDate", "Pattern.java.lang.String", "Pattern" ],
    "arguments" : [ {
      "codes" : [ "signupCommand.someDate", "someDate" ],
      "arguments" : null,
      "defaultMessage" : "someDate",
      "code" : "someDate"
    }, [ ], "^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$" ],
    "defaultMessage" : "must match \"^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$\"",
    "objectName" : "signupCommand",
    "field" : "someDate",
    "rejectedValue" : "02-16-2015",
    "bindingFailure" : false,
    "code" : "Pattern"
  } ],
  "message" : "Validation failed for object='signupCommand'. Error count: 1",
  "path" : "/api/signup"
}

这是我的问题所在。我试过将以下内容放在类路径根目录下的 messages.propertiesValidationMessages.properties 中(在 src/main/resources 中),但没有成功:

Pattern.signupCommand.someDate=Please enter a valid date in the format MM-DD-YYYY.

我想我对 Spring 如何结合 Hibernate Validator 进行消息解析还不够了解。感谢您的帮助!

更新

我决定将 message="{mymessage}" 添加到 @Pattern 并在两个文件中添加 mymessage=Some message 以查看使用了哪个。当它像 ValidationMessages.properties 文件中那样明确定义时,它看起来能够解析消息。

如果您使用 javax.validation.constraints.Pattern.message=... 作为消息键,该值将用于所有模式验证错误消息。这不太可能是您想要的,因为并非所有模式都适用于日期!

采用 @Pattern(..., message="dateValidationMessage") 的方法并使用 dateValidationMesssage=... 作为您的消息密钥。

我能够使用 this blog post 解决我的问题。佩特里又来了!

我基本上只需要创建一个 @ExceptionHandler 并手动解析消息。我不确定为什么我认为抛出 BindException 会自动为我解决我的消息。