所需工作的魔法是
LocalValidatorFactoryBean#setValidationMessageSource(MessageSource messageSource).
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=MyNotNullMessage
Person.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