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

相关推荐
禾小西10 分钟前
深入理解 Java String:从底层原理到高性能优化实战
java·开发语言·性能优化
渔民小镇14 分钟前
不用前端也能测试 —— 模拟客户端请求模块详解
java·服务器·前端·分布式·游戏
Huangjin007_16 分钟前
【C++类和对象(四)】手撕 Date 类:赋值运算符重载 + 日期计算
开发语言·c++
飞Link17 分钟前
深入挖掘 LangChain Community 核心组件,从数据接入到企业级 RAG 实战
开发语言·python·langchain
@atweiwei18 分钟前
基于Go语言构建轻量级微服务框架的设计与实现
开发语言·微服务·golang
长不大的小Tom20 分钟前
快速学习 C/C++ 并进阶的路线
开发语言·c++
星如雨グッ!(๑•̀ㅂ•́)و✧21 分钟前
Spring WebFlux中DataBufferLimitException异常的解决方案
java·后端·spring
独断万古他化26 分钟前
Selenium 实战 —— 抽奖系统 UI 自动化测试框架搭建
java·selenium·测试工具·ui·自动化·测试
心勤则明29 分钟前
使用 Spring AI Alibaba MCP 结合 Nacos 实现企业级智能体应用
java·人工智能·spring