当前位置: 代码网 > it编程>编程语言>Java > Spring实现国际化与本地化的详细步骤

Spring实现国际化与本地化的详细步骤

2025年06月18日 Java 我要评论
一、核心概念:国际化(i18n)与本地化(l10n)国际化(internationalization):简称 i18n,指设计应用时使其能够适应不同语言和区域的过程。开发者需将应用中的固定文本(如提示

一、核心概念:国际化(i18n)与本地化(l10n)

  • 国际化(internationalization):简称 i18n,指设计应用时使其能够适应不同语言和区域的过程。开发者需将应用中的固定文本(如提示信息、按钮标签)提取为可替换的资源,避免硬编码。
  • 本地化(localization):简称 l10n,是根据用户的语言、地区等偏好,将国际化后的应用内容显示为对应语言和格式(如日期、货币)的过程。例如,将英文界面切换为中文,或者根据地区显示不同格式的日期(美式 “mm/dd/yyyy” vs 中式 “yyyy-mm-dd”)。

二、spring 国际化实现步骤

1. 创建资源文件

src/main/resources目录下创建以messages为基础名,后跟语言代码和区域代码的属性文件。常见的语言代码如zh(中文)、en(英文),区域代码如cn(中国)、us(美国)。

  • messages.properties:默认资源文件,用于未匹配到特定语言时的兜底显示。
  • messages_zh_cn.properties:简体中文资源文件。
  • messages_en_us.properties:美式英语资源文件。

示例内容:

messages.properties

greeting=hello!

messages_zh_cn.properties

greeting=你好!

messages_en_us.properties

greeting=hello!

2. 配置 messagesource

在 spring 配置类(如@configuration类)或application.properties中配置messagesource,用于加载和管理资源文件。

java 配置方式

import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.context.support.resourcebundlemessagesource;
 
@configuration
public class appconfig {
    @bean
    public resourcebundlemessagesource messagesource() {
        resourcebundlemessagesource messagesource = new resourcebundlemessagesource();
        messagesource.setbasename("messages"); // 指定资源文件基础名
        messagesource.setdefaultencoding("utf-8"); // 设置编码
        return messagesource;
    }
}

application.properties 配置方式

spring.messages.basename=messages
spring.messages.encoding=utf-8

3. 在代码中使用 messagesource

通过注入messagesource,调用getmessage方法获取对应语言的文本。

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.context.messagesource;
import org.springframework.context.i18n.localecontextholder;
import org.springframework.stereotype.component;
 
@component
public class messageservice {
    private final messagesource messagesource;
 
    @autowired
    public messageservice(messagesource messagesource) {
        this.messagesource = messagesource;
    }
 
    public string getgreeting() {
        return messagesource.getmessage("greeting", null, localecontextholder.getlocale());
    }
}

上述代码中,localecontextholder.getlocale()获取当前用户的区域设置,messagesource.getmessage根据区域设置查找对应的资源文件,返回相应的文本。

三、本地化实现:处理日期、数字和货币

spring 通过dateformatnumberformat等类实现不同区域的格式转换,结合@bean配置和@autowired注入使用。

1. 配置日期格式化

import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.format.formatterregistry;
import org.springframework.web.servlet.config.annotation.webmvcconfigurer;
 
import java.text.simpledateformat;
import java.util.date;
import java.util.locale;
 
@configuration
public class webconfig implements webmvcconfigurer {
    @override
    public void addformatters(formatterregistry registry) {
        registry.addformatterforfieldtype(date.class, new simpledateformat("yyyy-mm-dd", locale.getdefault()));
    }
}

上述配置将date类型数据格式化为 “yyyy-mm-dd”,并根据用户的区域设置动态调整。

2. 货币格式化

import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import java.text.numberformat;
import java.util.currency;
import java.util.locale;
 
@configuration
public class appconfig {
    @bean
    public numberformat currencyformat() {
        locale locale = locale.getdefault();
        currency currency = currency.getinstance(locale);
        return numberformat.getcurrencyinstance(locale).setcurrency(currency);
    }
}

通过上述配置,在显示货币金额时,会根据用户区域自动使用对应货币符号和格式(如¥、$)。

四、在 web 应用中实现语言切换

1. 通过请求参数切换语言

在 controller 中接收lang参数,设置locale

import org.springframework.web.bind.annotation.getmapping;
import org.springframework.web.bind.annotation.requestparam;
import org.springframework.web.bind.annotation.restcontroller;
import org.springframework.web.servlet.localeresolver;
import org.springframework.web.servlet.support.requestcontextutils;
 
import javax.servlet.http.httpservletrequest;
import java.util.locale;
 
@restcontroller
public class languagecontroller {
    @getmapping("/setlang")
    public string setlanguage(@requestparam string lang, httpservletrequest request) {
        localeresolver localeresolver = requestcontextutils.getlocaleresolver(request);
        if (localeresolver != null) {
            localeresolver.setlocale(request, new locale(lang));
        }
        return "language set to: " + lang;
    }
}

用户访问/setlang?lang=zh即可将语言切换为中文,访问/setlang?lang=en切换为英文。

2. 通过 cookie 或 session 切换语言

实现自定义的localeresolver,将用户选择的语言存储在 cookie 或 session 中,下次访问时自动应用。

import org.springframework.web.servlet.localeresolver;
import org.springframework.web.servlet.i18n.cookielocaleresolver;
 
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
import java.util.locale;
 
public class customlocaleresolver extends cookielocaleresolver {
    private static final string lang_cookie_name = "myapp_lang";
 
    @override
    public locale resolvelocale(httpservletrequest request) {
        locale locale = super.resolvelocale(request);
        if (locale == null) {
            // 从cookie获取语言,若不存在则使用默认语言
            string lang = request.getcookies() != null ? findcookievalue(request.getcookies(), lang_cookie_name) : null;
            if (lang != null) {
                locale = new locale(lang);
            }
        }
        return locale;
    }
 
    @override
    public void setlocale(httpservletrequest request, httpservletresponse response, locale locale) {
        // 将语言存储到cookie
        super.setlocale(request, response, locale);
        setcookie(response, lang_cookie_name, locale.getlanguage());
    }
 
    private string findcookievalue(javax.servlet.http.cookie[] cookies, string cookiename) {
        for (javax.servlet.http.cookie cookie : cookies) {
            if (cookie.getname().equals(cookiename)) {
                return cookie.getvalue();
            }
        }
        return null;
    }
}

在 spring 配置类中注册自定义localeresolver

import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.web.servlet.localeresolver;
 
@configuration
public class appconfig {
    @bean
    public localeresolver localeresolver() {
        return new customlocaleresolver();
    }
}

五、总结

spring 的国际化与本地化功能通过资源文件管理、messagesource配置和locale设置,为开发者提供了一套完整的解决方案。通过合理配置和代码实现,能够轻松满足不同地区用户的语言和格式需求,提升应用的用户体验和全球化竞争力。在实际开发中,可根据项目需求灵活选择语言切换方式,并结合前端技术(如 vue、react)实现更流畅的多语言交互效果。

以上就是spring实现国际化与本地化的详细步骤的详细内容,更多关于spring国际化与本地化的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com