SpringCloud根据浏览器语言实现国际化(翻译动态log日志、接口返回参数信息)

一、什么是国际化?

国际化实际上就是指多语言展示页面内容,前端实现一般有提供好的插件例如vue-i18n,react—i18n,后端也提供了ResourceBundleMessageSource这个类来实现的,前端用于翻译页面,设置点击事件翻译整个页面即可。后端的服务器log日志以及接口返回的各种参数信息需要我们做成动态的,下面我们一起来看一下Spring Boot是如何实现国际化支持的。

二、国际化的基本原理

类路径:

org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration

该类的源代码:

@Configuration
@ConditionalOnMissingBean(value = MessageSource.class, search = SearchStrategy.CURRENT)
@AutoConfigureOrder(Ordered.HIGHEST_PRECEDENCE)
@Conditional(ResourceBundleCondition.class)
@EnableConfigurationProperties
public class MessageSourceAutoConfiguration {

    private static final Resource[] NO_RESOURCES = {};

    @Bean
    @ConfigurationProperties(prefix = "spring.messages")
    public MessageSourceProperties messageSourceProperties() {
        return new MessageSourceProperties();
    }

    @Bean
    public MessageSource messageSource() {
        MessageSourceProperties properties = messageSourceProperties();
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        if (StringUtils.hasText(properties.getBasename())) {
            messageSource.setBasenames(StringUtils.commaDelimitedListToStringArray(
                StringUtils.trimAllWhitespace(properties.getBasename())));
        }
        if (properties.getEncoding() != null) {
            messageSource.setDefaultEncoding(properties.getEncoding().name());
        }
        messageSource.setFallbackToSystemLocale(properties.isFallbackToSystemLocale());
        Duration cacheDuration = properties.getCacheDuration();
        if (cacheDuration != null) {
            messageSource.setCacheMillis(cacheDuration.toMillis());
        }
        messageSource.setAlwaysUseMessageFormat(properties.isAlwaysUseMessageFormat());
        messageSource.setUseCodeAsDefaultMessage(properties.isUseCodeAsDefaultMessage());
        return messageSource;
    }

MessageSourceProperties properties = messageSourceProperties();
在这个方法中声明了MessageSourceProperties这个对象:

public class MessageSourceProperties {

	/**
	 * Comma-separated list of basenames (essentially a fully-qualified classpath
	 * location), each following the ResourceBundle convention with relaxed support for
	 * slash based locations. If it doesn't contain a package qualifier (such as
	 * "org.mypackage"), it will be resolved from the classpath root.
	 */
	private String basename = "messages";

	/**
	 * Message bundles encoding.
	 */
	private Charset encoding = StandardCharsets.UTF_8;

类中首先声明了一个属性basename,默认值为messages。看其介绍,这是一个以逗号分隔的基本名称列表,如果它不包含包限定符(例如“org.mypackage”),它将从类的根路径解析。它的意思是如果你不在配置文件中指定以逗号分隔开的国际化资源文件名称的话,它默认会去类路径下找messages.properties作为国际化资源文件的基本文件。若是你的国际化资源文件是在类路径某个包(如:i18n)下的话,你就需要在配置文件中指定基本名称了。

三、国际化的配置

在application.yml 配置国际化文件所在位置

	spring:
    messages:
        encoding: UTF-8  
        cache-seconds: 1  
        basename: static/i18n/messages

四、创建国际化文件

在这里插入图片描述

messages.properties该文件是默认文件,例如当谷歌浏览器设置默认语言在配置的pproperties下找不到对应的,cn对应中文,us对应英文语言,那么就会找该文件配置的code值:

配置文件内容:动态配置采用{0},{1}两个占位符设置两个动态参数

messages.properties:

amapGateway.synchroAPI.200=API同步成功,详情:{0}个API,{1}个API分组

messages_zh_CN.properties:

amapGateway.synchroAPI.200=API同步成功,详情:{0}个API,{1}个API分组

messages_en_US.properties:

amapGateway.synchroAPI.200=API synchronization successful, details: {0} API,{1} API group

五、、工具类ResultVo

该工具类作用获取占位符{0},{1},对应的配置文件的value值

@Getter
public class ResultVo<T> {

    private  String  code;

    private String msg;

