標籤:http io ar sp 檔案 on log 代碼 bs
首先,建立一個描述message的XML檔案,名為messages.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- 資源國際化測試 -->
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basenames">
<list>
<value>org/rjstudio/spring/properties/messages</value>
</list>
</property>
</bean>
</beans>
這個Bean的id是定死的,只能為“messageSource”。這裡的Class需要填入MessageSource介面的實現。其中,在我看的書中只提及了兩個類,一個是:ResourceBundleMessageSource,另一個則是ReloadableResourceBundleMessageSource。其中,後者提供了無需重啟就可重新載入新配置的特性。
list節點的value子節點中的body值“org/rjstudio/spring/properties/messages”,是指org.rjstudio.spring.proerties包下的以messages為主要名稱的properties檔案。比如說,以Locale為zh_CN為例,Spring會自動在類路徑中在org.rjstudio.spring.properties包下按照如下順序搜尋設定檔並進行載入:
接下來,讓我們在org.rjstudio.spring.properties下,建立兩個messages的屬性檔案。一個名為messages_zh_CN.properties,另一個為messages_en_US.properties,分別對應國際化中的中國和美國。
在這兩個屬性檔案中分別建立一個userinfo屬性。
中國為:userinfo=當前登陸使用者[{0}] 登陸時間[{1}]
美國為:userinfo=current login user:[{0}] login time:[{1}]
好了,一切就緒,接下來可以寫段代碼來測試了。。建個類,寫個測試Main方法。
public class MessageTest {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext("messages.xml");
Object[] arg = new Object[] { "Erica", Calendar.getInstance().getTime() };
String msg = ctx.getMessage("userinfo", arg,Locale.CHINA);
System.out.println("Message is ===> " + msg);
}
}
最後輸出的結果是:Message is ===> 當前登入使用者:[Erica] 登入時間:[07-6-8 上午10:20]
ctx.getMessage("userinfo", arg,Locale.getDefault());這個方法,傳入的三個參數,第一個是properties檔案中對應的名。arg為一個對象數組,我們在properties裡面放置了兩個變數,[{0}]和[{1}],Spring會為我們給它們賦值。而最後則需要傳入一個Local。這裡用 Locale.CHINA代表中國。如果我們用Locale.US,則輸出會變為:
Message is ===> current login user:[Erica] login time:[6/8/07 10:59 AM]
OK,到這裡,就到這裡。
Spring 中的國際化Message的簡單例子(ApplicationContext) 不跟框架組成的版本