《深入理解Spring系列之四:BeanDefinition装载前奏曲》中提到,对于非延迟单例bean的初始化在finishBeanFactoryInitialization(beanFactory)中完成。进入这个方法,代码如下。

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {// Initialize conversion service for this context.if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {beanFactory.setConversionService(beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));}// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);for (String weaverAwareName : weaverAwareNames) {getBean(weaverAwareName);}// Stop using the temporary ClassLoader for type matching.beanFactory.setTempClassLoader(null);// Allow for caching all bean definition metadata, not expecting further changes.beanFactory.freezeConfiguration();// Instantiate all remaining (non-lazy-init) singletons.beanFactory.preInstantiateSingletons();
}复制代码

关注最后一行代码,

beanFactory.preInstantiateSingletons()完成初始化所有非延迟的单例bean,进入这个方法的具体实现,代码如下。
public void preInstantiateSingletons() throws BeansException {if (this.logger.isDebugEnabled()) {this.logger.debug("Pre-instantiating singletons in " + this);}// Iterate over a copy to allow for init methods which in turn register new bean definitions.// While this may not be part of the regular factory bootstrap, it does otherwise work fine.List beanNames = new ArrayList(this.beanDefinitionNames);// Trigger initialization of all non-lazy singletonbeans...for (String beanName : beanNames) {RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {if (isFactoryBean(beanName)) {final FactoryBean factory = (FactoryBean) getBean(FACTORY_BEAN_PREFIX + beanName);boolean isEagerInit;if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {isEagerInit = AccessController.doPrivileged(new PrivilegedAction() {@Overridepublic Boolean run() {return ((SmartFactoryBean) factory).isEagerInit();}}, getAccessControlContext());}else {isEagerInit = (factory instanceof SmartFactoryBean &&((SmartFactoryBean) factory).isEagerInit());}
if (isEagerInit) {getBean(beanName);}}else {getBean(beanName);}}}// Trigger post-initialization callback for all applicable beans...for (String beanName : beanNames) {Object singletonInstance = getSingleton(beanName);if (singletonInstance instanceof SmartInitializingSingleton) {final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;if (System.getSecurityManager() != null) {AccessController.doPrivileged(new PrivilegedAction() {@Overridepublic Object run() {smartSingleton.afterSingletonsInstantiated();return null;}}, getAccessControlContext());}else {
smartSingleton.afterSingletonsInstantiated();}}}
}复制代码

从上面的代码中看到,只会对非延迟单例bean进行初始化,scope为其它值的bean会在使用到的时候进行初始化,如prototype。这里关注getBean方法,这个方法看着很眼熟,其实就是《深入理解Spring系列之一:开篇》示例代码中用到的getBean,Spring对这个方法做了重复使用。getBean方法的具体实现在doGetBean方法中,这个方法的代码很长就不贴代码了。在doGetBean中,首先会初始化其依赖的bean,然后进行自身的初始化,这个方法里关注如下的代码段。

 // Create bean instance.if (mbd.isSingleton()) {sharedInstance = getSingleton(beanName, new ObjectFactory() {@Overridepublic Object getObject() throws BeansException {try {return createBean(beanName, mbd, args);}catch (BeansException ex) {// Explicitly remove instance from singleton cache: It might have been put there// eagerly by the creation process, to allow for circular reference resolution.// Also remove any beans that receiveda temporary reference to the bean.destroySingleton(beanName);throw ex;}}});bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);}复制代码

这段代码完成了单例bean的初始化,追踪代码进入doCreateBean方法中,在这个方法中进行bean实例的创建、属性填充、将bean实例加入单例bean实例的缓存中。doCreateBean方法中有如下代码段。

if (instanceWrapper == null) {instanceWrapper = createBeanInstance(beanName, mbd, args);
}复制代码

createBeanInstance方法里完成bean实例的创建,具体过程可继续追踪代码查看,其实就是使用反射进行实例对象的创建。

