Hibernate Validator:违反消息语言 [英] Hibernate Validator: Violation Message Language
问题描述
我有一个测试类,用于测试一个域模型,该域模型带有例如@NotNull
I have a test class where I am testing a domain model which is annotated with e.g. @NotNull
在我的测试班中,我首先获得验证器
In my test class I am first getting the validator
private static Validator validator;
@BeforeClass
public static void setup() {
validator = Validation.buildDefaultValidatorFactory().getValidator();
}
稍后我有一个JUnit测试,用于测试领域模型(比如说一个人)
Later I have a JUnit Test where I am testing the domain model (lets say a Person)
Set<ConstraintViolation<Person>> violations = validator.validate( aPerson );
让我们说,我想检索我做的第一条违规消息:
Lets say, I want to retrieve the first violation Message I do:
String violationMessage = violations.iterator().next().getMessage()
我没有在@NotNull批注上设置任何自定义违规消息.因此,休眠验证器将从hibernate-validator-jar中的资源包中拉出默认消息.我的路径如下所示:
I haven't set any custom violation message on the @NotNull annotation. So hibernate validator will pull the default message from the Resource Bundle which is in the hibernate-validator-jar. My path looks like this:
hibernate-validator-5.3.5.Final.jar
- org
- hibernate
- validator
...
ResourceBundle 'Validation Messages'
在此资源包中,支持多种语言(英语,德语,法语,...)
In this Resource Bundle there are quite a few languages supported (English, German, French, ...)
示例
@NotNull违反德语消息
@NotNull violation message in German
javax.validation.constraints.NotNull.message = darf nicht null sein
@NotNull英文违规消息
@NotNull violation message in English
javax.validation.constraints.NotNull.message = may not be null
问题:
在测试时,如何强制Hibernate Validator从资源包中为违规消息选择特定的语言?现在,我收到英语违规消息.但是,在另一台机器上是德语.
When I am testing, how can I enforce Hibernate Validator to choose a specific language for the violation message from the Resource Bundle? Right now, I am getting English violation messages. However, on another machine German.
推荐答案
参考文档摘要:
默认情况下,在查找包中的消息时将使用JVM的默认语言环境(Locale#getDefault()).
By default, the JVM's default locale (Locale#getDefault()) will be used when looking up messages in the bundle.
在不触动源代码的情况下,或者在不干扰操作系统/用户的情况下,尝试执行以下操作以解决西班牙语消息:
Without touching source code or fiddle with your OS/User seetings, try this for spanish messages:
java -Duser.country=ES -Duser.language=es