我和春天(4.0.5)和Hibernate驗證工作(5.1.2.Final)編碼Hibernate驗證自定義錯誤消息配置通過Spring框架
我已經通過屬性文件工作中的錯誤消息,它也適用於i18n。
- 它在獨立和測試(JUnit的)環境中,由時刻。我不想包含Web環境,但仍然保持簡單。
我有以下幾點:
對於ValidationMessages_es_PE.properties文件(西班牙文)
person.salary.digits=Dato invalido '${validatedValue}', máximo tamaño no decimal permitido es {integer}, máximo tamaño decimal permitido es {fraction}
關於基礎設施
@Configuration
public class ValidatorConfiguration {
@Bean
public ResourceBundleMessageSource resourceBundleMessageSource(){
ResourceBundleMessageSource resourceBundleMessageSource = new ResourceBundleMessageSource();
resourceBundleMessageSource.setDefaultEncoding("UTF-8");
resourceBundleMessageSource.setBasenames("com.manuel.jordan.validation.messages.ValidationMessages");
return resourceBundleMessageSource;
}
@Bean
public LocalValidatorFactoryBean localValidatorFactoryBean(){
LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();
localValidatorFactoryBean.setValidationMessageSource(resourceBundleMessageSource());
MessageSourceResourceBundleLocator messageSourceResourceBundleLocator = new MessageSourceResourceBundleLocator(resourceBundleMessageSource());
ResourceBundleMessageInterpolator resourceBundleMessageInterpolator = new ResourceBundleMessageInterpolator(messageSourceResourceBundleLocator);
localValidatorFactoryBean.setMessageInterpolator(resourceBundleMessageInterpolator);
return localValidatorFactoryBean;
}
}
觀察我setDefaultEncoding("UTF-8")
測試類
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=ValidatorConfiguration.class)
public class InvalidPersonValidation03Test {
private static final Logger logger = LoggerFactory.getLogger(InvalidPersonValidation03Test.class);
@Autowired
private LocalValidatorFactoryBean validator;
public InvalidPersonValidation03Test(){
LocaleContextHolder.setLocale(new Locale("es","PE"));
}
@Test
public void testInvalidNullId(){
...
部分輸出的是以下
- >>>testInvalidFractionSalary
- ConstraintViolationImpl{interpolatedMessage='Dato invalido '1578.100', m�ximo tama�o no decimal permitido es 4, m�ximo tama�o decimal permitido es 2', propertyPath=salary, rootBeanClass=class com.manuel.jordan.domain.PersonValidation03, messageTemplate='{person.salary.digits}'}
- ConstraintViolationImpl{interpolatedMessage='Dato invalido '1578.100', m�ximo tama�o no decimal permitido es 4, m�ximo tama�o decimal permitido es 2', propertyPath=salary, rootBeanClass=class com.manuel.jordan.domain.PersonValidation03, messageTemplate='{person.salary.digits}'}
字符ñ
和á
沒有顯示它是如何預計
我的IDE已經
Preferences -> Workspace -> Text file encoding
與UTF-8
我需要多少額外的缺失配置?
嘗試設置'-Dfile.encoding = utf-8'到服務器。 – 2014-08-27 15:29:20
謝謝,我應該在哪裏應用?我嘗試了'VM參數'或'程序參數'中的'JUnit-> Run Configurations - > Arguments'以及相同的錯誤結果。 – 2014-08-27 15:34:41