在Spring Boot中实现国际化(i18n)可以通过以下步骤完成。我们将使用Spring的消息源(MessageSource)功能来支持多语言文本。
首先,创建一个新的Spring Boot项目。可以使用Spring Initializr(https://start.spring.io/)来生成项目,选择以下依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>springboot-demo</artifactId>
<groupId>com.et</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>i18n</artifactId>
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
</project>
在src/main/resources
目录下,创建一个名为messages
的文件夹,并在其中创建不同语言的资源文件。例如:
messages.properties
(默认语言,通常是英语)messages_zh.properties
(中文)messages_fr.properties
(法语)每个文件的内容如下:
messages.properties(默认语言)
greeting=Hello!
farewell=Goodbye!
messages_zh.properties(中文)
greeting=你好!
farewell=再见!
messages_fr.properties(法语)
greeting=Bonjour!
farewell=Au revoir!
在Spring Boot中,默认会自动配置MessageSource
,但你可以自定义配置。创建一个配置类,例如MessageConfig
:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
@Configuration
public class MessageConfig {
@Bean
public ReloadableResourceBundleMessageSource messageSource() {
ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
messageSource.setBasename("classpath:messages/messages");
messageSource.setDefaultEncoding("UTF-8");
return messageSource;
}
}
创建一个控制器来处理请求并返回国际化的消息:
package com.et.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.LocaleResolver;
import javax.servlet.http.HttpServletRequest;
import java.util.Locale;
@RestController
public class GreetingController {
@Autowired
private MessageSource messageSource;
@Autowired
private LocaleResolver localeResolver;
@GetMapping("/greeting")
public String greeting(HttpServletRequest request, @RequestHeader(value = "Accept-Language", required = false) String acceptLanguage) {
Locale locale = localeResolver.resolveLocale(request);
// set language by Accept-Language
if (acceptLanguage != null && !acceptLanguage.isEmpty()) {
String[] languages = acceptLanguage.split(",");
String language = languages[0].split(";")[0]; // get the first language
language = language.trim();
locale = Locale.forLanguageTag(language);
}
return messageSource.getMessage("greeting", null, locale);
}
}
如果你有前端页面,可以通过AJAX请求获取国际化文本。例如,使用JavaScript:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Internationalization Example</title>
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
color: #333;
padding: 20px;
}
select {
margin-bottom: 20px;
}
</style>
</head>
<body>
<h1 id="greeting"></h1>
<label for="language-select">Choose a language:</label>
<select id="language-select">
<option value="en">English</option>
<option value="zh">中文</option>
<option value="fr">Français</option>
</select>
<script>
function fetchGreeting(lang) {
fetch('/greeting', {
method: 'GET',
headers: {
'Accept-Language': lang
}
})
.then(response => response.text())
.then(data => {
document.getElementById('greeting').innerText = data;
});
}
// Fetch greeting based on selected language
document.getElementById('language-select').addEventListener('change', function() {
const selectedLang = this.value;
fetchGreeting(selectedLang);
});
// Initial fetch in English
fetchGreeting('en');
</script>
</body>
</html>
启动Spring Boot应用,访问http://127.0.0.1:8088/index.html。效果如下图
通过以上步骤,你可以在Spring Boot应用中实现国际化。你可以根据用户的语言偏好动态地返回不同的文本内容。根据需要,你可以扩展更多语言和消息,并在前端实现语言切换功能。