深入理解Spring系列之六:bean初始化相关推荐

  1. 深入理解Spring系列之四:BeanDefinition装载前奏曲

    转载 https://mp.weixin.qq.com/s?__biz=MzI0NjUxNTY5Nw==&mid=2247483835&idx=1&sn=276911368d4 ...

  2. 深入理解Spring系列之三:BeanFactory解析

    转载 https://mp.weixin.qq.com/s?__biz=MzI0NjUxNTY5Nw==&mid=2247483824&idx=1&sn=9b7c2603093 ...

  3. spring扩展点之二:spring中关于bean初始化、销毁等使用汇总,ApplicationContextAware将ApplicationContext注入...

    <spring扩展点之二:spring中关于bean初始化.销毁等使用汇总,ApplicationContextAware将ApplicationContext注入> <spring ...

  4. Spring生命周期Bean初始化过程详解

    Spring生命周期Bean初始化过程详解 Spring 容器初始化 Spring Bean初始化 BeanFactory和FactoryBean 源码分析 Bean的实例化 preInstantia ...

  5. Spring系列之bean的使用

    转载自 https://www.cnblogs.com/xiaoxi/p/5850095.html 一.Bean的定义 <bean id="userDao" class=&q ...

  6. Spring IOC之Bean初始化篇

    Spring Bean初始化简介 Spring IOC 是Spirng反向控制应用程序需要的资源,说白了就是类的实例化(new)操作交由Spring来进行管理.在Spring中创建的实例化对象我们称之 ...

  7. 理解Spring框架中Bean的作用域

    本篇介绍Spring Bean实例的作用范围,Spring Bean实例的作用范围由配置项scope限定.通过本篇的学习,可以达成如下目标. ● 应用scope配置项配置Bean的作用域 ● 应用单例 ...

  8. Spring系列(三) Bean装配的高级技术

    profile 不同于maven的profile, spring的profile不需要重新打包, 同一个版本的包文件可以部署在不同环境的服务器上, 只需要激活对应的profile就可以切换到对应的环境 ...

  9. 深入理解Spring系列之一:开篇

    转载 https://mp.weixin.qq.com/s?__biz=MzI0NjUxNTY5Nw==&mid=2247483810&idx=1&sn=a2df14fdb63 ...

最新文章

  1. 前端传来的图片并保存_C# 将前端传来的图片文件分别以大图和缩略图保存
  2. 成熟的GAN会自己分析脸部纹理!英伟达StyleGAN团队出新作,网友:竟然还能有突破...
  3. 客户决定架构-架构是赤裸裸的
  4. Qt 多重继承时 moc 编译出错
  5. html5 css 文本缩进,使用 CSS 文本缩进和 Padding 隐藏文本 - 文章教程
  6. codeforces 1039B Subway Pursuit【二分+随机】
  7. mysql utf 8bm4 没用_不要在 MySQL 中使用“utf8”,請使用“utf8mb4”
  8. 直入灵魂的Python教学:《看动漫学Python》让学习不再枯燥
  9. kafka入门(一)简介
  10. Python爬取百度热榜前十条数据
  11. linux c语言 模拟键盘输入
  12. JRTPLib的编译步骤
  13. ros buntu安装手册_超详细 ROS安装教程
  14. 苹果手机怎么查看已连接的wifi密码_如何查看已连接的WiFi密码,可以这样做!...
  15. 如何控制局域网网速_单臂路由|N1盒子(OpenWRT)单线多拨实现网速叠加
  16. 广东第一高中生_广东男篮签下全美第一高中生 NBA状元热门征战CBA
  17. Android 学习笔记(5)之RxJava解析1
  18. 【学习】利用结构化思维学习
  19. 蒋宇捷——程序员的进化 - 在拉勾1024程序员节上的演讲
  20. iOS开发者遇到审核失败的原因及解决办法

热门文章

  1. Linux下编辑器vi/vim的使用介绍
  2. 【数据库】mysql 常用命令(一)
  3. 小黑盒不显示服务器,steam上买的游戏小黑盒不显示 | 手游网游页游攻略大全
  4. mysql实现sass_使用sass绘制三角形
  5. 计算机表格大小怎么调整,excel表格如何调整表格大小
  6. android锁屏流程_Android开机锁屏流程分析
  7. 傻瓜式动画制作软件_一个傻瓜版的动画制作软件——万彩动画大师
  8. linux本地agent执行脚本_github 4.4K星|马哥教育企业教练团队研发一款轻量级、无Agent自动化运维平台...
  9. AttributeError: Cant get attribute SPPF on module models
  10. JavaScript数据结构与算法——字典