springboot 实现多语言
时间: 2023-10-29 09:54:06 浏览: 71
在Spring Boot中实现多语言支持可以通过国际化(i18n)来实现。下面是实现多语言的基本步骤:
1. 在Spring Boot项目的资源文件夹(src/main/resources)下创建一个文件夹,命名为i18n(可以根据需要自定义名称)。
2. 在i18n文件夹下创建多个语言对应的属性文件,***.properties等。
- messages.properties 是默认的属性文件,用于存储英文(或其他语言***_en_US.properties 存储英文美国的键值对。
3. 在属性文件中定义键值对,例如:
- messages.properties:
```
greeting=Hello
```***```
greeting=你好
```
- messages_en_US.properties:
```
greeting=Hi
```
4. 在Spring Boot的配置文件(application.properties或application.yml)中配置默认的语言,例如:
- application.properties:
```
spring.messages.basename=i18n/messages
spring.messages.fallback-to-system-locale=false
spring.messages.encoding=UTF-8
```
- application.yml:
```yaml
spring:
messages:
basename: i18n/messages
fallback-to-system-locale: false
encoding: UTF-8
```
5. 在需要国际化的地方使用MessageSource获取对应的消息,例如在Controller中:
```java
@Autowired
private MessageSource messageSource;
@GetMapping("/greeting")
public String getGreeting(@RequestHeader(value = "Accept-Language", required = false) Locale locale) {
return messageSource.getMessage("greeting", null, locale);
}
```
这样,根据请求的Accept-Language头部信息,Spring Boot会自动选择对应的属性文件,并返回相应的消息。如果不存在对应的语言属性文件,则会返回默认的messages.properties中的消息。