Bean的生命周期 : 創建bean對象 – 屬性賦值 – 初始化方法調用前的操作 – 初始化方法 – 初始化方法調用后的操作 – …-- 銷毀前操作 – 銷毀方法的調用。
【1】init-method和destroy-method
自定義初始化方法和銷毀方法兩種方式:xml配置和注解。
① xml配置
<bean id="person"
class="com.core.Person" scope="singleton"
init-method="init" destroy-method="cleanUp"
autowire="byName" lazy-init="true" >
</bean>
② 注解配置
@Scope("singleton")
@Lazy
@Bean(name="person",initMethod="init",destroyMethod="cleanUp",
autowire=Autowire.BY_NAME)
public Person person01(){
return new Person("lisi", 20);
}
單實例bean在容器創建完成前會進行創建並初始化,在容器銷毀的時候進行銷毀。多實例bean(scope=prototype)在第一次獲取該bean實例時才會創建並初始化,且容器不負責該bean的銷毀。
【2】InitializingBean 和DisposableBean
InitializingBean 接口:
public interface InitializingBean {
void afterPropertiesSet() throws Exception;
}
-
在BeanFactory設置完bean屬性后執行
-
需要被bean實現的接口,一旦bean的屬性被BeanFactory設置后需要做出反應: 如,執行自定義初始化,或者僅僅是檢查是否設置了所有強制屬性。
-
實現InitializingBean 的可替代方式為給bean指定一個自定義的init-method,例如在一個xml bean 定義中。
-
在bean的屬性設置之后進行操作,不返回任何值但是允許拋出異常。
DisposableBean接口:
public interface DisposableBean {
void destroy() throws Exception;
}
- 被bean實現的接口,在銷毀時釋放資源,在Bean銷毀的時候調用該方法。
- 如果銷毀一個緩存的單例,一個BeanFactory 可能會調用這個銷毀方法。
- 在容器關閉時,應用上下文會銷毀所有的單例bean。
- 一種替代實現DisposableBean 接口的方案為指定一個自定義的destroy-method方法,例如在一個xml bean定義中。
自定義bean實現上述兩個接口
@Component
public class Cat implements InitializingBean,DisposableBean {
public Cat(){
System.out.println("cat constructor...");
}
@Override
public void destroy() throws Exception {
// TODO Auto-generated method stub
System.out.println("cat...destroy...");
}
@Override
public void afterPropertiesSet() throws Exception {
// TODO Auto-generated method stub
System.out.println("cat...afterPropertiesSet...");
}
}
測試結果
cat constructor...
cat...afterPropertiesSet...
容器創建完成...
四月 08, 2018 6:35:46 下午 org.springframework.context.annotation.AnnotationConfigApplicationContext
doClose
信息: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@11028347:
startup date [Sun Apr 08 18:35:46 CST 2018]; root of context hierarchy
cat...destroy...
【3】@PostConstruct和@PreDestroy
使用JSR250規范定義的兩個注解:
- @PostConstruct: PostConstruct注解作用在方法上,在依賴注入完成后進行一些初始化操作。這個方法在類被放入service之前被調用,所有支持依賴項注入的類都必須支持此注解。
- @PreDestroy:在容器銷毀bean之前通知我們進行清理工作
【4】BeanPostProcessor-Bean后置處理器
① 什么是bean后置處理器
在bean初始化前后進行一些處理工作
- postProcessBeforeInitialization:在初始化之前工作
- postProcessAfterInitialization:在初始化之后工作
【5】Spring底層使用BeanPostProcessor