• java
  • go
  • 数据库
  • linux
  • 中间件
  • 书
  • 源码
  • 夕拾

  • java
  • go
  • 数据库
  • linux
  • 中间件
  • 书
  • 源码
  • 夕拾

ioc流程

目录

  • 目录
  • ioc体系概述
    • BeanFactory 概述
    • ApplicationContext 概述
    • 几个重要的接口(类)
      • ListableBeanFactory(interface)
      • HierarchicalBeanFactory
      • AutowireCapableBeanFactory
      • ConfigurableListableBeanFactory
        • 设置忽略的依赖关系,注册找到的特殊依赖
        • 获取bean定义 (可以访问属性值跟构造方法的参数值)
        • 锁定配置信息.在调用refresh时会使用到.
        • 预加载不是懒加载的单例.用于解决循环依赖问题
  • ApplicationContext 初始化过程源码阅读
    • 概述
    • 构造器
    • refresh()
      • prepareRefresh()
      • obtainFreshBeanFactory()
        • getBeanFactory()
      • prepareBeanFactory()
        • finishBeanFactoryInitialization()
        • getBean()
          • createBean()
          • initializeBean
    • 其他特性

ioc体系概述

BeanFactory 概述

基础类型IoC容器,提供完整的IoC服务支持。如果没有特殊指定,默认采用延迟初始化策略(lazy-load)。只有当客户端对象需要访问容器中的某个受管对象的时候,才对该受管对象进行初始化以及依赖注入操作。所以,相对来说,容器启动初期速度较快,所需要的资源有限。对于资源有限,并且功能要求不是很严格的场景,BeanFactory是比较合适的IoC容器选择。

ApplicationContext 概述

ApplicationContext在BeanFactory的基础上构建,是相对比较高级的容器实现,除了拥有BeanFactory的所有支持,ApplicationContext还提供了其他高级特性,比如事件发布、国际化信息支持等,ApplicationContext所管理的对象,在该类型容器启动之后,默认全部初始化并绑定完成。所以,相对于BeanFactory来说,ApplicationContext要求更多的系统资源,同时,因为在启动时就完成所有初始化,容器启动时间较之BeanFactory也会长一些。在那些系统资源充足,并且要求更多功能的场中,ApplicationContext类型的容器是比较合适的选择。

几个重要的接口(类)

ListableBeanFactory(interface)

java-doc的描述:

  • 获取所有的bean实例,而非一个一个按照名字等获取.如果BeanFactory实现了预加载所有的bean,可能会继承这个接口
  • 如果实现了hierarchialBeanFactory,那么在当前工厂中,返回值不考虑分级,使用BeanFactoryUtils帮助类获取祖先工厂的beans,
  • 此接口只考虑当前工厂实现的beans,会忽略那些 singleton-bean,如ConfigurableBeanFactory的registerSingleton注册的单例bean.(getBeanNamesOfType,getBeansOfType会考虑手动注册的singletion-beans),beanFactory的getBean同样可以透明的访问这些特殊bean.在典型情况下,所有的bean都是由external bean定义,所以应用不需要顾虑这些差别.
  • 注意:getBeanDefinitionCount和containsBeanDefinition的实现方法因为效率比较低,还是少用为好.

它可以枚举所有的bean实例,而不是客户端通过名称一个一个的查询得出所有的实例。要预加载所有的bean定义的beanfactory可以实现这个接口来。该接口定义了访问容器中Bean基本信息的若干方法,如查看Bean的个数、获取某一类型Bean的配置名、查看容器中是否包括某一Bean等方法.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//是否包含bean
boolean containsBeanDefinition(String beanName);
// 当前factory中定义的bean数量
int getBeanDefinitionCount(); 
// 获取当前工厂中定义的所有bean 的name
String[] getBeanDefinitionNames();

//根据bean 的类型获取bean

//这边的方法仅检查顶级bean.它不会检查嵌套的bean
//.FactoryBean创建的bean会匹配为FactoryBean而不是原始类型.

