如何理解spring加载类放到容器里面的过程

如何理解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加载类放到容器里面的过程问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注创新互联行业资讯频道了解更多相关知识。

当前文章:如何理解spring加载类放到容器里面的过程
URL网址:https://www.cdcxhl.com/article4/jddpie.html

成都网站建设公司_创新互联,为您提供建站公司营销型网站建设微信公众号网站收录域名注册云服务器

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

成都网页设计公司