Spring註解(二)——————Bean的生命週期及BeanPostProcessor原理

關注微信公衆號【行走在代碼行的尋路人】獲取Java相關資料,分享項目經驗及知識乾貨。

以下測試的源碼地址:https://github.com/877148107/Spring-Annotation

  • Bean的生命週期

   bean創建----初始化---銷燬的過程

     1.創建

         bean對象創建,單實例:在容器啓動的時候就創建對象;多實例:容器啓動的時候不創建,每次獲取的時候創建

     2.初始化

        對象創建完成並賦值後調用初始化方法

     3.銷燬

        單實例:容器關閉後就銷燬;多實例:容器關閉後不會銷燬,容器不管理這個多實例bean

@Configuration
public class MyBeanLifeConfiguration {

    @Bean(initMethod = "init",destroyMethod = "destroy")
    public Car car(){
        return new Car();
    }
}


public class Car {

    public void car(){
        System.out.println("car 創建");
    }

    public void init(){
        System.out.println("car 初始化");
    }

    public void destroy(){
        System.out.println("car 銷燬");
    }
}
  • Bean的初始化、銷燬有四種方法進行

   1.通過上面自定義初始化、銷燬方法,並在註解當中去配置

   2.通過實現初始化InitializingBean和銷燬DisposableBean的接口

@Component
public class Cat implements InitializingBean, DisposableBean {

    public void cat(){
        System.out.println("cat 創建");
    }

    public void destroy() throws Exception {
        System.out.println("Cat destroy。。。。。。。。。");
    }

    public void afterPropertiesSet() throws Exception {
        System.out.println("Cat afterPropertiesSet。。。。。。。。。。");
    }
}

   3.可以使用JSR250;@PostConstruct:在bean創建完成並且屬性賦值完成;來執行初始化方法,@PreDestroy:在容器銷燬bean之前通知我們進行清理工作

   4.通過實現接口【BeanPostProcessor】的方式

@Component
public class MyBeanPostProcessor implements BeanPostProcessor {

    public Object postProcessBeforeInitialization(Object o, String s) throws BeansException {
        System.out.println("postProcessBeforeInitialization:"+o+"==>"+s);
        return o;
    }

    public Object postProcessAfterInitialization(Object o, String s) throws BeansException {
        System.out.println("postProcessAfterInitialization:"+o+"==>"+s);
        return o;
    }
}
  • 接口【BeanPostProcessor】的原理

Spring底層很多類實現了這個BeanPostProcessor後置處理器。很多註解功能都是通過這個接口實現的。

    第一步:創建容器AnnotationConfigApplicationContext

AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyBeanLifeConfiguration.class);

    第二步:初始化自定義後置處理器創建並初始化MyBeanPostProcessor

     當容器創建時回去掃描註解的組件bean添加到容器中,這裏我們自己創建了一個自定義的後置處理器MyBeanPostProcessor

    第三步:doCreateBean(beanName, mbdToUse, args)創建Bean

    第四步:populateBean(beanName, mbd, instanceWrapper)對Bean進行賦值等操作

    第五步:initializeBean(beanName, exposedObject, mbd)初始化bean

    第六步:applyBeanPostProcessorsBeforeInitialization(bean, beanName)調用初始化bean之前的方法

    第七步:invokeInitMethods(beanName, wrappedBean, mbd)調用初始化bean方法

    第八步:applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName)調用初始化bean之後的方法

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章