//一样不会考虑父factory中的bean
// 非要用可以通过BeanFactoryUtils中的beanNamesForTypeIncludingAncestors.
//其他方式注册的单例这边会纳入判断.
//这个版本的getBeanNamesForType会匹配所有类型的bean,包括单例,原型,FactoryBean.返回的bean names会根据backend 配置的进行排序.


// 获取给定类型的bean names(包括子类),通过bean 定义或者FactoryBean的getObjectType判断.
String[] getBeanNamesForType(Class<?> type);

String[] getBeanNamesForType(Class<?> type, boolean includeNonSingletons, boolean allowEagerInit);
// 如果保护懒加载的类,FactoryBean初始化的类和工厂方法初始化的类会被初始化.就是说执行这个方法会执行对应的初始化.
<T> Map<String, T> getBeansOfType(Class<T> type) throws BeansException;

<T> Map<String, T> getBeansOfType(Class<T> type, boolean includeNonSingletons, boolean allowEagerInit) throws BeansException;

//查找使用注解的类
Map<String, Object> getBeansWithAnnotation(Class<? extends Annotation> annotationType) throws BeansException;

//查找一个类上的注解,如果找不到,父类,接口使用注解也算.
<A extends Annotation> A findAnnotationOnBean(String beanName, Class<A> annotationType);

HierarchicalBeanFactory

提供父容器的访问功能.至于父容器的设置,需要找ConfigurableBeanFactory的setParentBeanFactory(接口把设置跟获取给拆开了!).

1
2
3
4
5
// 获取父容器 bean factory
BeanFactory getParentBeanFactory();

//判断当前容器是否包含bean,忽视父级工厂的beans.
boolean containsLocalBean(String name);

AutowireCapableBeanFactory

对于想要拥有自动装配能力,并且想把这种能力暴露给外部应用的BeanFactory类需要实现此接口。
正常情况下,不要使用此接口,应该更倾向于使用BeanFactory或者ListableBeanFactory接口。此接口主要是针对框架之外,没有向Spring托管Bean的应用。通过暴露此功能,Spring框架之外的程序,具有自动装配等Spring的功能。
需要注意的是,ApplicationContext接口并没有实现此接口,因为应用代码很少用到此功能,如果确实需要的话,可以调用ApplicationContext的getAutowireCapableBeanFactory方法,来获取此接口的实例。
如果一个类实现了此接口,那么很大程度上它还需要实现BeanFactoryAware接口。它可以在应用上下文中返回BeanFactory。

ConfigurableListableBeanFactory

提供bean definition的解析,注册功能,再对单例来个预加载(解决循环依赖问题).

貌似我们一般开发就会直接定义这么个接口了事.而不是像Spring这样先根据使用情况细分那么多,到这边再合并

设置忽略的依赖关系,注册找到的特殊依赖
1
2
3
4
5
6
7
8
9
10
    void ignoreDependencyType(Class<?> type); // 忽略类型

    void ignoreDependencyInterface(Class<?> ifc); // 忽略接口

    void registerResolvableDependency(Class<?> dependencyType
, Object autowiredValue);

    boolean isAutowireCandidate(String beanName,
DependencyDescriptor descriptor)
throws NoSuchBeanDefinitionException;
获取bean定义 (可以访问属性值跟构造方法的参数值)
1
2
    BeanDefinition getBeanDefinition(String beanName)
throws NoSuchBeanDefinitionException;
锁定配置信息.在调用refresh时会使用到.
1
2
3
4
5
6
//冻结全部bean定义
//给被注册的bean定义发信号告诉它们今后不再被修改和进一步后续处理。
//它允许factory去积极缓存bean定义元数据。
    void freezeConfiguration();

    boolean isConfigurationFrozen();
预加载不是懒加载的单例.用于解决循环依赖问题
1
    void preInstantiateSingletons() throws BeansException;

