
有没有办法可以访问ValidationMessages.properties文件中的字段名称,例如下面我尝试使用{0}但它不起作用,我已经在某处看到了它.我希望Spring动态地将字段名称放在那里,所以我不必为每个类重复它.
public class RegistrationForm {
@NotEmpty(message = "{NotEmpty}")
private String email;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
ValidationMessages.properties
NotEmpty={0} TEST
使用您的示例,Spring将(在第一次传递中)尝试使用messages.properties中的以下消息键(或代码)本地化字段名称:
[RegistrationForm.email,email]
如果找不到任何内容,则回到字段名称.
Spring然后使用以下键查找本地化的错误消息:
[NotEmpty.RegistrationForm.email,NotEmpty.email,NotEmpty.java.lang.String,NotEmpty]
请注意,NotEmpty的优先级高于java.lang.String,NotEmpty,因此如果要根据字段类型自定义消息,请不要被愚弄.
因此,如果您将以下内容放在messages.properties中,您将获得所需的行为:
# for the localized field name (or just email as the key)
RegistrationForm.email=Registration Email Address
# for the localized error message (or use another specific message key)
NotEmpty={0} must not be empty!
从SpringValidatorAdapter的javadoc#getArgumentsForConstraint():
Return FieldError arguments for a validation error on the given field.
Invoked for each violated constraint.The default implementation returns a first argument indicating the field name
(of type DefaultMessageSourceResolvable, with “objectName.field” and “field” as codes).
Afterwards, it adds all actual constraint annotation attributes (i.e. excluding
“message”, “groups” and “payload”) in alphabetical order of their attribute names.Can be overridden to e.g. add further attributes from the constraint descriptor.
使用ValidationMessages.properties时,您可以使用{max}来引用@Size注释的max属性,使用Spring消息包{1}(因为按字母顺序排序时,max是@Size的第一个属性).
有关更多信息,您还可以查看我对ease field name localization的功能请求.
附录:如何查找此信息?
不幸的是踩到代码(现在这个帖子!).
要找出用于本地化错误字段的键,请检查BindingResult的值.在您的示例中,您将收到此错误:
Field error in object 'RegistrationForm' on field 'email': rejected value []; codes [NotEmpty.RegistrationForm.email,NotEmpty.email,NotEmpty.java.lang.String,NotEmpty]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [RegistrationForm.email,email]; arguments []; default message [email]]; default message [may not be empty]
SpringValidatorAdapter #getArgumentsForConstraint()负责为验证注释属性值和错误消息可用的字段名称.
转载注明原文:Spring Validation自定义消息 – 字段名称 - 乐贴网