一、ApplicationContext實現類
* ClassPathXmlApplicationContext : 加載類路徑下的spring配置文件
* FileSystemXmlApplicationContext:加載本地磁盤下的spring配置文件
二、spring框架的Bean管理的配置文件方式
1、 id屬性和name屬性的區別
* id -- Bean起個名字,在約束中採用ID的約束,唯一,必須以字母開始,可以使用字母、數字、連字符、下劃線、句話、冒號 id:不能出現特殊字符
* name -- Bean起個名字,沒有采用ID的約束(瞭解)現在不使用name了,因爲struts1已經不使用了
* 取值要求:name:出現特殊字符.如果<bean>沒有id的話 , name可以當做id使用
* Spring框架在整合Struts1的框架的時候,Struts1的框架的訪問路徑是以/開頭的,例如:/bookAction
2、 class屬性 – Bean對象的全路徑
3、scope屬性 – scope屬性代表Bean的作用範圍
* singleton -- 單例(默認值)加載配置文件的時候,創建對象,只創建一個。很大程度上可以減少內存的開銷。
* prototype -- 多例,每次從容器中獲取對象,纔會創建實例對象。銷燬工作不由容器負責。
* request -- 多例,應用在Web項目中,每次HTTP請求都會創建一個新的Bean
* session -- 多例,應用在Web項目中,同一個HTTP Session 共享一個Bean 一個會話
* globalsession -- 應用在Web項目中,多服務器間的session。很多人去訪問百度,百度爲每個人保存一個session。百度下有很多產品,比如你現在正在訪問百度文庫,然後又去訪問百度音樂,這時你不用去重新登錄,因爲兩個產品之間共享了一個Session。
* 一般singleton與prototype使用的較多
4、Bean對象的創建和銷燬的兩個屬性配置
* 說明:Spring初始化bean或銷燬bean時,有時需要作一些處理工作,因此spring可以在創建和拆卸bean的時候調用bean的兩個生命週期方法
* init-method -- 初始化方法,當bean被載入到容器的時候調用init-method屬性指定的方法
* destroy-method --銷燬方法, 當bean從容器中刪除的時候調用destroy-method屬性指定的方法
* 想查看destroy-method的效果,有如下條件
* scope= singleton有效
* web容器中會自動調用,但是main函數或測試用例需要手動調用(需要使用ClassPathXmlApplicationContext的close()方法)
三、運行例子
1、bean配置文件
scope=“singleton” 單例時
<bean id="us" class="cn.tx.service.UserServiceImpl"
scope="singleton" init-method="init" destroy-method="destory"/>
2、實現類
package cn.tx.service;
public class UserServiceImpl implements UserService{
public UserServiceImpl(){
System.out.println("UserServiceImpl對象被創建...");
}
public void hello() {
System.out.println("Hello IOC");
}
//初始化方法
public void init(){
System.out.println("對象創建完成,進行初始化操作!!");
}
//銷燬方法
public void destory(){
System.out.println("銷燬對象!!");
}
}
3、測試類
@Test
public void run3(){
//創建spring的IOC的工廠,加載src目錄下的配置文件,把配置文件中創建成對象,存儲到IOC容器中。
//ClassPathXmlApplicationContext :加載類路徑下的spring配置文件
//FileSystemXmlApplicationContext:加載本地磁盤下的spring配置文件
ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
System.out.println("===============================");
//從容器中獲取對象就ok. Map<"us",對象>
UserService us= (UserService) ac.getBean("us");
//調用對象方法即可
us.hello();
}
4、運行結果:
從運行結果我們可以看出單例模式時配置文件一加載,實例對象就會被創建。
scope=“prototype” 多例時
<bean id="us" class="cn.tx.service.UserServiceImpl"
scope="prototype" init-method="init" destroy-method="destory"/>
運行結果:
從運行結果中我們可以看出 需要從IOC容器中獲取對象時纔會創建實例對象。