Spring Boot 配置i18n国际化

1. 添加配置类 LocaleConfig
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;

import java.util.Locale;

@Configuration
public class LocaleConfig {

    @Bean
    public LocaleResolver localeResolver() {
        AcceptHeaderLocaleResolver localeResolver = new AcceptHeaderLocaleResolver();
        localeResolver.setDefaultLocale(Locale.SIMPLIFIED_CHINESE); // 设置默认语言环境为简体中文
        return localeResolver;
    }
}
2. 在 resources 目录下的 i18n 文件夹下,创建三个文件:
messages.properties
messages_en_US.properties
messages_zh_CN.properties

最终文件结构如下:

在 messages.properties 和 messages_zh_CN.properties 中添加内容

server.name=中文测试

在 messages_en_us.properties 中添加内容

server.name=english test
3. 在 application.properties 添加配置,配置国际化文件的所在目录
spring.messages.basename=i18n/messages
4. 创建 controller 类

import lombok.RequiredArgsConstructor;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
public class IndexController {
    private final MessageSource messageSource;

    @GetMapping("/")
    public String index() {
        return messageSource.getMessage("server.name", null, LocaleContextHolder.getLocale());
    }

}
5. 测试访问
// 中文
curl -H "Accept-Language: zh-CN"  "http://localhost:8080"

// 英文
curl -H "Accept-Language: en-US"  "http://localhost:8080"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值