基本概念
Spring 中的 Bean 的生命周期,指的是 Bean 從創建到銷毀的過程。
下面來探究下幾個有關 Bean 生命周期配置的屬性。
lazy-init
lazy-init 表示延遲加載 Bean,默認在 Spring IoC 容器初始化時會實例化所有在配置文件定義的 Bean,若啟用了 lazy-init 則在調用 Bean 時才會去創建 Bean。
定義 Bean:
1
2
3
4
5
|
public class Animals { public Animals(){ System.out.println( "creating..." ); } } |
配置方式如下(以 xml 文件為例):
1
2
3
4
5
6
|
<!-- 表示啟用了延遲加載 --> < bean id = "animals" class = "com.demo.Animals" lazy-init = "true" /> <!-- 不啟用延遲加載 --> < bean id = "animals" class = "com.demo.Animals" lazy-init = "default" /> < bean id = "animals" class = "com.demo.Animals" /> |
調用驗證:
1
2
3
4
5
6
|
// 創建容器 String location = ... ApplicationContext factory = new FileSystemXmlApplicationContext(location); // 輸出結果: // 若啟用了 lazy-init 則輸出 creating...,否則無打印信息。 |
depends-on
depends-on 是指指定 Bean 初始化及銷毀時的順序。該屬性可以用于標識當前 Bean 初始化之前顯式地強制一個或多個 Bean 被初始化。若指定 Bean 的作用域都是 singleton 時,表示該屬性指定的 Bean 要在當前 Bean 銷毀之前被銷毀。
在 Bean 中定義:
1
2
3
4
5
6
7
8
9
10
|
public class BeanOne{ public BeanOne(){ System.out.println( "BeanOne..." ); } } public class BeanTwo{ public BeanTwon(){ System.out.println( "BeanTwo..." ); } } |
在配置文件中定義:
1
2
|
< bean id = "beanOne" class = "com.demo.BeanOne" lazy-init = "true" depends-on = "beanTwo" /> < bean id = "beanTwo" class = "com.demo.BeanTwo" lazy-init = "true" /> |
調用驗證:
1
2
3
4
5
6
|
String location = ... ApplicationContext factory = new FileSystemXmlApplicationContext(location); BeanOne beanOne= (BeanOne)factory.getBean( "beanOne" ); // 輸出結果: // BeanTwo... // BeanOne... |
觀察輸出結果,調用 BeanOne 時,Spring 會自動創建 BeanTwo 實例。
init-method & destory-method
當實例化一個 Bean 時,可能需要執行一個初始化操作來確保該 Bean 可用狀態。同樣地,當不需要 Bean 時,將其從容器中移除時,可能還需要按順序執行一些清楚工作。
為 Bean 定義初始化和銷毀操作,需要使用 init-method 和 destory-method 屬性。
定義 Bean
1
2
3
4
5
6
7
8
9
10
11
12
|
// 進入房間后要開燈,離開房間后要關燈 public class Room { public Room(){ System.out.println( "enter room..." ); } public void turnOnLights(){ System.out.println( "turn on..." ); } public void turnOffLights(){ System.out.println( "turn off..." ); } } |
在 Xml 文件中配置
1
|
< bean class = "com.demo.Room" init-method = "turnOnLights" destroy-method = "turnOffLights" /> |
在 Ioc 容器中實例化該 Bean,在銷毀它
1
2
3
4
5
6
7
8
|
// 實例化 Bean FileSystemXmlApplicationContext context = ... // 銷毀 Bean context.registerShutdownHook(); // 輸出內容: // enter room... // turn on... // turn off... |
總結
以上就是本文關于Spring配置使用之Bean生命周期詳解的全部內容,希望對大家有所幫助。有什么問題,歡迎大家留言交流討論。感謝朋友們對服務器之家網站的支持!
原文鏈接:http://blog.csdn.net/u012420654/article/details/52761391