[spring]從頭開始-Internationalization with MessageSource
開發工具:IntelliJ IDEA 13
開發環境:jdk1.6.0_45
Framework:spring 3
示範一下如何使用 spring 來讀取 *.properties,並支持 i18n,我們直接建立一個演繹類別
MessageSourceDemo.java
import org.springframework.context.support.GenericXmlApplicationContext;
import java.util.Locale;
/**
* Created by Hsu on 2014/7/16.
*/
public class MessageSourceDemo {
public static void main(String[] args) {
GenericXmlApplicationContext ctx = new GenericXmlApplicationContext();
ctx.load("classpath:appContext/messageSource.xml");
ctx.refresh();
//設定語系
Locale english = Locale.ENGLISH;
Locale czech = new Locale("cs", "CZ");
Locale chinese = new Locale("zh", "TW");
// getMessage() 繼承自 AbstractApplicationContext
System.out.println(ctx.getMessage("msg", null, english));
System.out.println(ctx.getMessage("msg", null, czech));
System.out.println(ctx.getMessage("msg", null, chinese));
System.out.println(ctx.getMessage("nameMsg", new Object[] { "Clarence", "Ho" }, english));
}
}
當中比較特別的是下面這個方法 getMessage,就是用來讀取我們設定好的 *.properties
getMessagepublic String getMessage(String code, Description copied from interface: MessageSource Try to resolve the message. Treat as an error if the message can't be found. Specified by: getMessage in interface MessageSource Parameters: code - the code to lookup up, such as 'calculator.noRateSet' args - Array of arguments that will be filled in for params within the message (params look like "{0}", "{1,date}", "{2,time}" within a message), or null if none. locale - the Locale in which to do the lookup Returns: the resolved message Throws: NoSuchMessageException - if the message wasn't found See Also: |
再來看看spring configuration file 的部分
messageSource.xml
..
..標頭的部分省略
<bean id="messageSource"
class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<!-- 設定 properties 開頭檔名 -->
<value>labels</value>
</list>
</property>
</bean>
..結尾省略
最後是三個 *.properties 的部分:
labels_en.properties
msg=The quick brown fox jumped over the lazy dog
nameMsg=My name is {0} {1}
labels_cz_CZ.properties
msg=Príšerne žlutoucký kun úpel dábelské ódy
labels_zh_TW.properties
msg=測試中文
執行結果:
The quick brown fox jumped over the lazy dog
Príšerne žlutoucký kun úpel dábelské ódy
測試中文
My name is Clarence Ho
ps.若過程中或發現執行結果中文變成換碼,請參照