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

相关推荐
蜗牛互联网1 分钟前
长任务多Agent共享文件系统的Manifest交接模式
java·人工智能·后端
Sirens.23 分钟前
Java并发锁详解:六类锁策略与 synchronized 底层原理
java·前端·算法
sunshine22 girl1 小时前
Java学习五 面向对象高级5 内部类1
java·学习
weixin_440730501 小时前
函数return、参数、参数组、递归函数、高阶函数等小结
开发语言·python
苏supper2 小时前
Spring Boot多环境配置与打包运行
spring boot·后端·spring
sugarzhangnotes2 小时前
【无标题】
开发语言·人工智能·python
geovindu2 小时前
rust: Composite Pattern
开发语言·后端·设计模式·rust·组合模式
天衍四九-2 小时前
【无标题】
前端·spring boot·mysql·nginx·docker
用户1305180712153 小时前
JDBC学习DAY2:从Statement到PreparedStatement
java
蛋蛋的就会顺顺的3 小时前
hot100——矩阵
java·数据结构·算法·leetcode·力扣