SpringIOC容器Bean初始化和銷毀回調(diào)方式
前言
Spring Bean 的生命周期:init(初始化回調(diào))、destory(銷毀回調(diào)),在Spring中提供了四種方式來設(shè)置bean生命周期的回調(diào):
- 1.@Bean指定初始化和銷毀方法
- 2.實現(xiàn)接口
- 3.使用JSR250
- 4.后置處理器接口
使用場景:
在Bean初始化之后主動觸發(fā)事件。如配置類的參數(shù)。
1.@Bean指定初始化和銷毀方法
public class Phone {
private String name;
private int money;
//get set
public Phone() {
super();
System.out.println("實例化phone");
}
public void init(){
System.out.println("初始化方法");
}
public void destory(){
System.out.println("銷毀方法");
}
}@Bean(initMethod = "init",destroyMethod = "destory")
public Phone phone(){
return new Phone();
} AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig5.class); context.close();
打印輸出:
實例化phone
初始化方法
銷毀方法
2.實現(xiàn)接口
通過讓Bean實現(xiàn)InitializingBean(定義初始化邏輯),DisposableBean(定義銷毀邏輯)接口
public class Car implements InitializingBean, DisposableBean {
public void afterPropertiesSet() throws Exception {
System.out.println("對象初始化后");
}
public void destroy() throws Exception {
System.out.println("對象銷毀");
}
public Car(){
System.out.println("對象初始化中");
}
}
打印輸出:
對象初始化中
對象初始化后
對象銷毀
3.使用JSR250
通過在方法上定義@PostConstruct(對象初始化之后)和@PreDestroy(對象銷毀)注解
public class Cat{
public Cat(){
System.out.println("對象初始化");
}
@PostConstruct
public void init(){
System.out.println("對象初始化之后");
}
@PreDestroy
public void destory(){
System.out.println("對象銷毀");
}
}打印輸出:
對象初始化
對象初始化之后
對象銷毀
4.后置處理器接口
public class Dog implements BeanPostProcessor{
public Dog(){
System.out.println("對象初始化");
}
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
System.out.println(beanName+"對象初始化之前");
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
System.out.println(beanName+"對象初始化之后");
return bean;
}
}對象初始化
org.springframework.context.event.internalEventListenerProcessor對象初始化之前
org.springframework.context.event.internalEventListenerProcessor對象初始化之后
org.springframework.context.event.internalEventListenerFactory對象初始化之前
org.springframework.context.event.internalEventListenerFactory對象初始化之后
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot多模塊依賴沖突排查與架構(gòu)優(yōu)化實戰(zhàn)
本文詳細記錄了在SpringBoot多模塊項目開發(fā)中遇到的依賴版本沖突、模塊依賴設(shè)計不合理等問題的排查和解決方案的過程,主要重點關(guān)注了父模塊依賴管理、模塊化拆分、按需依賴等等,需要的朋友可以參考下2026-04-04
新手學(xué)習(xí)微服務(wù)SpringCloud項目架構(gòu)搭建方法
這篇文章主要介紹了新手學(xué)習(xí)微服務(wù)SpringCloud項目架構(gòu)搭建方法,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-01-01
Java實現(xiàn)簡易即時通訊系統(tǒng)的示例詳解
這篇文章主要為大家詳細介紹了如何使用Java模擬實現(xiàn)類似QQ的簡易即時通訊系統(tǒng),文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-06-06
spring使用Filter過濾器對Response返回值進行修改的方法
這篇文章主要介紹了spring使用Filter過濾器對Response返回值進行修改,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09