ApplicationContext 初始化过程源码阅读

概述

简单来说,IoC容器的初始化是由refresh()方法来启动的

这个启动包括BeanDefinition的Resource定位、载入和注册.

spring将这三个过程分开,使用不同的模块来完成,如使用ResourceLoader、BeanDefinitionReader等,可以让用户更灵活的对三个过程进行修改,定义出最适合自己的IoC容器的初始化过程

  1. 第一个过程是Resource定位过程(指BeanDefinition)资源定位。由ResourceLoader通过统一的Resource接口来完成,这个Resource对各种形式的BeanDefinition的使用都提供了统一接口。
  2. 第二个过程是BeanDefinition的载入。这个载入过程把用户定义好的Bean表示成IoC容器内部的数据结构。具体来说,这个BeanDefinition实际上就是POJO对象在IoC容器中的抽象,通过这个BeanDefinition定义数据结构,使IoC容器能够方便地对POJO对象进行管理。
  3. 第三个过程是向IoC容器注册这些BeanDefinition的过程。这个过程是通过调用BeanDefinitionRegistry接口的实现来完成。这个注册过程把载入过程中解析得到的BeanDefinition向容器进行注册。在IoC容器内部将BeanDefinition注入到一个HashMap中去,IoC容器就是通过这个HashMap持有这些BeanDefinition数据。
  • IoC容器初始化过程中,一般不包含Bean依赖注入的实现。在Spring IoC的设计中,Bean定义的载入和依赖注入是两个独立的过程。依赖注入一般发生在应用第一次通过getBean向容器索取bean的时候。但是有一个例外值得注意,在使用IoC容器时有一个预实例化的配置,通过这个预实例化的配置(具体来说,可以通过为Bean定义信息中的lazyinit属性),用户可以对容器初始化过程做一个微小的控制,从而改变这个被设置了lazyinit属性的Bean的依赖注入过程。举例来说,如果我们对某个Bean设置了lazyinit属性,那么这个Bean的依赖注入在IoC容器初始化时就预先完成了。而不需要等到整个初始化完成以后,第一次使用getBean时才会触发。

补充:

  • application完成的事情

    1. 标识一个应用环境
    2. 利用beanfactory构建bean对象
    3. 保存对象关系表
    4. 各种事件
  • ConfigurableApplicationContext,context可被修改。构建context种,用户可以动态添加或者修改已有配置信息。最常使用的事可更新的context–AbstractRefreshableApplicationContext

  • WebApplicationContext,可直接访问ServletContext,通常情况下,使用的少

application完成的事情

  1. 标识一个应用环境
  2. 利用beanfactory构建bean对象
  3. 保存对象关系表
  4. 各种事件

core中,资源的加载、解析、描述工作委托了ResourcePatternResolver类。

构造器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* Create a new ClassPathXmlApplicationContext with the given parent,
* loading the definitions from the given XML files.
* @param configLocations array of resource locations
* @param refresh whether to automatically refresh the context,
* loading all bean definitions and creating all singletons.
* Alternatively, call refresh manually after further configuring the context.
* @param parent the parent context
* @throws BeansException if context creation failed
* @see #refresh()
*/
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
throws BeansException {

super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}

refresh()

