當(dāng)前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
【Spring注解系列09】Spring初始化和销毁接口-InitializingBean与DisposableBean
生活随笔
收集整理的這篇文章主要介紹了
【Spring注解系列09】Spring初始化和销毁接口-InitializingBean与DisposableBean
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1.InitializingBean與DisposableBean
InitializingBean
定義初始化邏輯,用于執(zhí)行自定義初始化或者校驗(yàn)已設(shè)置的屬性值等。
* 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
定義銷毀邏輯,用于一個(gè)實(shí)例bean銷毀后需要釋放資源等。 只有bean從容器中移除或者銷毀或容器關(guān)閉時(shí),才會調(diào)用該方法。
ApplicationContext關(guān)閉時(shí),默認(rèn)對所有單例bean都會調(diào)用這個(gè)方法。
* 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.實(shí)例
//實(shí)現(xiàn)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 ..... 初始化結(jié)束");System.out.println("applicationContext ..... 準(zhǔn)備關(guān)閉");applicationContext.close();System.out.println("applicationContext ..... 已關(guān)閉");} }測試結(jié)果: BeanLife--->construct... BeanLife--->InitializingBean.afterPropertiesSet applicationContext ..... 初始化結(jié)束applicationContext ..... 準(zhǔn)備關(guān)閉 BeanLife--->DisposableBean.destroy applicationContext ..... 已關(guān)閉?
總結(jié)
以上是生活随笔為你收集整理的【Spring注解系列09】Spring初始化和销毁接口-InitializingBean与DisposableBean的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【Spring注解系列08】@PostC
- 下一篇: 【Spring注解系列10】Spring