为了演示Spring中对象是如何创建并放到spring容器中,这里新建一个maven项目:

其中pom.xm文件中只引入了一个依赖:

<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.9.RELEASE</version>
</dependency>
</dependencies>

其实我们只需要这一个,不过spring还是会自动导入他别的依赖,例如spring core,spring aop:

需要说明的是我这里并没有建spring boot项目,只是引入一个spring context依赖的maven项目。

新建一个config配置类,并没有@Configuration注解:

@ComponentScan("component")
public class MyConfig {
}

只有一个@ComponentScan注解,去扫描指定包。

新建一个类(bean),只有@Component注解:

@Component
public class People {
}

新建Test类,此类去创建spring context(spring上下文,或者说是spring容器):

import config.MyConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext; public class Test {
public static void main(String[] args) {
//通过注解配置类初始化 spring上下文
AnnotationConfigApplicationContext annotationConfigApplicationContext =
new AnnotationConfigApplicationContext(MyConfig.class);
//还有一种通过xml来初始化 spring上下文,这里就不介绍了。
//ClassPathXmlApplicationContext
System.out.println(annotationConfigApplicationContext.getBean("people"));
}
}

项目结构如图:

我们只关注bean的创建,所以在 new AnnotationConfigApplicationContext(MyConfig.class) 时会去扫描类,然后实例化。

this()调用此类的构造器:

这个reader和scanner和这里bean实例化没有关系,是一些扩展。我们关注他的父类构造器:

可见this()方法就是建立一个beanFactory工厂,至于细节暂时不去深入。

register()方法作用是新建一个BeanDefinition。

BeanDefinition顾名思义就是spring定义的一个描述bean的类,这个是接口,其描述类的属性由其子类扩展,比如class,lazy(懒加载)等等:

上面时AbstarctBeanDefinition类下的属性。spring根据我们的类(不管是@Service,@Controller,或者是通过@Bean方式),生成对应的BeanDefinition对象。

再把它放到一个Map中:

registerBeanDefinition有三个实现方法,不管哪个都有下面这一句:

即把各个BeanDefinition对象放入beanDefinitionMap中去,而这些map的集合就是spring 的容器。

所以register()做了两件事:

1:生成对应BeanDefinition对象;

2:放入beanDefinitionMap中。

最后再来看refresh()方法:

这个方法是spring中最复杂也是最重要的方法:

@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh(); // Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory); try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory); // Initialize message source for this context.
initMessageSource(); // Initialize event multicaster for this context.
initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses.
onRefresh(); // Check for listener beans and register them.
registerListeners(); // Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event.
finishRefresh();
} catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
} // Destroy already created singletons to avoid dangling resources.
destroyBeans(); // Reset 'active' flag.
cancelRefresh(ex); // Propagate exception to caller.
throw ex;
} finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}

其中invokeBeanFactoryPostProcessors()方法需要讲一讲,详见下一篇。

Spring Boot源码(五):BeanFactoryPostProcessor和BeanPostProcessor