refersh命名: ApplicationContext 建立起来以后,其实我们是可以通过调用 refresh() 这个方法重建的,refresh() 会将原来的 ApplicationContext 销毁,然后再重新执行一次初始化操作。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
public void refresh() throws BeansException, IllegalStateException {
//加锁
synchronized (this.startupShutdownMonitor) {
// 准备工作主
prepareRefresh();

// 加载(Xml)资源并解析,根据解析结果组装BeanDefinitions,然后初始化BeanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

// 配置beanfactory的类加载器以及后置处理器post-processors
prepareBeanFactory(beanFactory);

try {
// 如果bean 实现了 BeanFactoryPostProcessor
// 那么在容器初始化以后,Spring 会负责调用里面的 postProcessBeanFactory 方法
// 此时所有的类都已经加载完毕,但是还未初始化,可以用类似BeanFactoryProcessor接口实现类搞事情
postProcessBeanFactory(beanFactory);
// 调用BeanFactoryPostPorcessor中的方法
invokeBeanFactoryPostProcessors(beanFactory);
// 注册 BeanPostProcessor
// 此接口两个方法: postProcessBeforeInitialization 和 postProcessAfterInitialization
// 两个方法分别在 Bean 初始化之前和初始化之后得到执行。注意,到这里 Bean 还没初始化
registerBeanPostProcessors(beanFactory);
// 国际化....用到再说9,
initMessageSource();
// 初始化当前 ApplicationContext 的事件广播器
initApplicationEventMulticaster();
/**
* 模板方法,以添加特定的 context 刷新。
* 在初始化特殊的实例之前调用。在singleton初始化之前
* Called on initialization of special beans, before * instantiation of singletons.
* 刷新由子类实现。
*/
onRefresh();
// 注册事件监听器
registerListeners();
// 初始化所有的bean,lazy-init的除外
finishBeanFactoryInitialization(beanFactory);
// 广播事件,初始化完毕。
finishRefresh();
}
catch (BeansException ex) {
// 发生异常,销毁所有beans
// Destroy already created singletons to avoid dangling resources.
beanFactory.destroySingletons();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
}
}

prepareRefresh()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
protected void prepareRefresh() {
// 记录启动时间,
// 将 active 属性设置为 true,closed 属性设置为 false,它们都是 AtomicBoolean 类型
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);

if (logger.isInfoEnabled()) {
logger.info("Refreshing " + this);
}

// Initialize any placeholder property sources in the context environment
initPropertySources();

// 校验 xml 配置文件
getEnvironment().validateRequiredProperties();

this.earlyApplicationEvents = new LinkedHashSet<ApplicationEvent>();
}

obtainFreshBeanFactory()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
// 刷新BeanFactory,负责这个工作做在类AbstractRefreshableApplicationContext中,
// 主要作用:
// 顾名思义这是专门用来刷新的。
// load-BeanDefinitions, 通过beanDefinitionReader读取,放入resources[]中
// getBeanFactory方法同样是从此类中获取得到的Beanfactory并返回。
refreshBeanFactory();

ConfigurableListableBeanFactory beanFactory = getBeanFactory();

if (logger.isInfoEnabled()) {
logger.info("Bean factory for application context [" + getId() + "]: " +
ObjectUtils.identityToString(beanFactory));
}
if (logger.isDebugEnabled()) {
logger.debug(beanFactory.getBeanDefinitionCount() + " beans defined in " + this);
}

return beanFactory;
}
getBeanFactory()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/**
* This implementation performs an actual refresh of this context's underlying
* bean factory, shutting down the previous bean factory (if any) and
* initializing a fresh bean factory for the next phase of the context's lifecycle.
*/
protected final void refreshBeanFactory() throws BeansException {
// 是否有beanFactory,销毁并关闭(置空),避免重复加载BeanFacoty.
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
//创建具体的beanFactory,这里创建的是DefaultListableBeanFactory
//最重要的beanFactory
//spring注册及加载bean就靠它。其实这里还是一个基本的容器
DefaultListableBeanFactory beanFactory = createBeanFactory();
// bean的特性主要包含两个
// allowBeanDefinitionOverriding
// allowCircularReferences 默认为true,即关闭循环依赖,在遇到时抛出异常.
// - 循环引用解析意味着其中一个涉及的bean将接收对另一个尚未完全初始化的bean的引用。
// - 不建议循环依赖
customizeBeanFactory(beanFactory);
// 加载beanDefinitions
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException(
"I/O error parsing XML document for application context [" + getDisplayName() + "]", ex);
}
}

