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

