在SpringBoot中使用MessageSource
几个说明:
properties配置文件中,;spring.messages.basename必须要加classpath前缀。如spring.messages.basename=classpath:i18n/messages必须要手动配置;MessageSource,springboot不会自动配置之- 如果使用
MessageSource.getMessage()方法,第一个参数的引用形式为"code",而不是"{code}"或者"${code}"。如messageSource.getMessage("test.msg", null,Locale.getDefault());- 在配置
LocalValidatorFactoryBean之后,才可以在javax.validation.constraints包下的注解(@Size,@NotNull...)下的message属性中使用"{code}"的形式声明校验提示信息。如@NotNull(message = "{leftTime.not.null}");- springMVC的locale配置和JVM的locale配置不一样,在application.properties中配置的
spring.mvc.locale=zh_CN实际上配置的是WebMvcProperties,在获取消息时,locale信息应该使用webMvcProperties.getLocale()1获取而不是使用Locale.getDefault()获取。
MessageSource is a powerful feature available in Spring applications. This helps application developers handle various complex scenarios with writing much extra code, such as environment-specific configuration, internationalization or configurable values.
One more scenario could be modifying the default validation messages to more user-friendly/custom messages.
In this tutorial, we'll see how to configure and manage custom validation MessageSource in the application using Spring Boot.
...