Spring Boot源码(四):Bean装配的更多相关文章

  1. 曹工说Spring Boot源码(6)-- Spring怎么从xml文件里解析bean的

    写在前面的话 相关背景及资源: 曹工说Spring Boot源码(1)-- Bean Definition到底是什么,附spring思维导图分享 曹工说Spring Boot源码(2)-- Bean ...

  2. 曹工说Spring Boot源码系列开讲了(1)-- Bean Definition到底是什么,附spring思维导图分享

    写在前面的话&&About me 网上写spring的文章多如牛毛,为什么还要写呢,因为,很简单,那是人家写的:网上都鼓励你不要造轮子,为什么你还要造呢,因为,那不是你造的. 我不是要 ...

  3. 曹工说Spring Boot源码(2)-- Bean Definition到底是什么,咱们对着接口,逐个方法讲解

    写在前面的话 相关背景及资源: 曹工说Spring Boot源码系列开讲了(1)-- Bean Definition到底是什么,附spring思维导图分享 工程代码地址 思维导图地址 工程结构图: 正 ...

  4. 曹工说Spring Boot源码(3)-- 手动注册Bean Definition不比游戏好玩吗,我们来试一下

    写在前面的话 相关背景及资源: 曹工说Spring Boot源码系列开讲了(1)-- Bean Definition到底是什么,附spring思维导图分享 工程代码地址 思维导图地址 工程结构图: 大 ...

  5. 曹工说Spring Boot源码(4)-- 我是怎么自定义ApplicationContext,从json文件读取bean definition的?

    写在前面的话 相关背景及资源: 曹工说Spring Boot源码系列开讲了(1)-- Bean Definition到底是什么,附spring思维导图分享 工程代码地址 思维导图地址 工程结构图: 大 ...

  6. 曹工说Spring Boot源码(5)-- 怎么从properties文件读取bean

    写在前面的话 相关背景及资源: 曹工说Spring Boot源码(1)-- Bean Definition到底是什么,附spring思维导图分享 曹工说Spring Boot源码(2)-- Bean ...

  7. Spring Boot源码(六):Bean的创建详解

    继续之前的项目: People加上无参构造方法: @Component public class People { // private User user; public People(){ Sys ...

  8. 曹工说Spring Boot源码(9)-- Spring解析xml文件,到底从中得到了什么(context命名空间上)

    写在前面的话 相关背景及资源: 曹工说Spring Boot源码(1)-- Bean Definition到底是什么,附spring思维导图分享 曹工说Spring Boot源码(2)-- Bean ...

  9. # 曹工说Spring Boot源码(10)-- Spring解析xml文件,到底从中得到了什么(context:annotation-config 解析)

    写在前面的话 相关背景及资源: 曹工说Spring Boot源码(1)-- Bean Definition到底是什么,附spring思维导图分享 曹工说Spring Boot源码(2)-- Bean ...

随机推荐

  1. 基于Arduino开发的简易“高水位报警系统解决方案”

    长期以来,针对“某些办公室空调没有排水系统,只能用水桶接水,经常造成水漫金山的问题”而提出来的. 材料:Arduino开发板一块.水位传感器一个.高电平蜂鸣器一个.杜邦线若干. 原理:将水位传感器置于 ...

  2. session、cookie、sessionStorage、localStorage的简要理解

    一.cookie和session 首先 session 和 cookie 用于浏览器客户端与服务端数据交互,通过会话的方式跟踪浏览器用户身份. 1.cookie (1).一般由服务器生成,可以设置失效 ...

  3. 使用alpine制作最小化的JDK基础镜像

    注意:这里使用的是oracle的JRE,版本是1.8. 1.解压jre包,删除根目录下文本文件,然后删除其他不必要文件. #解压 tar xvcf jre-8u161-linux-x64.tar.gz ...

  4. 通过欧拉计划学Rust编程(第54题)

    由于研究Libra等数字货币编程技术的需要,学习了一段时间的Rust编程,一不小心刷题上瘾. 刷完欧拉计划中的63道基础题,能学会Rust编程吗? "欧拉计划"的网址: https ...

  5. 【限时免费】近1000G JAVA学习视频下载

    2020的情人节是个极特殊的情人节,面对肆虐的疫情,我们无法出门,宅在家里,也无法阻止你作为一名优秀程序员的梦想. 或许没有鲜花.没有蛋糕…… 姜小白就为大家备好了一份大礼,将自己近几年整理收藏的全网 ...

  6. selenium 调用JavaScript代码

    selenium 调用JavaScript代码 调用JavaScript方法有两种: execute_script(): 方法解释:是同步方法,用它执行js代码会阻塞主线程执行,直到js代码执行完毕. ...

  7. HEXO常用命令总结

    博客搬家:hexo常用命令总结 常见命令 hexo new "postName" #新建文章 hexo new page "pageName" #新建页面(新建 ...

  8. HDU_1864_01背包

    http://acm.hdu.edu.cn/showproblem.php?pid=1864 题目好像是输入的数据都是两位小数,先统计能报销的发票,然后把小数*100变成成熟就是01背包问题了. #i ...

  9. DaSiamRPN学习

    9月14日,2018年视觉目标跟踪挑战赛(Visual-Object-Tracking Challenge 2018)的结果在ECCV Workshop上揭晓.VOT2018共设三项任务:Baseli ...

  10. 在家想自学Java,有C语言底子,请问哪本书适合?

    一.问题剖析 看到这个问题,我想吹水两句再做推荐.一般发出这个疑问都处在初学编程阶段,编程语言都是相通的,只要你领悟了一门语言的"任督二脉",以后你学哪一门语言都会轻易上手.学语言 ...