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"
9123

被折叠的 条评论
为什么被折叠?



