1.添加国际化文件
2.application.properties中添加配置参数
spring.messages.basename=i18n.common,i18n.login
3.编写工具类I18nUtil
package com.example.demo;
import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import java.util.Locale;
@Component
public class I18nUtil implements MessageSourceAware {
private MessageSource messageSource;
@Override
public void setMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;
}
public String get(String key, String locale){
Locale realLocale = Locale.getDefault();
if(!ObjectUtils.isEmpty(locale)){
switch (locale){
case "US":
realLocale = Locale.US;
break;
case "CN":
realLocale = Locale.CHINA;
break;
}
}
return messageSource.getMessage(key, null, realLocale);
}
}
4.测试controller
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private I18nUtil i18nUtil;
@RequestMapping("i18n")
public String i18n(String key, String locale){
return i18nUtil.get(key, locale);
}
}
5.测试
http://localhost:8000/user/i18n?key=order.tip&locale=US
http://localhost:8000/user/i18n?key=order.tip&locale=CN
6.另外方式
package com.example.demo;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import java.util.Locale;
@SpringBootApplication
@MapperScan("com.example.demo.test")
public class DemoApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(DemoApplication.class, args);
String message = context.getMessage("order.tip", null, Locale.US);
System.out.println(message);
}
}