Spring boot with i18n
节选自《Netkiller Spring Cloud 手札》
i18n 国际化
在 appliction.properties 中配置启用 i18n
spring.messages.basename=message
spring.messages.encoding=UTF-8
创建语言包文件
创建默认语言包文件 message.properties,当匹配不到语言时使用默认配置
member.name=Name
message_en_US.properties
member.name=Name
message_zh_CN.properties
member.name=姓名
注意:Eclipse 需要安装 properties 编辑工具,否则中文会自动转换成UTF8编码,无法直接阅读。
控制器重引用语言包
RestController
@RestController
public class HomeController {
@Autowired
private MessageSource messageSource;
@GetMapping("/lang")
public String language() {
String message = messageSource.getMessage("member.name", null, LocaleContextHolder.getLocale());
return message;
}
}
Controller
package cn.netkiller.controller;
import org.springframework.stereotype.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.MessageSource;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.ui.Model;
import java.util.Locale;
@Controller
public class HomeController {
@Autowired
private MessageSource messageSource;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String index(Locale locale, Model model){
// add parametrized message from controller
String welcome = messageSource.getMessage("welcome.message", new Object[]{"Neo Chan"}, locale);
model.addAttribute("message", welcome);
// obtain locale from LocaleContextHolder
Locale currentLocale = LocaleContextHolder.getLocale();
model.addAttribute("locale", currentLocale);
model.addAttribute("startMeeting", "10:30");
return "index";
}
}
参数传递
有时定义语言包会出现一种情况,一个句子中可能存在变量。例如:
恭喜你 XXXX 您已成为我们的会员
这样的需求,如果丁一两个key处理起来会非常麻烦。这里可以定义一个变量,通过参数传递来修改一句话中间的部分。
welcome=Welcom to {0}
@GetMapping("/lang/args")
public String welcome() {
String[] args = { "China" };
String message = messageSource.getMessage("welcome", args, LocaleContextHolder.getLocale());
return message;
}
参数以此类推 {0}, {1} ...... {n}
String welcome = messageSource.getMessage("welcome.message", new Object[]{"Neo chen"}, locale);