问题描述
问题:
我正在尝试使用尽可能多的Spring Boot自动配置来减少样板代码.我无法获得Spring Validation代码来自动映射到我的外部化messages.properties.仅当我添加自己的 LocalValidatorFactoryBean 并使用完全限定的javax约束消息时,它才起作用.
I am trying to use as much Spring Boot Auto-configuration as possible to reduce boiler plate code. I cannot get the Spring Validation codes to automatically map to my externalized messages.properties. It will only work if I add my own LocalValidatorFactoryBean and use the fully qualified javax constraint message.
目标
我想基于Spring验证代码在我的应用程序中全局覆盖 @ javax.validation.constraints.NotNull 的 defaultMessage .
I want to override the defaultMessage for @javax.validation.constraints.NotNull globally in my application based on Spring Validation codes.
我做的第一件事是注册这个bean ...我真的必须这样做吗?我看到Spring Boot有一个,但似乎与messages.properties没有关联.
The first thing I did was register this bean...do I really have to? I see Spring Boot has one but it doesn't seem to correlate to messages.properties.
@Bean
public LocalValidatorFactoryBean validator(MessageSource messageSource) {
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
bean.setValidationMessageSource(messageSource);
return bean;
}
下一个令我惊讶. Spring Validation具有这个漂亮的 DefaultMessageCodesResolver 为看起来像这样的失败提供了出色的代码策略:
The next one is surprising to me. Spring Validation has this nifty DefaultMessageCodesResolver that provides excellent code strategy for failures that look something like this:
"code": "NotNull",
"codes": [
"NotNull.user.firstName",
"NotNull.firstName",
"NotNull.java.lang.String",
"NotNull"
],
但是@NotNull约束甚至不考虑这些代码. 验证转换的春季文档暗示确实存在类似的东西,但是还没有任何有用的东西.
But these codes aren't even considered for the @NotNull constraint. The spring documentation for Validation Conversion hints that something like this does exist but falls short of anything useful yet.
问题
如何基于基于messages.properties的代码覆盖默认的Spring Validation错误消息?
How can I override the default message of Spring Validation errors based on those codes from messages.properties?
相关的build.gradle
- springBootVersion ='2.0.0.RELEASE'
- compile('org.springframework.boot:spring-boot-starter-web')
src/main/resources/messages.properties:
NotNull.user.firstName=This doesn't work
NotNull.firstName=Or this
NotNull.java.lang.String=This doesn't work either
NotNull=And this doesn't work
javax.validation.constraints.NotNull.message=THIS DOES WORK! But why have codes then?
Spring自动配置输出,证明已加载自动配置.
MessageSourceAutoConfiguration matched:
- ResourceBundle found bundle URL [file:/home/szgaljic/git/jg-github/journey-through-spring/basic-web-validations/build/resources/main/messages.properties] (MessageSourceAutoConfiguration.ResourceBundleCondition)
- @ConditionalOnMissingBean (types: org.springframework.context.MessageSource; SearchStrategy: current) did not find any beans (OnBeanCondition)
其他一些相关的启动日志:
2018-03-26 14:32:22.970 TRACE 1093 --- [ main] o.s.beans.CachedIntrospectionResults : Found bean property 'validationMessageSource' of type [org.springframework.context.MessageSource]
验证约束:
public class User {
@NotNull
private String username;
@NotNull
private String firstName;
}
仅用于测试的控制器
@RestController
public class UserController {
@PostMapping("/users")
public List<ObjectError> testValidation(@Valid @RequestBody User user){
return null; // null implies no failed validations.. just for testing
}
}
无法使用代码
我试图注释/取消注释messages.properties中的消息,但是它将仅使用 javax.validation.constraints.NotNull.message 的值.
I tried to comment/uncomment the messages in messages.properties but it will only take the value of javax.validation.constraints.NotNull.message.
推荐答案
由于配置
@Bean
public LocalValidatorFactoryBean validator(MessageSource messageSource) {
LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
bean.setValidationMessageSource(messageSource);
return bean;
}
因此,您正在使用Bean验证,然后使用javax.validation.constraints.NotNull.message键从message.properties文件中获取从org.hibernate.validator.ValidationMessages.properties文件覆盖的消息.如果您想要键值对:
So you're using Bean Validation then spring get the messages from message.properties file that override from org.hibernate.validator.ValidationMessages.properties file using the key javax.validation.constraints.NotNull.message. If you would like to have key-value pairs:
NotNull.user.firstName=This doesn't work
NotNull.firstName=Or this
NotNull.java.lang.String=This doesn't work either
NotNull=And this doesn't work
要工作,您必须编写如下内容:
to work you have to write as follows:
@Autowired
private MessageSource messageSource;
@PostMapping("/users")
public List<ObjectError> testValidation(@Valid @RequestBody User user, BindingResult bindingResult){
bindingResult.getFieldErrors().forEach(fieldError -> new ObjectError(
/*Assumes that ObjectError has constructor of ObjectError(String message) */
messageSource.getMessage(fieldError, Locale.getDefault())
));
return null;
}
这篇关于Spring Boot将验证码映射到MessageSource消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!