我无法让自定义错误消息与 Spring 3.2 一起使用。这是我的配置:
配置:
@Configuration
@EnableWebMvc
@EnableJpaRepositories(basePackages = {"com.."})
@EnableTransactionManagement
@ComponentScan(basePackages = {"com.."})
public class Config extends WebMvcConfigurerAdapter {
@Bean
public PersistenceExceptionTranslator jpaExceptionTranslator() {
return new HibernateExceptionTranslator();
}
@Bean
public FactoryBean<EntityManagerFactory> entityManagerFactory(
DataSource ds, JpaVendorAdapter jva) {
LocalContainerEntityManagerFactoryBean factoryBean =
new LocalContainerEntityManagerFactoryBean();
factoryBean.setPackagesToScan(new String[] { "com.." });
factoryBean.setDataSource(ds);
factoryBean.setJpaVendorAdapter(jva);
factoryBean.afterPropertiesSet();
return factoryBean;
}
@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(emf);
return transactionManager;
}
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JodaModule());
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
return objectMapper;
}
@Bean
public MessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
messageSource.setBasename("i18n/messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
MappingJackson2HttpMessageConverter converter =
new MappingJackson2HttpMessageConverter();
converter.setObjectMapper(objectMapper());
converters.add(converter);
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}
}
这是 messages_en_US.properties 文件:
Pattern.userdto.email=Invalid email.
Pattern=Invalid syntax.
用户 DTO 类:
public final class UserDTO {
@Size(min = MIN_EMAIL_LENGTH, max = MAX_EMAIL_LENGTH)
@Pattern(regexp = EMAIL_PATTERN)
private String email;
...
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
...
}
使用 javax.validation.Valid 注解触发验证。
我希望当给定的电子邮件与模式不匹配时,这会打印出“无效的电子邮件”,但我收到了“无效的语法”消息。