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>

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值