默认语言环境(例如ValidationMessage.properties)可以是您想要的任何语言,这完全是特定于应用程序的。因为我会说英语,所以我倾向于使该文件包含基于英语的翻译,并根据需要扩展到其他语言。
至于选择适当的语言环境选项,您需要提供一种将值从应用程序层下游传递到验证框架的方法。
例如,您的应用程序可以设置一个线程局部变量或使用 LocalContextHolder(如果您使用的是 spring),这将允许您设置一个线程特定的 Locale,您可以在代码中以静态方式访问该线程。
根据我过去的经验,我们通常有一个资源包,我们希望在 bean 验证中使用它与控制器和服务共享。我们为 bean 验证提供了一个解析器实现,它根据线程局部变量加载资源包并以这种方式公开国际化消息。
提供的示例:
// This class uses spring's LocaleContextHolder class to access the requested
// application Locale instead a ThreadLocal variable. See spring's javadocs
// for details on how to use LocaleContextHolder.
public class ContextualMessageInterpolator
extends ResourceBundleMessageInterpolator {
private static final String BUNDLE_NAME = "applicationMessages";
@Override
public ContextualMessageInterpolator() {
super( new PlatformResourceBundleLocator( BUNDLE_NAME ) );
}
@Override
public String interpolate(String template, Context context) {
return super.interpolate( template, context, LocaleContextHolder.getLocale() );
}
@Override
public String interpolate(String template, Context context, Locale locale) {
return super.interpolate( template, context, LocaleContextHolder.getLocale() );
}
}
下一步是您需要向 Hibernate Validator 提供 ContextualMessageInterpolator 实例。这可以通过创建validation.xml 并将META-INF 放在类路径的根目录下来完成。在 Web 应用程序中,这将是 WEB-INF/classes/META-INF。
<validation-config
xmlns="http://jboss.org/xml/ns/javax/validation/configuration"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://jboss.org/xml/ns/javax/validation/configuration"
version="1.1">
<message-interpolator>com.company.ContextualMessageInterpolator</message-interpolator>
</validation-config>
由于我使用 applicationMessages 作为我的包名称,因此只需创建一个默认的 applicationMessages.properties 文件和后续特定于语言环境的版本,并将您的验证消息字符串添加到这些属性文件中。
javax.validation.constraints.NotNull.message=Field must not be empty.
javax.validation.constraints.Max.message=Field must be less-than or equal-to {value}.
javax.validation.constraints.Min.message=Field must be greater-than or equal-to {value}.
希望对您有所帮助。