必要なジョブを実行する魔法のメソッドは、LocalValidatorFactoryBean#setValidationMessageSource(MessageSource messageSource)です。
まず第一に、メソッドの契約:-
クラスパス内のJSR-303のデフォルトの「ValidationMessages.properties」バンドルに依存する代わりに、検証メッセージを解決するためのカスタムSpringMessageSourceを指定します。これは、Springコンテキストの共有「messageSource」Bean、または検証目的でのみ使用される特別なMessageSourceセットアップを参照する場合があります。
注:この機能には、クラスパスにHibernateValidator4.1以降が必要です。それでも、別の検証プロバイダーを使用することはできますが、構成中にHibernateValidatorのResourceBundleMessageInterpolatorクラスにアクセスできる必要があります。
このプロパティまたは「messageInterpolator」のいずれかを指定します。両方を指定することはできません。カスタムMessageInterpolatorを構築する場合は、Hibernate ValidatorのResourceBundleMessageInterpolatorから派生し、補間器を構築するときにSpringMessageSourceResourceBundleLocatorを渡すことを検討してください。
このメソッドを呼び出すことにより、カスタムmessage.properties(または.xml)を指定できます...このように...
my-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>
validate_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: Custom Message:- MyNotNullMessage