Spring實(shí)現(xiàn)國(guó)際化與本地化的詳細(xì)步驟
一、核心概念:國(guó)際化(i18n)與本地化(l10n)
- 國(guó)際化(Internationalization):簡(jiǎn)稱(chēng) i18n,指設(shè)計(jì)應(yīng)用時(shí)使其能夠適應(yīng)不同語(yǔ)言和區(qū)域的過(guò)程。開(kāi)發(fā)者需將應(yīng)用中的固定文本(如提示信息、按鈕標(biāo)簽)提取為可替換的資源,避免硬編碼。
- 本地化(Localization):簡(jiǎn)稱(chēng) l10n,是根據(jù)用戶(hù)的語(yǔ)言、地區(qū)等偏好,將國(guó)際化后的應(yīng)用內(nèi)容顯示為對(duì)應(yīng)語(yǔ)言和格式(如日期、貨幣)的過(guò)程。例如,將英文界面切換為中文,或者根據(jù)地區(qū)顯示不同格式的日期(美式 “MM/dd/yyyy” vs 中式 “yyyy-MM-dd”)。
二、Spring 國(guó)際化實(shí)現(xiàn)步驟
1. 創(chuàng)建資源文件
在src/main/resources目錄下創(chuàng)建以messages為基礎(chǔ)名,后跟語(yǔ)言代碼和區(qū)域代碼的屬性文件。常見(jiàn)的語(yǔ)言代碼如zh(中文)、en(英文),區(qū)域代碼如CN(中國(guó))、US(美國(guó))。
messages.properties:默認(rèn)資源文件,用于未匹配到特定語(yǔ)言時(shí)的兜底顯示。messages_zh_CN.properties:簡(jiǎn)體中文資源文件。messages_en_US.properties:美式英語(yǔ)資源文件。
示例內(nèi)容:
messages.properties
greeting=Hello!
messages_zh_CN.properties
greeting=你好!
messages_en_US.properties
greeting=Hello!
2. 配置 MessageSource
在 Spring 配置類(lèi)(如@Configuration類(lèi))或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"); // 指定資源文件基礎(chǔ)名
messageSource.setDefaultEncoding("UTF-8"); // 設(shè)置編碼
return messageSource;
}
}application.properties 配置方式
spring.messages.basename=messages spring.messages.encoding=UTF-8
3. 在代碼中使用 MessageSource
通過(guò)注入MessageSource,調(diào)用getMessage方法獲取對(duì)應(yīng)語(yǔ)言的文本。
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()獲取當(dāng)前用戶(hù)的區(qū)域設(shè)置,messageSource.getMessage根據(jù)區(qū)域設(shè)置查找對(duì)應(yīng)的資源文件,返回相應(yīng)的文本。
三、本地化實(shí)現(xiàn):處理日期、數(shù)字和貨幣
Spring 通過(guò)DateFormat、NumberFormat等類(lèi)實(shí)現(xiàn)不同區(qū)域的格式轉(zhuǎn)換,結(jié)合@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類(lèi)型數(shù)據(jù)格式化為 “yyyy-MM-dd”,并根據(jù)用戶(hù)的區(qū)域設(shè)置動(dòng)態(tài)調(diào)整。
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);
}
}通過(guò)上述配置,在顯示貨幣金額時(shí),會(huì)根據(jù)用戶(hù)區(qū)域自動(dòng)使用對(duì)應(yīng)貨幣符號(hào)和格式(如¥、$)。
四、在 Web 應(yīng)用中實(shí)現(xiàn)語(yǔ)言切換
1. 通過(guò)請(qǐng)求參數(shù)切換語(yǔ)言
在 Controller 中接收lang參數(shù),設(shè)置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;
}
}用戶(hù)訪問(wèn)/setLang?lang=zh即可將語(yǔ)言切換為中文,訪問(wèn)/setLang?lang=en切換為英文。
2. 通過(guò) Cookie 或 Session 切換語(yǔ)言
實(shí)現(xiàn)自定義的LocaleResolver,將用戶(hù)選擇的語(yǔ)言存儲(chǔ)在 Cookie 或 Session 中,下次訪問(wèn)時(shí)自動(dòng)應(yīng)用。
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獲取語(yǔ)言,若不存在則使用默認(rèn)語(yǔ)言
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) {
// 將語(yǔ)言存儲(chǔ)到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 配置類(lèi)中注冊(cè)自定義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();
}
}五、總結(jié)
Spring 的國(guó)際化與本地化功能通過(guò)資源文件管理、MessageSource配置和Locale設(shè)置,為開(kāi)發(fā)者提供了一套完整的解決方案。通過(guò)合理配置和代碼實(shí)現(xiàn),能夠輕松滿(mǎn)足不同地區(qū)用戶(hù)的語(yǔ)言和格式需求,提升應(yīng)用的用戶(hù)體驗(yàn)和全球化競(jìng)爭(zhēng)力。在實(shí)際開(kāi)發(fā)中,可根據(jù)項(xiàng)目需求靈活選擇語(yǔ)言切換方式,并結(jié)合前端技術(shù)(如 Vue、React)實(shí)現(xiàn)更流暢的多語(yǔ)言交互效果。
以上就是Spring實(shí)現(xiàn)國(guó)際化與本地化的詳細(xì)步驟的詳細(xì)內(nèi)容,更多關(guān)于Spring國(guó)際化與本地化的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
springboot無(wú)法從靜態(tài)上下文中引用非靜態(tài)變量的解決方法
這篇文章主要介紹了springboot無(wú)法從靜態(tài)上下文中引用非靜態(tài)變量的解決方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-06-06
淺談Spring-cloud 之 sleuth 服務(wù)鏈路跟蹤
本篇文章主要介紹了淺談Spring-cloud 之 sleuth 服務(wù)鏈路跟蹤,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-01-01
Java實(shí)現(xiàn)BASE64編碼和解碼的方法
本篇文章主要介紹了Java實(shí)現(xiàn)BASE64編碼和解碼的方法,BASE64編碼通常用于轉(zhuǎn)換二進(jìn)制數(shù)據(jù)為文本數(shù)據(jù),有需要的可以了解一下。2016-11-11
SpringBoot實(shí)戰(zhàn)教程之新手入門(mén)篇
Spring Boot使我們更容易去創(chuàng)建基于Spring的獨(dú)立和產(chǎn)品級(jí)的可以"即時(shí)運(yùn)行"的應(yīng)用和服務(wù),下面這篇文章主要給大家介紹了關(guān)于SpringBoot實(shí)戰(zhàn)教程之入門(mén)篇的相關(guān)資料,需要的朋友可以參考下2022-03-03
Spring?Boot使用線程池處理上萬(wàn)條數(shù)據(jù)插入功能
這篇文章主要介紹了Spring?Boot使用線程池處理上萬(wàn)條數(shù)據(jù)插入功能,使用步驟是先創(chuàng)建一個(gè)線程池的配置,讓Spring Boot加載,用來(lái)定義如何創(chuàng)建一個(gè)ThreadPoolTaskExecutor,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友參考下吧2022-08-08
Java語(yǔ)言實(shí)現(xiàn)最大堆代碼示例
這篇文章主要介紹了Java語(yǔ)言實(shí)現(xiàn)最大堆代碼示例,具有一定參考價(jià)值,需要的朋友可以了解下。2017-12-12
如何將java或javaweb項(xiàng)目打包為jar包或war包
本文主要介紹了如何將java或javaweb項(xiàng)目打包為jar包或war包,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2022-07-07
Java高效實(shí)現(xiàn)復(fù)制PPT(PowerPoint)幻燈片
在日常的開(kāi)發(fā)工作中,我們經(jīng)常會(huì)遇到需要對(duì)Office文檔進(jìn)行編程處理的需求,本文將為您揭示如何利用強(qiáng)大的 Spire.Presentation for Java進(jìn)行PPT復(fù)制,有需要的小伙伴可以了解下2025-09-09
Java的IO流實(shí)現(xiàn)文件和文件夾的復(fù)制
這篇文章主要為大家詳細(xì)介紹了Java的IO流實(shí)現(xiàn)文件和文件夾的復(fù)制,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-06-06

