news 2026/5/14 5:51:53

SpringBoot国际化实现

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
SpringBoot国际化实现

Spring国际化实现

本次我们要实现的是统一错误信息,进行国际化。

1. 首先我们要添加SpringBoot配置,有两种方式能开启国际化功能:

1.1 yaml配置:

spring:messages:basename:i18n/messagesencoding:UTF-8
  • 与之对应的文件地址和名称要匹配
  • 具体如下:

    i18n:包名
    messages:文件前缀。
    en_US / zh_CN:对应的国际化语言,可以通过LocaleContextHolder.getLocale()这个方法来获取当前请求的Locale。如果要自定义的话:
    • en_US:Locale.US
    • zh_CN:Locale.SIMPLIFIED_CHINESE

你可以修改你的文件前缀名,但是对应文件的名称也需要改。

❓如果配置yaml不好使,或者输出的内容都是????????这种,我们要看一下对应的*.properties的文件编码是否是UTF-8

如果不是UTF-8,在IDEA中的 settings -> editor -> file ecoding ->Default encoding for properties files 这个配置改成UTF-8。 如果失败删除原文件,重新创建一个properties文件

1.2. 通过 Java 实现。

@ConfigurationpublicclassI18nConfig{/** * 创建并返回 MessageSource 实例,用于解析国际化消息。 * * @return 已配置的 {@link MessageSource},支持可重加载、指定编码与缓存时间。 */@BeanpublicMessageSourcemessageSource(){ReloadableResourceBundleMessageSourcems=newReloadableResourceBundleMessageSource();// 指定消息文件的基础路径(不带语言后缀与扩展名)ms.setBasename("classpath:i18n/messages");// 使用 UTF-8 编码,避免中文乱码ms.setDefaultEncoding("UTF-8");// 缓存时间(秒),为 3600s 表示每小时刷新一次;开发时可设置为 0ms.setCacheSeconds(3600);returnms;}}

1.创建国际化文件

上述我的配置i18n/messages,那么我就需要在项目中resource文件夹中创建一个名为i18n的包,在这个包下创建前缀为messages的国际化文件。

我创建了两个国际化文件,一个中文,一个英文:

  • i18n/messages_zh_CN.properties
  • i18n/messages_en_US.properties

2.国际化文件内容

国际化文件的内容非常简单,格式为key = value, 我们先配置好两个国际化文件。

  • key: 可以理解为Map中的key 用来定位具体内容。
  • value:具体内容。

messages_en_US.properties:

user.not.found=User not found user.disabled=User is disabled

messages_zh_CN.properties:

user.not.found=用户不存在 user.disabled=用户已被禁用

3.获取国际化内容工具类

我们可以直接注入这个工具类调用I18nUtil.get("user.not.found"),来获取国际化内容。
也可以主动设置Locale,来自定义获取国际化内容:

  • I18nUtil.get("user.not.found",Locale.SIMPLIFIED_CHINESE)调用这个方法,就在messages_zh_CN.properties配置中寻找user.not.found这个Key的Value值。返回结果为:用户不存在

  • I18nUtil.get("user.not.found",Locale.US)调用这个方法,就在messages_en_US.properties配置中寻找user.not.found这个Key的Value值。返回结果为:User not found

@ComponentpublicclassI18nUtil{@ResourceprivateMessageSourcemessageSource;/** * Resolve a message by its code using the current locale. * * @param code the message code (key) in the properties files * @param args optional arguments for parameterized messages * @return the localized message for the current locale */publicStringget(Stringcode,Object...args){returnmessageSource.getMessage(code,args,LocaleContextHolder.getLocale());}/** * Resolve a message by its code for a specific locale. * * @param code the message code (key) * @param locale the locale to use for lookup * @param args optional message parameters * @return the localized message for the given locale */publicStringget(Stringcode,Localelocale,Object...args){returnmessageSource.getMessage(code,args,locale);}/** * Resolve a message using an {@link ErrorCode} and the current locale. * * @param errorCode the error code which provides the message key * @param args optional message parameters * @return the localized message corresponding to the error code */publicStringget(ErrorCodeerrorCode,Object...args){returnmessageSource.getMessage(errorCode.getMsgKey(),args,LocaleContextHolder.getLocale());}}

如果你想要使用I18nUtil工具类,对应的类不能注入依赖,怎么办?

  • 通过静态的方式设置I18nUtil,让普通的类也能够调用I18nUtil内部的方法。
    • 可以直接在普通类中调用I18nHolder.getMessage("user.not.found")
    • 💡可以使用如下类:
importcom.entity.taient.exception.ErrorCode;importorg.springframework.stereotype.Component;importjavax.annotation.Resource;/** * I18nHolder 是一个静态访问点,用于在无法注入 Bean(例如静态方法或工具类中)时获取国际化消息。 * <p> * Spring 在启动时会通过 {@link #setI18nUtil(I18nUtil)} 注入实际的 {@code I18nUtil} 实例。 */@ComponentpublicclassI18nHolder{/** * 持有被注入的 I18nUtil 实例(用于检索国际化消息)。 */privatestaticI18nUtili18nUtil;/** * 由 Spring 注入 I18nUtil 实例。该方法会在容器初始化时被调用。 * * @param util 注入的 I18nUtil */@ResourcepublicvoidsetI18nUtil(I18nUtilutil){I18nHolder.i18nUtil=util;}/** * 根据错误码获取对应的国际化消息。 * 该方法为静态方法,方便在非 Spring 管理的静态上下文中直接调用。 * * @param errorCode 国际化 key * @param args 可选的参数,用于消息格式化 * @return 本地化后的消息字符串 * @throws NullPointerException 当 I18nUtil 未被注入时会抛出(通常表示 Spring 未正确初始化) */publicstaticStringgetMessage(StringerrorCode,Object...args){returni18nUtil.get(errorCode,args);}}
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/9 23:42:20

【SRE专家亲授】:Docker MCP 网关监控面板的7大核心组件详解

第一章&#xff1a;Docker MCP 网关监控面板概述Docker MCP&#xff08;Microservice Control Panel&#xff09;网关监控面板是一款专为微服务架构设计的可视化管理工具&#xff0c;集成于 Docker 容器化环境中&#xff0c;用于实时监控 API 网关的请求流量、服务健康状态、响…

作者头像 李华
网站建设 2026/5/10 14:04:48

揭秘VSCode远程调试卡顿问题:3步实现毫秒级响应的优化方案

第一章&#xff1a;VSCode远程调试卡顿问题的现状与影响在现代软件开发中&#xff0c;VSCode凭借其轻量级和强大的插件生态&#xff0c;成为开发者广泛使用的代码编辑器之一。然而&#xff0c;当通过Remote-SSH、Remote-WSL或Remote-Containers等扩展进行远程开发时&#xff0c…

作者头像 李华
网站建设 2026/5/7 5:15:57

PaddleClas PULC超轻量图像分类完整教程:从入门到快速部署

PaddleClas PULC超轻量图像分类完整教程&#xff1a;从入门到快速部署 【免费下载链接】PaddleClas A treasure chest for visual classification and recognition powered by PaddlePaddle 项目地址: https://gitcode.com/gh_mirrors/pa/PaddleClas 还在为图像分类模型…

作者头像 李华
网站建设 2026/5/11 22:28:17

React Router v7数据模式使用指南

React Router官方文档&#xff1a;https://reactrouter.com.cn/ react-router中路由模式分为&#xff1a;框架模式、 数据模式、声明式模式 以下仅为 * 数据模式 * 的使用笔记 安装 当前版本v7 npm install react-router使用createBrowserRouter创建路由配置&#xff0c;支…

作者头像 李华
网站建设 2026/5/12 5:10:37

手把手教你部署VSCode中的量子模拟内核:7个专业级配置步骤

第一章&#xff1a;VSCode Jupyter 量子模拟内核概述 VSCode 与 Jupyter Notebook 的深度集成&#xff0c;为量子计算开发者提供了高效、直观的编程环境。通过 Python 内核运行量子模拟代码&#xff0c;用户可以在交互式单元格中设计量子电路、执行测量并可视化结果。该环境广泛…

作者头像 李华