    private T data;

    private String  createTime ;

    private  ResultVo(String code){
        this.code = code;
        setCode(code);
    }

    public void setCode(String code) {
        String message = null;
        try {
            message = I18nUtil.getMessage(code);
        }catch (Exception e){
            message = code;
        }
        this.code = code;
        this.msg = message;
    }

    /**
     * 默认成功返回
     * @param <T>
     * @return
     */
    public static<T> ResultVo<T> OK(){
        return new ResultVo<T>("SUCCESS");
    }

    /**
     * 返回只带code的信息
     * @param code
     * @param <T>
     * @return
     */
    public static<T> ResultVo<T> faild(String code){
        return new ResultVo<T>(code);
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}

六、创建Testcontroller测试

@RestController
@Slf4j
public class TestController {

    @Autowired
    private MessageUtil messageUtil;

    @GetMapping(value = "/test")
    public ResultVo test(){
        String a = "2";
        ResultVo resultVo = ResultVo.faild("amapGateway.synchroAPI.200");
        resultVo.setMsg(resultVo.getMsg().replace("{0}", a));
        resultVo.setMsg(resultVo.getMsg().replace("{1}", "3"));
        System.out.println(resultVo.getMsg());
        return resultVo;
    }

七、测试

谷歌浏览器设置浏览器语言
在这里插入图片描述

中文效果:
在这里插入图片描述
英文效果:
在这里插入图片描述

八、代码地址

国际化代码地址点击跳转

九、 最后整理

以上内容是做SpringBoot国际化,当我们项目是SpringCloud的时候,每一个Moudle都需要创建一个I18n的文件夹简化成每一个SpringBoot项目去做,如果是common模块没有启动项那么它就不是一个Springbooot工程就需要修改SpringBBoot底层代码了。
例如这样:
在这里插入图片描述

配置文件的名称zh_CNen_US是和浏览器中相互对应的,可以写一个js文件用request.getLocal()这个方法获取,名称对应不上配置是不生效的!

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
【2021年,将Spring全家桶的课程进行Review,确保不再有课程的顺序错乱,从而导致学员看不懂。进入2022年,将Spring的课程进行整理,整理为案例精讲的系列课程,并开始加入高阶Spring Security等内容,一步步手把手教你从零开始学会应用Spring,课件将逐步进行上传,敬请期待!】 本课程是Spring全家桶系列课程的第三部分Spring BootSpring案例精讲课程以真实场景、项目实战为导向,循序渐进,深入浅出的讲解Java网络编程,助力您在技术工作中更进一步。 本课程聚焦Spring Boot核心知识点:整合Web(如:JSP、Thymeleaf、freemarker等的整合)的开发、全局异常处理、配置文件的配置访问、多环境的配置文件设置、日志Logback及slf4j的使用、国际化设置及使用, 并在最后以一个贯穿前后台的Spring Boot整合Mybatis的案例为终奖,使大家快速掌握Spring的核心知识,快速上手,为面试、工作都做好充足的准备。 由于本课程聚焦于案例,即直接上手操作,对于Spring的原理等不会做过多介绍,希望了解原理等内容的需要通过其他视频或者书籍去了解,建议按照该案例课程一步步做下来,之后再去进一步回顾原理,这样能够促进大家对原理有更好的理解。 【通过Spring全家桶,我们保证你能收获到以下几点】 1、掌握Spring全家桶主要部分的开发、实现2、可以使用Spring MVC、Spring BootSpring Cloud及Spring Data进行大部分的Spring开发3、初步了解使用微服务、了解使用Spring进行微服务的设计实现4、奠定扎实的Spring技术,具备了一定的独立开发的能力  【实力讲师】 毕业于清华大学软件学院软件工程专业,曾在Accenture、IBM等知名外企任管理及架构职位,近15年的JavaEE经验,近8年的Spring经验,一直致力于架构、设计、开发及管理工作,在电商、零售、制造业等有丰富的项目实施经验  【本课程适用人群】如果你是一定不要错过!  适合于有JavaEE基础的,如:JSP、JSTL、Java基础等的学习者没有基础的学习者跟着课程可以学习,但是需要补充相关基础知识后,才能很好的参与到相关的工作中。 【Spring全家桶课程共包含如下几门】 

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值