易學筆記--第2章:spring中的Bean/2.5 Bean的週期回撥
第2章:spring中的Bean/2.5 Bean的週期回撥/2.5.1 概念
-
- 這裡的宣告週期指的是Bean在建立完成後和銷燬時這兩個時間點,對於不同的作用域這兩個時間點有所不同
- 作用域對應的時間點
- 單例:singleton( 第2章:spring中的Bean/2.3 Bean的作用域/2.3.1 單例:singleton)
- 初始化:
- spring容器啟動時,也就是生成spring的applicationContext物件時,具體參考:
- bean物件被引用時
- applicationContext.getBean操作時
- 銷燬 通過applicationContext 物件呼叫registerShutdownHook方法
- 初始化:
- 原型作用域:prototype( 第2章:spring中的Bean/2.3 Bean的作用域/2.3.2 原型作用域:prototype
- 初始化:
- bean物件被引用時
- applicationContext.getBean操作時
- 銷燬:因為prototype作用域物件無法跟蹤,不會呼叫銷燬方法
- 初始化:
- 請求作用域:request( 第2章:spring中的Bean/2.3 Bean的作用域/2.3.3 請求作用域:request)
- 會話作用域:session( 第2章:spring中的Bean/2.3 Bean的作用域/2.3.4 會話作用域:session)
- 單例:singleton( 第2章:spring中的Bean/2.3 Bean的作用域/2.3.1 單例:singleton)
第2章:spring中的Bean/2.5 Bean的週期回撥/2.5.2 宣告週期方法
第2章:spring中的Bean/2.5 Bean的週期回撥/2.5.3 XML方式定義回撥方法
- Bean物件建立完成後初始化方法:init-method="方法名",這裡的方法名符合: 第2章:spring中的Bean/2.5 Bean的宣告週期/2.5.2 宣告週期方法
- Bean物件銷燬之前清理方法:destroy-method="方法名",這裡的方法名符合: 第2章:spring中的Bean/2.5 Bean的宣告週期/2.5.2 宣告週期方法
- 舉例:
- 類定義:
public class Foo {
//初始化方法
public void init() throws Exception {
System.out.println("Foo.init method invoked");
}
//銷燬方法
public void destroy() throws RuntimeException {
System.out.println("Foo.destroy method invoked");
}
}
- XML格式定義:
<!-- init和 destroy分別對應com.wiley.beginningspring.ch2.Foo類中的方法-->
<bean id="foo" class="com.wiley.beginningspring.ch2.Foo" init-method="init" destroy-method="destroy"/>
- 呼叫方法:
public class Main {
public static void main(String[] args) {
ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:/applicationContext.xml");
applicationContext.registerShutdownHook();
}
}
- 呼叫結果:Foo.init method invoked
Foo.destroy method invoked
- 類定義:
第2章:spring中的Bean/2.5 Bean的週期回撥/2.5.4 註解方式方式定義回撥方法
- Bean物件建立完成後初始化方法:使用註解:@PostConstruct,
- Bean物件銷燬之前清理方法:使用註解:@PreDestroy
- 舉例:
- 類定義:
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
public void init() throws Exception {
System.out.println("Bar.init method invoked");
public void destroy() throws RuntimeException {
- XML中定義:
- 呼叫方法:
public static void main(String[] args) {
- 呼叫結果: Bar.init method invoked
- 類定義:
第2章:spring中的Bean/2.5 Bean的週期回撥/2.5.5 實現介面方式
- Bean物件建立完成後初始化方法:實現介面InitializingBean中的public void afterPropertiesSet() throws Exception方法
- Bean物件銷燬之前清理方法:實現介面DisposableBean中的public void destroy() throws Exception方法
- 舉例:
- 舉例:
- 類定義:
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
public class Baz implements InitializingBean, DisposableBean {
public void afterPropertiesSet() throws Exception {
System.out.println("Baz.init method invoked");
public void destroy() throws Exception {
- XML中定義:
- 呼叫方法:
public static void main(String[] args) {
- 呼叫結果: Baz.init method invoked
- 類定義:
- 舉例: