當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
【Spring注解系列09】Spring初始化和销毁接口-InitializingBean与DisposableBean
生活随笔
收集整理的這篇文章主要介紹了
【Spring注解系列09】Spring初始化和销毁接口-InitializingBean与DisposableBean
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.InitializingBean與DisposableBean
InitializingBean
定義初始化邏輯,用于執行自定義初始化或者校驗已設置的屬性值等。
* Interface to be implemented by beans that need to react once all their properties * have been set by a {@link BeanFactory}: e.g. to perform custom initialization, * or merely to check that all mandatory properties have been set.DisposableBean
定義銷毀邏輯,用于一個實例bean銷毀后需要釋放資源等。 只有bean從容器中移除或者銷毀或容器關閉時,才會調用該方法。
ApplicationContext關閉時,默認對所有單例bean都會調用這個方法。
* Interface to be implemented by beans that want to release resources on destruction. * A {@link BeanFactory} will invoke the destroy method on individual destruction of a * scoped bean. An {@link org.springframework.context.ApplicationContext} is supposed * to dispose all of its singletons on shutdown, driven by the application lifecycle.2.實例
//實現InitializingBean,DisposableBean接口的bean public class BeanLife implements InitializingBean,DisposableBean{public BeanLife() {System.out.println("BeanLife--->construct...");}@Overridepublic void afterPropertiesSet() throws Exception {System.out.println("BeanLife--->InitializingBean.afterPropertiesSet");}@Overridepublic void destroy() throws Exception {System.out.println("BeanLife--->DisposableBean.destroy");} }//配置類 @Configuration public class BeanLifeCycleConfig {@Bean(value = "beanLife")public BeanLife life() {return new BeanLife();} }//測試 public class BeanLifeCycleTest {public static void main(String[] args) {AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(BeanLifeCycleConfig.class);System.out.println("applicationContext ..... 初始化結束");System.out.println("applicationContext ..... 準備關閉");applicationContext.close();System.out.println("applicationContext ..... 已關閉");} }測試結果: BeanLife--->construct... BeanLife--->InitializingBean.afterPropertiesSet applicationContext ..... 初始化結束applicationContext ..... 準備關閉 BeanLife--->DisposableBean.destroy applicationContext ..... 已關閉?
總結
以上是生活随笔為你收集整理的【Spring注解系列09】Spring初始化和销毁接口-InitializingBean与DisposableBean的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Spring注解系列08】@PostC
- 下一篇: 【Spring注解系列10】Spring