ApplicationContext學習
相對BeanFactory而言,ApplicationContext提供了以下擴展功能:
1.國際化支持
我們可以在Beans.xml文件中,對程序中的語言信息(如提示信息)進行定義,將程序中的提示
信息抽取到配置文件中加以定義,為我們進行應用的各語言版本轉換提供了極大的靈活性。
2.資源訪問
支持對文件和URL的訪問。
3.事件傳播
事件傳播特性為系統中狀態改變時的檢測提供了良好支持。
4.多實例加載
可以在同一個應用中加載多個Context實例。
下面我們就這些特性逐一進行介紹。
1) 國際化支持
配置文件
<beans>
<description>Spring Quick Start</description>
<bean id="messageSource" <!—注意,這里名字必須為messageSource -->
class="org.springframework.context.support.ResourceB
undleMessageSource">
<property name="basenames">
<list>
<value>messages</value>
</list>
</property>
</bean>
</beans>
在配置節點中,我們指定了一個配置名“messages”。Spring會自動在CLASSPATH根路徑中按照如下順序搜尋配置文件并進行加載(以Locale為zh_CN為例):
messages_zh_CN.properties
messages_zh.properties
messages.properties
messages_zh_CN.class
messages_zh.class
messages.class
再加入二個properties文件
示例中包含了兩個配置文件,內容如下:
messages_zh_CN.properties:
userinfo=當前登錄用戶: [{0}] 登錄時間:[{1}]
messages_en_US.properties:
userinfo=Current Login user: [{0}] Login time:[{1}]
測試
import java.util.Calendar;
import java.util.Locale;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
publicclass TestAction {
publicstaticvoid main(String[] args) {
ApplicationContext ctx2=new
ClassPathXmlApplicationContext("applicationContext.xml");
Object[] arg = new Object[]{
"Erica",
Calendar.getInstance().getTime()
};
// 以系統默認Locale加載信息(對于中文WinXP而言,默認為zh_CN)
String msg = ctx2.getMessage("userinfo", arg,Locale.US);
System.out.println("Message is ===> "+msg);
}
}
結果
Message is ===> Current Login user: [Erica] Login time:[3/23/09 12:20 PM]
2) 資源訪問
ApplicationContext.getResource方法提供了對資源文件訪問支持,如:
Resource rs = ctx.getResource("classpath:config.properties");
File file = rs.getFile();
上例從CLASSPATH根路徑中查找config.properties文件并獲取其文件句柄。
getResource方法的參數為一個資源訪問地址,如:
file:C:/config.properties
/config.properties
classpath:config.properties
注意getResource返回的Resource并不一定實際存在,可以通過Resource.exists()方法對
其進行判斷。
3)事件傳播
ApplicationContext基于Observer模式(java.util包中有對應實現),提供了針對Bean的事件傳
播功能。通過Application. publishEvent方法,我們可以將事件通知系統內所有的
ApplicationListener。
posted on 2009-03-23 12:39
重慶理工小子 閱讀(429)
評論(0) 編輯 收藏 所屬分類:
Spring2