SpringBoot2.2.6使用spring-boot-validation读取不到自定义配置文件中的属性

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
    @Override
    public 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>
  1. 在resources下创建 msg文件夹,并创建message.properties文件

  2. 在message.properties文件自定义属性xxx.xxx=自定义提示信息

  3. 在实体类的属性,引用校验注解,例如: @NotEmpty(message="{xxx.xxx}")

  4. 在application.yml中做如下配置:

复制代码
spring:
  messages:
    basename: msg/message
  1. 在controller的请求参数前加 @Validated @RequestBody 实体类 引用名

注意第6步中是Post请求,body传参校验,其余请求方式请自行测试。

相关推荐
wearegogog1232 分钟前
基于C#的FTP客户端实现方案
java·网络·c#
听风吟丶3 分钟前
Java NIO 深度解析:从核心组件到高并发实战
java·开发语言·jvm
野生技术架构师9 分钟前
Java面试题及答案总结(互联网大厂新版)
java·面试·状态模式
a努力。10 分钟前
小红书Java面试被问:ThreadLocal 内存泄漏问题及解决方案
java·jvm·后端·算法·面试·架构
此生只爱蛋11 分钟前
【Redis】String 字符串
java·数据库·redis
C++业余爱好者11 分钟前
Java开发中Entity、VO、DTO、Form对象详解
java·开发语言
zmzb010312 分钟前
C++课后习题训练记录Day50
开发语言·c++
froginwe1113 分钟前
`.toggleClass()` 方法详解
开发语言
lsx20240614 分钟前
SQLite 附加数据库详解
开发语言
catchadmin16 分钟前
PHP 开发者指南 如何在 Composer 中使用本地包
开发语言·php·composer