溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

如何理解spring加載類放到容器里面的過程

發布時間:2021-10-20 15:32:53 來源:億速云 閱讀:169 作者:柒染 欄目:大數據

如何理解spring加載類放到容器里面的過程,針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

     工作三年,初探得Spring原理,現在分享一下從宏觀上理解一下Spring啟動是如何加載Bean的。我們知道Spring所有的bean都是放在容器里面的,Spring的頂級容器BeanFactory定義了容器的基本規范,最直白的說法就是定義了如何獲取Bean的方法,那么既然能從容器中獲取Bean那就必須先把JavaBean放到容器里面。放到里面的是對象,既然是對象那就必須實例化、初始化,我們對象最簡單的就是new出來,也有通過反射獲取類全稱用getInstance來實例化的,那我們就從宏觀上理解,Spring將對象實例化后放到容器里面,然后我們再從容器里面拿出來用。所以問題就來了,從哪里獲取類全稱呢?對,你腦子里現在第一個反映就是XML,就是它,Spring通過解析XML,拿到所有的類全稱,通過反射進行實例化,放到容器里面的,我們知道并不是所有的類都是寫在XML里面的,還有很多注解:@Comonent、@Service、@Controller等等,這種的是怎么拿到的呢?不知道你們是否記得XML里面有一個context:component-scan標簽,這個標簽會掃描配置包下面帶有上述注解的所有類進行加載。這里們首先從宏觀上理解了,Spring從拿到所有要管理的類全稱實例化、初始化后放到容器里面去的來龍去脈了,但是JavaBean是如何變成Spring管理的bean的呢?其實在實例化之前Spring還做了許多的預處理操作后后置處理,先眼熟一下這個接口BeanDefinitionRegistryPostProcessor,

public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {

   /**
    * Modify the application context's internal bean definition registry after its
    * standard initialization. All regular bean definitions will have been loaded,
    * but no beans will have been instantiated yet. This allows for adding further
    * bean definitions before the next post-processing phase kicks in.
    * @param registry the bean definition registry used by the application context
    * @throws org.springframework.beans.BeansException in case of errors
    */
   void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;

}
public interface BeanFactoryPostProcessor {

   /**
    * Modify the application context's internal bean factory after its standard
    * initialization. All bean definitions will have been loaded, but no beans
    * will have been instantiated yet. This allows for overriding or adding
    * properties even to eager-initializing beans.
    * @param beanFactory the bean factory used by the application context
    * @throws org.springframework.beans.BeansException in case of errors
    */
   void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;

}

postProcessBeanDefinitionRegistry在對象實例化之前被調用,這個方法會修改Bean定義,mybatis就是通過實現此接口,將mapper類都修改成了MapperFactoryBean,后續會詳細講解次接口。然后再眼熟一下BeanPostProcessor這個接口,

public interface BeanPostProcessor {


    Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;

    
    Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;

}

在加載之前Spring會找到所有BeanPostProcessor這個接口下的所有子類并加載,實現這個接口的所有類,在初始化之前會執行postProcessBeforeInitializtion方法,初始化之后執行postProcessAfterInitializtion方法。

關于如何理解spring加載類放到容器里面的過程問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女