当使用Spring应用程序进行hibernate自动配置(只有适当的hibernate验证* .jar文件应该存在并且会被自动使用).在这种情况下,如何替代ResourceBundleLocator?在任何属性或applicationContext.xml文件中,我没有看到任何自定义ResourceBundleLocator的方法.
解决方法
首先,合同方式: –
Specify a custom Spring MessageSource for resolving validation
messages,instead of relying on
JSR-303’s default
“ValidationMessages.properties” bundle
in the classpath. This may refer to a
Spring context’s shared
“messageSource” bean,or to some
special MessageSource setup for
validation purposes only.
注意:此功能需要休眠
验证器4.1或更高版本
类路径.你可以使用a
不同的验证提供商,但
Hibernate验证器
ResourceBundleMessageInterpolator
课程必须在之前访问
组态.
指定此属性或
“messageInterpolator”,而不是两者.如果
你想建立一个习惯
MessageInterpolator,考虑派生
来自Hibernate Validator的
ResourceBundleMessageInterpolator和
穿过春天
MessageSourceResourceBundleLocator
构建插值器时.您可以通过调用此方法来指定自定义的message.properties(或.xml)…像这样…
我-beans.xml文件
<bean name="validator" class="org.springframework.validation.beanvalidation.LocalValidatorfactorybean"> <property name="validationMessageSource"> <ref bean="resourceBundleLocator"/> </property> </bean> <bean name="resourceBundleLocator" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basenames"> <list> <value>Meta-INF/validation_errors</value> </list> </property> </bean>validation_errors.properties
javax.validation.constraints.NotNull.message=MyNotNullMessagePerson.java
class Person { private String firstName; private String lastName; @NotNull public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } }BeanValidationTest.java
public class BeanValidationTest { private static ApplicationContext applicationContext; @BeforeClass public static void initialize() { applicationContext = new ClassPathXmlApplicationContext("classpath:Meta-INF/spring/webmvc-beans.xml"); Assert.assertNotNull(applicationContext); } @Test public void test() { LocalValidatorfactorybean factory = applicationContext.getBean("validator",LocalValidatorfactorybean.class); Validator validator = factory.getValidator(); Person person = new Person(); person.setLastName("dude"); Set<ConstraintViolation<Person>> violations = validator.validate(person); for(ConstraintViolation<Person> violation : violations) { System.out.println("Custom Message:- " + violation.getMessage()); } } }Outupt:自定义消息: – MyNotNullMessage