目标

使用spring boot 自带组件完成表单验证消息的国际化

国际化顺序:

1.注解自定义消息国际化,例:

@ISBN(message = "{param.empty}")

2.默认消息国际化,例:

@ISBN

配置

1.系统环境:

spring boot 2.6.8

  • spring-boot-starter-validation
  •  hibernate-validator

2.配置

java:

import lombok.RequiredArgsConstructor;
import org.springframework.boot.validation.MessageInterpolatorFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@Configuration
@RequiredArgsConstructor
public class MessageConfig implements WebMvcConfigurer {

    private final ResourceBundleMessageSource resourceBundleMessageSource;

    @Bean
    public LocalValidatorFactoryBean localValidatorFactoryBean() {
        LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
        MessageInterpolatorFactory interpolatorFactory = new MessageInterpolatorFactory();
        factoryBean.setMessageInterpolator(interpolatorFactory.getObject());
        // 设置快速失败,Hibernate 验证框架默认验证所有字段设置的所有规则,并返回错误集合。
        // 快速失败则是只要验证时出现一个错误,立马返回,不执行后面的验证规则
        factoryBean.getValidationPropertyMap().put("hibernate.validator.fail_fast", "true");
        //为Validator配置国际化
        factoryBean.setValidationMessageSource(resourceBundleMessageSource);
        return factoryBean;
    }

}

yml:

spring: 
  messages:
    basename: messages
    encoding: UTF-8

message文件:

 hibernate-validator自带message文件:

 使用

通过请求 中的 Header,Accept-Language 来控制国际化的展示

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