參考資料:<<Spring源碼深度解析>>
一矾瘾、bean的生命周期:
簡單描述:創(chuàng)建-->初始化-->銷毀
(后續(xù)會對Spring Bean的生命周期進行詳細(xì)分析)
二、容器管理bean的生命周期:可以自定義初始化和銷毀方法(三種)
-
第一種:指定init-method和destroy-method方法(使用xml配置)
-
第二種:使用注解配置:@Bean(initMethod = "xxName",destroyMethod = "xxName")
initMethod :實體bean中的init方法名稱
destroyMethod :實體bean中destroy方法名稱
初始化:對象創(chuàng)建完成鼠锈,并賦值好,調(diào)用初始化方法
銷毀:單實例,容器關(guān)閉的時候銷毀婆翔;多實例水泉,容器調(diào)用銷毀bean
第三種:
1.實現(xiàn) InitializingBean 接口的 afterPropertiesSet() 方法:當(dāng)beanFactory創(chuàng)建好對象善涨,并且將bean中的是所有屬性設(shè)置好后,調(diào)用afterPropertiesSet()方法草则;
2.實現(xiàn) DisposableBean 接口钢拧,實現(xiàn)bean的銷毀
- 第四種:使用JSR250注解方式
@PostConstruct:在bean創(chuàng)建完成并且屬性賦值完成,來執(zhí)行初始化方法炕横;該注解標(biāo)記在方法上
@PreDestroy:在容器銷毀bean之前通知銷毀操作 - 第五種:BeanPostProcessor 接口豌蟋,bean的后置處理器:
在bean初始化前后進行一些處理工作:
1.postProcessBeforeInitialization():初始化之前工作
2.postProcessAfterInitialization():初始化之后工作
三铆帽、BeanPostProcessor原理 / Spring對BeanPostProcessor的使用
1域蜗、原理(待補充)
2黎休、使用
- ApplicationContextAwareProcessor ,向組件中注入ioc容器:
用法:實體bean需要實現(xiàn) ApplicationContextAware 接口,重寫其 setApplicationContext( ApplicationContext applicationContext)方法
- BeanValidationPostProcessor,進行數(shù)據(jù)校驗
- AutowiredAnnotationBeanPostProcessor,自動注入注解
四夫壁、bean初始化相關(guān)的順序:
bean的創(chuàng)建(construct) --> bean初始化之前(實現(xiàn) BeanPostProcessor 接口) --> bean初始化的值(實現(xiàn)initializingBean接口的afterSetproperties() ) --> bean 初始化之后 (實現(xiàn) BeanPostProcessor 接口) --> bean的銷毀(實現(xiàn)DisposableBean 接口)