2、Application Context
(1)什麼是Application Context
l 聚集能夠被所有組件使用的應用程序信息
l Bean定義的位置
l 加載多個contexts
l 層次contexts
l il8n,消息資源
l 資源訪問
l 事件傳播
(2)ApplicationContext
l 擴展BeanFactory
l 可以有一個父context
l 實現:
? FileSystemXmlApplicationContext
? ClassPathXmlApplicationContext
? XmlWebApplicationContext
l 例子:
l ApplicationContext可以讀取多個文件
(3)層次contexts
l 如果一個Bean在context中沒有找到,就會到父context中去找
l 創建一個層次contexts
(4)資源
l ApplicationContext處理資源位置
l ApplicationContext方法:
? URL全路經,如file:c:/test.dat
? 相對文件路徑,如WEB-INF/test.dat
? classpath僞URL,如classpath:test.dat
(5)資源編輯器
l 內建PropertyEditor
l 能夠在Bean定義中配置資源屬性
l 例子:
(6)il8n
l 國際化應用程序消息
l ApplicationContext方法:
代表一個messageSource Bean。
l ApplicationContext搜索messageSource Bean(必須實現MessageSource接口)
l 例子:在classpath中定義兩個資源束messages和errors
在classpath中搜索:
messages_pt_BR.properties errors_pt_BR.properties
messages_pt.properties errors_pt.properties
messages.properties errors.properties
(7)事件
l 事件傳播
? ApplicationContext處理事件,調用偵聽器
? Beans必須實現ApplicationListener接口來接收事件
? 應用程序可以擴展ApplicationEvent
? 內建事件:
2 ContextRefreshedEvent
2 ContextClosedEvent
2 RequestHandledEvent
l 偵聽事件
l 發送事件
(8)BeanFactoryPostProcessor
l 可以用來在它內部配置BeanFactory或Beans;應用程序contexts在它們的Bean定義中自動檢測BeanFactoryPostProcessor的Beans,在其它Beans創建之前應用它們
l post processor bean必須實現BeanFactoryPostProcessor接口
l 例子:增加定製編輯器到context中
(9)CustomEditorConfigurer
l BeanFactoryPostProcessor實現允許方便的註冊定製屬性編輯器
(10)典型的應用程序contexts
l 應用程序contexts通常與J2EE服務器定義的一個範圍相聯繫
? Web應用程序(javax.servlet.ServletContext):Sring提供通過偵聽器或Servlet實例化該context的能力
? Servlet:每個Servlet能夠擁有自己的應用程序context,來源於Web應用程序context
? EJBs:從EJB jar文件中的XML文檔中加載
l 不需要使用Singleton來引導Bean Factory