https://javadoop.com/post/spring-ioc
spring容器最顶层接口 beanfactory定义了spring容器最顶层的接口,它定义了spring容器的最基本的接口,定义的规范比较基础,没有实现AOP功能、web应用等。而applicationContext则是有beanfactory衍生而来,以一种更向面向框架的方式工作以及对上下文进行分层和实现继承,通常比beanfactory优先。
spring容器初始化可以分为两大步骤:一 spring容器的创建、加载(reader)解析(parseDelegate)配置文件中的配置信息,并把解析出来的信息注册到spring容器中的注册表中(beanname、beanDefined的一个map)。
二 bean的初始化。 遍历spring容器注册表中的beanDefined。 主要有三大步骤 1createInstance 实例化 三种初始化策略 工厂方法、构造器注入,无参构造器三种策略 2populateBean属性注入 3initializeBean一些回调方法的调用
spring容器初始化过程
1 prepareRefresh(); 做一些初始化准备工作
2 obtainFreshBeanFactory 创建spring容器,加载解析配置文件,并将解析出来的数据注册到spring容器中 是否允许覆盖,是否允许循环引用 默认允许覆盖,允许循环引用
解析配置文件 parseDefaultElement processBeanDefinition parseBeanDefinitionElement
parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
parseMetaElements(ele, bd);
parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
parseConstructorArgElements(ele, bd);
parsePropertyElements(ele, bd);
parseQualifierElements(ele, bd);
parseCustomElement ComponentScanBeanDefinitionParser componentScan扫描组件包等。
3 invokeBeanFactoryPostProcessors 调用BeanFactoryPostProcessors
4 registerBeanPostProcessors
5 finishBeanFactoryInitialization 实例化、依赖注入、做一些回调处理
依赖注入和自动装配
依赖注入的方式只有两种,一种是构造器注入,一种是属性注入
自动装配有byName,byType等几种自动装配方式,默认不自动装配。自动装配可以通过xml配置autowire属性byName,byType和使用注解等进行自动装配,例如autowire(byType)和Qualifier(byName)等注解自动装配