| 知乎專欄 | 多維度架構 | | | 微信號 netkiller-ebook | | | QQ群:128659835 請註明“讀者” |
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);