1.BeanFactory還是AppliactionContext:
這個我想大家肯定會選擇ApplicationContext,這也是Spring推薦選用的,ApplicationContext本身拓展了BeanFactory介面,而且對於一些特性,BeanFactory配置好了卻無法實現,例如交易管理和AOP。我們來看下Spring官方文檔提供的BeanFactory和ApplicationContext兩個介面所提供的功能:
從這我們基本可以看出ApplicationContext的優勢所在,所以開發中強烈建議使用ApplicationContext。
2.利用MessageSource實現國際化(i18N):
ApplicationContext介面擴充了MessageSource介面,因而提供了訊息處理的功能(i18n或者國際化)。MessageSource介面定義了如下幾個方法:
String getMessage(String code, Object[] args, String default, Locale locale):用來從MessageSource擷取訊息的基本方法。如果在指定的locale中沒有找到訊息,則使用預設的訊息。args中的參數將使用標準類庫中的MessageFormat來作訊息中替換值。
-
String getMessage(String code, Object[] args, Locale loc):本質上和上一個方法相同,其區別在:沒有指定預設值,如果沒找到訊息,會拋出一個NoSuchMessageException異常。
-
String getMessage(MessageSourceResolvable resolvable, Locale locale):上面方法中所使用的屬性都封裝到一個MessageSourceResolvable實現中,而本方法可以指定MessageSourceResolvable實現。
當一個ApplicationContext被載入時,它會自動在context中尋找已定義為MessageSource類型的bean。此bean的名稱須為messageSource。如果找到,那麼所有對上述方法的調用將被委託給該bean。否則ApplicationContext會在其父類中尋找是否含有同名的bean。如果有,就把它作為MessageSource。如果它最終沒有找到任何的訊息源,一個空的StaticMessageSource將會被執行個體化,使它能夠接受上述方法的調用。
Spring目前提供了兩個MessageSource的實現:ResourceBundleMessageSource和StaticMessageSource。它們都繼承NestingMessageSource以便能夠處理嵌套的訊息。StaticMessageSource很少被使用,但能以編程的方式向訊息源添加訊息。我們基本上都是用ResourceBundleMessageSource來執行個體化bean。如下代碼:
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basenames"> <list> <value>format</value> <value>window</value> </list> </property> </bean>
id屬性命名為messageSource,class為ResourceBundleMessageSource,我們在'applicationContext.xml'的檔案中(在classpath根目錄下)定義了一個messageSource bean,通過它的basenames屬性引用多個資源檔;而basenames屬性值由list元素所指定的三個值傳入,它們以檔案的形式存在並被放置在classpath的根目錄下(分別為format_zh_CN.properties,format_en_US.properties和windows.properties)(註:我這裡使用到了國際化,所以format定義了兩個properties,在測試類別中通過指定Locale設定的屬性自動去尋找對應的國際化資源)。
三個屬性檔案(format_zh_CN.properties,format_en_US.properties和windows.properties)代碼如下:
# format_zh_CN.propertiesmessage=你好# format_en_US.propertiesmessage=hello world# window.properties//這裡使用了兩個預留位置{0}和{1},在使用時通過object[]傳值進去message2=The arguments {0} {1} is required\!
測試類別代碼如下:
MessageSource source = new FileSystemXmlApplicationContext("src/applicationContext.xml"); String message = source.getMessage("message", null, Locale.US); System.out.println(message);
//Object[]數組裡面可以存放若干個元素,屬性檔案中有幾個預留位置,就按順序自動為預留位置附上值 String message2 = source.getMessage("message2", new Object[]{"dataSource", "default"}, "default", null); System.out.println(message2);
console輸出結果如下:
hello worldThe arguments dataSource default is required!
因為這裡使用了國際化,如果我將String message = source.getMessage("message", null, Locale.US);改為String message = source.getMessage("message", null, Locale.CHINA);時,console輸出結果如下:
你好The arguments dataSource default is required!
IoC我覺得要注意的是這些,其實Spring官方文檔對IoC眾多注意事項和特性有深入詳解,用到時可以隨時查閱。