前言-宏观理解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

相关文章
相关标签/搜索