prepareBeanFactory()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
* Configure the factory's standard context characteristics,
* such as the context's ClassLoader and post-processors.
* @param beanFactory the BeanFactory to configure
*/
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// 设置内部beanFactory的类加载器
beanFactory.setBeanClassLoader(getClassLoader());
// 属性编辑器支持
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this));
//设置beanfactory的上下文回调,这个 processor 比较简单:
// 实现了 Aware 接口的 beans 在初始化的时候,这个 processor 负责回调,
// 这个我们很常用,如我们会为了获取 ApplicationContext 而 implement ApplicationContextAware
// 注意:它不仅仅回调 ApplicationContextAware,
// 还会负责回调 EnvironmentAware、ResourceLoaderAware 等
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
// 忽略自动装配的接口
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// MessageSource 被注册成了一个普通bean。
// 若实现了以下几个接口,自动装配。
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this);

// Detect a LoadTimeWeaver and prepare for weaving, if found.
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME) && JdkVersion.isAtLeastJava15()) {
// Register the (JDK 1.5 specific) LoadTimeWeaverAwareProcessor.
// LTW 类加载期织入
try {
Class ltwapClass = ClassUtils.forName(
"org.springframework.context.weaving.LoadTimeWeaverAwareProcessor",
AbstractApplicationContext.class.getClassLoader());
BeanPostProcessor ltwap = (BeanPostProcessor) BeanUtils.instantiateClass(ltwapClass);
((BeanFactoryAware) ltwap).setBeanFactory(beanFactory);
beanFactory.addBeanPostProcessor(ltwap);
}
catch (ClassNotFoundException ex) {
throw new IllegalStateException("Spring's LoadTimeWeaverAwareProcessor class is not available");
}
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
finishBeanFactoryInitialization()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* Finish the initialization of this context's bean factory,
* initializing all remaining singleton beans.
*/
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
beanFactory.setTempClassLoader(null);
// 开始预处理化singleton-bean,所以直接冻结,使用缓存。
beanFactory.freezeConfiguration();

// Instantiate all remaining (non-lazy-init) singletons.
beanFactory.preInstantiateSingletons();
}

// 初始化bean,直接调用getBean(beanName)
public void preInstantiateSingletons() throws BeansException {
if (this.logger.isInfoEnabled()) {
this.logger.info("Pre-instantiating singletons in " + this);
}

synchronized (this.beanDefinitionMap) {
// 触发所有的 singleton beans 的初始化操作
for (Iterator it = this.beanDefinitionNames.iterator(); it.hasNext();) {
String beanName = (String) it.next();
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
// 非抽象,非单例,非懒加载的不初始化。
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
// 处理 FactoryBean
if (isFactoryBean(beanName)) {
FactoryBean factory = (FactoryBean) getBean(FACTORY_BEAN_PREFIX + beanName);
if (factory instanceof SmartFactoryBean && ((SmartFactoryBean) factory).isEagerInit()) {
getBean(beanName);
}
}
else {
// 对于普通的 Bean,只要调用 getBean(beanName) 这个方法就可以进行初始化了
getBean(beanName);
}
}
}
}
}



getBean()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}

protected Object doGetBean(
final String name,
final Class requiredType,
final Object[] args,
boolean typeCheckOnly) throws BeansException {
// 处理 & 和 别名
final String beanName = transformedBeanName(name);
// 返回值
Object bean = null;

// 检查下是不是已经创建过.
Object sharedInstance = getSingleton(beanName);
// args refresh()调用时为null,不为null,为创建新的bean
if (sharedInstance != null && args == null) {
if (logger.isDebugEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
}
// 普通 Bean ,直接返回 sharedInstance,
// FactoryBean , 返回它创建的实例对象
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}

else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
// 已经创建过了此 beanName 的 prototype 类型的 bean,那么抛异常,
// 往往是因为陷入了循环引用
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}

