前言-宏觀理解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,spring

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這個接口,mybatis

public interface BeanPostProcessor {


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

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

}

在加載以前Spring會找到全部BeanPostProcessor這個接口下的全部子類並加載,實現這個接口的全部類,在初始化以前會執行postProcessBeforeInitializtion方法,初始化以後執行postProcessAfterInitializtion方法。app

 

----未完待續post

相關文章
相關標籤/搜索