我目前正在评估Spring Data REST。 我从这个简单的例子开始:link
它开箱即用。但是现在,在下一步中,我想尝试一些验证来了解框架的反应。所以我只是注释了Person
class:
@Size(min = 2, message = "{test.error.message}")
private String firstName;
验证本身正在运行,我收到一条错误消息。如果我将一个名为ValidationMessages.properties
的文件放在类路径的根目录中,则会解析该消息(请参阅here why)。
现在,我没有将文件放在根目录中,而是将它们放在子文件夹(例如lang/ValidationMessages.properties
)中,而是使用Spring MessageSource
而不是默认方法。
经过一些研究,我发现了以下问题:MessageInterpolator in Spring
不幸的是,使用以下bean定义不起作用:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.2.xsd">
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>lang/ValidationMessages</value>
</list>
</property>
</bean>
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="validationMessageSource" ref="messageSource"/>
</bean>
</beans>
pom.xml中相应的依赖项(以防万一):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-rest</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
有谁知道我错过了什么?可能是因为我没有使用Spring MVC而是Spring Data REST?如果是的话,有没有办法让这个工作?
经过一些额外的调查(以及大量搜索)后,我找到了解决问题的方法。
问题
Hibernate不使用bean作为验证器工厂,这就是为什么不使用LocalValidatorFactoryBean
。
有关详细信息,请查看org.hibernate.cfg.beanvalidation.TypeSafeActivator#activate(ActivationContext activationContext)
第一种方法
您可以使用此属性实际指定要使用的工厂:javax.persistence.validation.factory
不幸的是,这不能在Spring Boot的application.properties
中使用。
(见本Issue on GitHub)
解
使用链接的GitHub问题中描述的解决方法可以正常工作。您必须为Hibernate提供配置:
@Configuration
public class HibernateConfig extends HibernateJpaAutoConfiguration {
@Autowired
private ValidatorFactory validator;
@Override
protected void customizeVendorProperties(Map<String, Object> vendorProperties) {
super.customizeVendorProperties(vendorProperties);
vendorProperties.put("javax.persistence.validation.factory", validator);
}
}
使用此方法可以正确解析消息。
HibernateJpaAutoConfiguration不能再工作了(春季启动后2.10)
如果您使用的是Spring Boot 2.1.0+,可以这样做:
@Configuration
@Lazy
class SpringValidatorConfiguration {
@Bean
@Lazy
public HibernatePropertiesCustomizer hibernatePropertiesCustomizer(final Validator validator) {
return new HibernatePropertiesCustomizer() {
@Override
public void customize(Map<String, Object> hibernateProperties) {
hibernateProperties.put("javax.persistence.validation.factory", validator);
}
};
}
}
来自Spring Boot 2.0.0 M6 - Add Hibernate Interceptor的想法
和Spring Boot - Hibernate custom constraint doesn't inject Service