// Check if bean definition exists in this factory.
// 检查这个容器是否有这个beanDefinition
BeanFactory parentBeanFactory = getParentBeanFactory();
// 父容器总检查一下,若有,返回父容器
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
String nameToLookup = originalBeanName(name);
if (args != null) {
// Delegation to parent with explicit args.
return parentBeanFactory.getBean(nameToLookup, args);
}
else {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
// typeCheckOnly 为 false,将当前 beanName 放入一个 alreadyCreated 的 Set 集合中。
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}

// 此时还没有创建bean
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);

// Guarantee initialization of beans that the current bean depends on.
// 初始化bean所依赖的所有bean
String[] dependsOn = mbd.getDependsOn();
if (dependsOn != null) {
for (int i = 0; i < dependsOn.length; i++) {
String dependsOnBean = dependsOn[i];
getBean(dependsOnBean);
// 注册一下依赖关系
registerDependentBean(dependsOnBean, beanName);
}
}

// Create bean instance.
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, new ObjectFactory() {
public 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 received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}

else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
// 如果不是 singleton 和 prototype 的话,需要委托给相应的实现类来处理
else {
String scopeName = mbd.getScope();
final Scope scope = (Scope) this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, new ObjectFactory() {
public Object getObject() throws BeansException {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; " +
"consider defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}

// Check if required type matches the type of the actual bean instance.
// 检查所需类型是否与实际bean实例的类型匹配
if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return bean;
}
createBean()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170

/**
* Central method of this class: creates a bean instance,
* populates the bean instance, applies post-processors, etc.
* @see #doCreateBean
*/
protected Object createBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
throws BeanCreationException {

AccessControlContext acc = AccessController.getContext();
return AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName + "'");
}
// Make sure bean class is actually resolved at this point.
// 确保 BeanDefinition 中的 Class 被加载
resolveBeanClass(mbd, beanName);

// 准备方法覆写.
// <lookup-method /> 和 <replaced-method />
//
try {
mbd.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbd.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}

try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
// 给 InstantiationAwareBeanPostProcessor 一个机会来返回代理
Object bean = resolveBeforeInstantiation(beanName, mbd);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}
// 创建bean.
Object beanInstance = doCreateBean(beanName, mbd, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
}, acc);
}

/**
* Actually create the specified bean. Pre-creation processing has already happened
* at this point, e.g. checking <code>postProcessBeforeInstantiation</code> callbacks.
* <p>Differentiates between default bean instantiation, use of a
* factory method, and autowiring a constructor.
* @param beanName the name of the bean
* @param mbd the merged bean definition for the bean
* @param args arguments to use if creating a prototype using explicit arguments to a
* static factory method. This parameter must be <code>null</code> except in this case.
* @return a new instance of the bean
* @throws BeanCreationException if the bean could not be created
* @see #instantiateBean
* @see #instantiateUsingFactoryMethod
* @see #autowireConstructor
*/
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
// 实例化bean
BeanWrapper instanceWrapper = null;
// 是单例,先清除缓存
if (mbd.isSingleton()) {
instanceWrapper = (BeanWrapper) this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
//根据指定bean使用对应的策略创建新的实例。例如:工厂方法,构造函数注入,简单的初始化。
// 将BeanDefinition转换为BeanWrapper,大概逻辑如下:
// 1.如果存在工厂方法,则使用工厂方法进行初始化。
// 2.一个类有多个构造函数,每个构造函数都有不同的参数,需要根据参数锁定构造函数并初始化。
// 3.如果不存在工厂,也不存在带参数的构造函数,则使用默认的构造函数进行bean初始化。
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
// bean 实例
final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
// bean 类型
Class beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);

// Allow post-processors to modify the merged bean definition.
// 允许后置处理器修改合并 beanDefinition?有啥用???
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
mbd.postProcessed = true;
}
}

// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
// 循环依赖问题..... 基本不用吧。
// 单例 & 允许循环依赖 & 正在创建中。这个条件先跳过了(在循环依赖问题分析的文章中,分析了)。。。
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
addSingletonFactory(beanName, new ObjectFactory() {
public Object getObject() throws BeansException {
return getEarlyBeanReference(beanName, mbd, bean);
}
});
}

// Initialize the bean instance.
Object exposedObject = bean;
try {
// 属性填充
populateBean(beanName, mbd, instanceWrapper);
// 初始化,下边详解
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
// 还是循环依赖???
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set actualDependentBeans = new LinkedHashSet(dependentBeans.length);
for (int i = 0; i < dependentBeans.length; i++) {
String dependentBean = dependentBeans[i];
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}

// Register bean as disposable.
// Add the given bean to the list of disposable beans in this factory,
// registering its DisposableBean interface and/or the given destroy method
// to be called on factory shutdown (if applicable). Only applies to singletons.
// 将给定的bean添加到此工厂的一次性bean列表中,
// 注册其DisposableBean接口和/或给定的destroy方法
// 在工厂停工时调用(如果适用)。仅适用singleton。
registerDisposableBeanIfNecessary(beanName, bean, mbd);

return exposedObject;
}
initializeBean
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

/**
* Initialize the given bean instance, applying factory callbacks
* as well as init methods and bean post processors.
* <p>Called from {@link #createBean} for traditionally defined beans,
* and from {@link #initializeBean} for existing bean instances.
* @param beanName the bean name in the factory (for debugging purposes)
* @param bean the new bean instance we may need to initialize
* @param mbd the bean definition that the bean was created with
* (can also be <code>null</code>, if given an existing bean instance)
* @return the initialized bean instance (potentially wrapped)
* @see BeanNameAware
* @see BeanClassLoaderAware
* @see BeanFactoryAware
* @see #applyBeanPostProcessorsBeforeInitialization
* @see #invokeInitMethods
* @see #applyBeanPostProcessorsAfterInitialization
*/
protected Object initializeBean(String beanName, Object bean, RootBeanDefinition mbd) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}

if (bean instanceof BeanClassLoaderAware) {
((BeanClassLoaderAware) bean).setBeanClassLoader(getBeanClassLoader());
}

if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(this);
}

Object wrappedBean = bean;
// 调用 beanPostProcessorBefore
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}

try {
// 若实现InitializingBean接口,调用之
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}

if (mbd == null || !mbd.isSynthetic()) {

//
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}

其他特性

ConcurrentHashMap
一、概述
  1. 1. 目录
  2. 2. ioc体系概述
    1. 2.1. BeanFactory 概述
    2. 2.2. ApplicationContext 概述
    3. 2.3. 几个重要的接口(类)
      1. 2.3.1. ListableBeanFactory(interface)
      2. 2.3.2. HierarchicalBeanFactory
      3. 2.3.3. AutowireCapableBeanFactory
      4. 2.3.4. ConfigurableListableBeanFactory
        1. 2.3.4.1. 设置忽略的依赖关系,注册找到的特殊依赖
        2. 2.3.4.2. 获取bean定义 (可以访问属性值跟构造方法的参数值)
        3. 2.3.4.3. 锁定配置信息.在调用refresh时会使用到.
        4. 2.3.4.4. 预加载不是懒加载的单例.用于解决循环依赖问题
  3. 3. ApplicationContext 初始化过程源码阅读
    1. 3.1. 概述
    2. 3.2. 构造器
    3. 3.3. refresh()
      1. 3.3.1. prepareRefresh()
      2. 3.3.2. obtainFreshBeanFactory()
        1. 3.3.2.1. getBeanFactory()
      3. 3.3.3. prepareBeanFactory()
        1. 3.3.3.1. finishBeanFactoryInitialization()
        2. 3.3.3.2. getBean()
          1. 3.3.3.2.1. createBean()
          2. 3.3.3.2.2. initializeBean
    4. 3.4. 其他特性
© 2023 haoxp
Hexo theme