SpringBoot2.2.6沒有做message.properties文件中屬性的自動讀取配置。解決方法有兩種:
1. 升級springboot版本到2.6.x以上
2. 在現有springboot版本的基礎上添加以下自定義配置:
@Configuration public class RequestParamValidationConfig implements WebMvcConfigurer {private MessageSource messageSource;public RequestParamValidationConfig(MessageSource messageSource) {this.messageSource = messageSource;}@Bean@Overridepublic Validator getValidator() {LocalValidatorFactoryBean localValidatorFactoryBean = new LocalValidatorFactoryBean();localValidatorFactoryBean.setValidationMessageSource(this.messageSource);return localValidatorFactoryBean;}}
spring-boot-starter-validation校驗請求參數操作步驟:
1. 在pom.xml中引入以下配置:
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-validation</artifactId> </dependency>
2. 在resources下創建 msg文件夾,并創建message.properties文件
3. 在message.properties文件自定義屬性xxx.xxx=自定義提示信息
4. 在實體類的屬性,引用校驗注解,例如: @NotEmpty(message="{xxx.xxx}")
5. 在application.yml中做如下配置:
spring:messages:basename: msg/message
6. 在controller的請求參數前加 @Validated @RequestBody 實體類 引用名
注意第6步中是Post請求,body傳參校驗,其余請求方式請自行測試。