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)文章
Java 中Comparable和Comparator區(qū)別比較
本文,先介紹Comparable 和Comparator兩個接口,以及它們的差異;接著,通過示例,對它們的使用方法進(jìn)行說明2013-09-09Springboot傳輸數(shù)據(jù)時日期格式化問題
這篇文章主要介紹了Springboot傳輸數(shù)據(jù)時日期格式化問題,本文通過示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09SpringMVC 通過commons-fileupload實現(xiàn)文件上傳功能
這篇文章主要介紹了SpringMVC 通過commons-fileupload實現(xiàn)文件上傳,本文通過實例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02