文档站点
Skip to content

国际化 ​

Laravel 用 lang/ 目录 + __() 辅助函数做多语言;Spring Boot 用 messages.properties 文件 + MessageSource 做 i18n。概念完全一致,只是配置方式不同。

配置步骤 ​

1. 加依赖(Spring Boot 3.x 需要) ​

xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>

实际上 Spring Boot 自带 MessageSource,多数场景不需要额外依赖。核心是配置 + 资源文件。

2. 建多语言文件 ​

src/main/resources/ 下:

messages.properties            ← 默认(英语)
messages_zh_CN.properties      ← 简体中文
messages_ja.properties         ← 日语

messages_zh_CN.properties:

properties
welcome=欢迎,{0}!
post.not_found=帖子不存在

默认 messages.properties:

properties
welcome=Welcome, {0}!
post.not_found=Post not found

3. 配置默认语言与基准名 ​

yaml
spring:
  messages:
    basename: messages        # 基准文件名
    encoding: UTF-8

TIP

basename: messages 会去读 messages_zh_CN.properties 这类文件。可以写多个基准名,用逗号分隔。

4. 获取本地化语言 ​

常见做法:前端传 Accept-Language 头,或登录后存到 Session,再放到 LocaleContextHolder:

java
// 例如在 Filter 里根据请求设置
LocaleContextHolder.setLocale(new Locale("zh", "CN"));

使用:MessageSource ​

java
@Service
public class PostService {

    private final MessageSource messageSource;

    public PostService(MessageSource messageSource) {
        this.messageSource = messageSource;
    }

    public String welcomeMessage(String name) {
        return messageSource.getMessage("welcome", new Object[]{name}, LocaleContextHolder.getLocale());
    }
}
  • messageSource.getMessage(key, 参数数组, locale) 对应 Laravel 的 __('welcome', ['name' => $name])
  • LocaleContextHolder.getLocale() 拿当前请求的语言

对应关系

LaravelSpring Boot
__('post.not_found')messageSource.getMessage("post.not_found", null, locale)
__('welcome', ['name' => $n])messageSource.getMessage("welcome", new Object[]{n}, locale)
lang/zh_CN/messages.phpmessages_zh_CN.properties
App::setLocale()LocaleContextHolder.setLocale(...)
:name 占位符{0} {1} 占位符

校验消息国际化 ​

Laravel 校验错误在 lang/xx/validation.php;Spring 的校验注解 message 支持键名:

java
@Data
public class PostDto {
    @NotBlank(message = "{post.title.required}")
    private String title;
}

messages_zh_CN.properties:

properties
post.title.required=标题不能为空

校验失败时自动取当前语言的消息。

TIP

{key} 包起来的 message 会被当作资源键去查找;不包 {} 则直接当作字面消息。这是 Spring 校验消息国际化的核心规则。

浏览器语言自动识别 ​

如果没手动设置 LocaleContextHolder,Spring 默认按 Accept-Language 请求头选择语言,用 LocaleResolver 实现。想改默认语言:

yaml
spring:
  web:
    locale: zh_CN
    locale-resolver: fixed      # 固定用默认语言,忽略请求头

小结 ​

  1. 消息文件命名:messages_语言.properties,UTF-8
  2. 取消息:messageSource.getMessage(key, args, locale)
  3. 语言来源:请求头 / Session / 手动 LocaleContextHolder
  4. 校验注解用 {key} 引用消息

基础入门十篇完成。接下来进入更深入的实战主题:模块化:包结构与模块划分。

面向 PHP / Laravel 开发者的 Spring Boot 中文文档