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传参校验,其余请求方式请自行测试。

相关推荐
m0_748238636 分钟前
Spring Boot项目接收前端参数的11种方式
前端·spring boot·后端
Forget the Dream27 分钟前
设计模式之责任链模式
java·c++·设计模式·责任链模式
jonyleek30 分钟前
「JVS更新日志」低代码、企业会议、智能BI、智能排产2.26更新说明
java·大数据·低代码·数据分析·软件需求
Joey_friends31 分钟前
【Linux】线程详解
开发语言
_GR36 分钟前
Qt开发⑧Qt的窗口_下_浮动窗口+对话框
开发语言·css·c++·qt·microsoft
Good Note44 分钟前
Golang——常用库context和runtime
开发语言·爬虫·golang
计算机小白一个1 小时前
蓝桥杯 Java B 组之最短路径算法(Dijkstra、Floyd-Warshall)
java·数据结构·算法·蓝桥杯
曼岛_1 小时前
[密码学实战]Java实现SM4加解密(ecb,cbc)及工具验证
java·密码学
菜鸟阿达1 小时前
spring boot 2.7 + seata +微服务 降级失败问题修复
spring boot·后端·微服务
清河__1 小时前
【Go】十七、grpc 服务的具体功能编写
开发语言·后端·golang