Bean Validation(JSR-303)校验机制下,读取不到properties配置文件自定义的错误提示信息

1、validator配置如下;

<mvc:annotation-driven conversion-service="conversionService" validator="validator"></mvc:annotation-driven>
    <!--校验器-->
    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
        <property name="validationMessageSource" ref="messageSource"></property>
    </bean>
    <!--校验错误信息配置文件-->
    <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="message"></property>
        <property name="cacheSeconds" value="120"></property>
        <property name="fileEncodings" value="UTF-8"></property>
    </bean>

2、添加注解;

    @Size(min=1,max=20,message = "{fruits.name.length.error}")
    private String name;
    @NotEmpty(message = "{fruits.producing_area.isEmpty}")
    private String producing_area;

3、自定义错误提示信息(properties配置文件下);

fruits.name.length.error=请输入1到20个字符的商品名称
fruits.producing_area.isEmpty=请输入商品产地

4、在controller方法中添加@Validated和BindingResult注解(两个需成对出现);

5、测试结果如下:(没有输出我们自定义的错误提示信息

 

问题的解决:

大家一般都是用ReloadableResourceBundleMessageSource这个实现类,上面也是用这个实现类的;

但是上面就出现了这个问题,不知道大家会不会一样有这个问题;

我的解决方法是将ReloadableResourceBundleMessageSource实现类改成ResourceBundleMessageSource实现类;但是会出现以下错误(ResourceBundleMessageSource实现类没有fileEncodings的属性);

此时将fileEncodings属性改成defaultEncoding即可获取到配置文件自定义的错误提示信息了;

出现以上问题和解决方法的原理其实我还不懂,并且这种方法还不一定对,所以有同学明白的话还请告知以下,谢谢。

猜你喜欢

转载自blog.csdn.net/qq_40181063/article/details/88083387
今日推荐