完成所需工作的魔术方法是LocalValidatorFactoryBean#setValidationMessageSource(MessageSource
messageSource)。
首先,合同的方法:
指定一个自定义的Spring MessageSource来解析验证消息,而不是依赖于类路径中JSR-303的默认“
ValidationMessages.properties”捆绑包。这可以引用Spring上下文的共享“ messageSource”
bean,或者仅出于验证目的参考某些特殊的MessageSource设置。注意:此功能需要在类路径上使用Hibernate Validator
4.1或更高版本。不过,您可以使用其他验证提供程序,但在配置期间必须可以访问Hibernate
Validator的ResourceBundleMessageInterpolator类。指定此属性或“
messageInterpolator”,不能两者都指定。如果您想构建一个自定义的MessageInterpolator,在构造内插器时,请考虑从Hibernate
Validator的ResourceBundleMessageInterpolator派生并传入Spring
MessageSourceResourceBundleLocator。
您可以通过调用此方法来指定自定义message.properties(或.xml)…像这样…
my-beans.xml
<bean name="validator" > <property name="validationMessageSource"> <ref bean="resourceBundleLocator"/> </property></bean><bean name="resourceBundleLocator" > <property name="basenames"> <list> <value>meta-INF/validation_errors</value> </list> </property></bean>
validation_errors.properties
javax.validation.constraints.NotNull.message=MyNotNullMessage
人.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()); } }}
输出:
Custom Message:- MyNotNullMessage
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)