Spring IOC源码分析

UML图

DefaultListableBeanFactory.png
DefaultListableBeanFactory.png

阅读入口

ClassPathXmlApplicationContext

开始阅读

从找到这个构造方法:

1
2
3
4
5
6
7
8
9
10
11
12
public ClassPathXmlApplicationContext(String[] paths, Class<?> clazz, @Nullable ApplicationContext parent)
throws BeansException {

super(parent);
Assert.notNull(paths, "Path array must not be null");
Assert.notNull(clazz, "Class argument must not be null");
this.configResources = new Resource[paths.length];
for (int i = 0; i < paths.length; i++) {
this.configResources[i] = new ClassPathResource(paths[i], clazz);
}
refresh();
}

重点是refresh这个方法,接下来就是看这个:org.springframework.context.support.AbstractApplicationContext#refresh

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
public void refresh() throws BeansException, IllegalStateException {
// 加锁
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
//调用容器准备刷新的方法,获取容器的当时时间,同时给容器设置同步标识,标志已启动标识
prepareRefresh();

// Tell the subclass to refresh the internal bean factory.
//告诉子类启动refreshBeanFactory()方法,Bean定义资源文件的载入从
//子类的refreshBeanFactory()方法启动
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

// Prepare the bean factory for use in this context.
//为BeanFactory配置容器特性,例如类加载器、事件处理器等
prepareBeanFactory(beanFactory);

try {
// Allows post-processing of the bean factory in context subclasses.
//为容器的某些子类指定特殊的BeanPost事件处理器
// 如果实现了BeanFactoryPostProcessor这个接口将会调用postProcessBeanFactory方法
postProcessBeanFactory(beanFactory);

// Invoke factory processors registered as beans in the context.
//调用所有注册的BeanFactoryPostProcessor的Bean
invokeBeanFactoryPostProcessors(beanFactory);

// Register bean processors that intercept bean creation.
//为BeanFactory注册BeanPost事件处理器.
// 注册BeanPostProcessors的实现类,注意这个和BeanFactoryPostProcessor不同
//BeanPostProcessor是Bean后置处理器,用于监听容器触发的事件
registerBeanPostProcessors(beanFactory);

// Initialize message source for this context.
//初始化信息源,和国际化相关.
initMessageSource();

// Initialize event multicaster for this context.
//初始化容器事件传播器.
initApplicationEventMulticaster();

// Initialize other special beans in specific context subclasses.
//调用子类的某些特殊Bean初始化方法
onRefresh();

// Check for listener beans and register them.
//为事件传播器注册事件监听器.
registerListeners();

// Instantiate all remaining (non-lazy-init) singletons.
//初始化所有剩余的单例Bean
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.
//销毁已创建的Bean
destroyBeans();

// Reset 'active' flag.
//取消refresh操作,重置容器的同步标识.
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();
}
}
}
  • 我们一个个来看,首先看的是org.springframework.context.support.AbstractApplicationContext#prepareBeanFactory这个方法。这个方法是bean创建前的方法,主要目的是准备刷新方法,设置激活标识。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    protected void prepareRefresh() {
    // 记录开始时间
    this.startupDate = System.currentTimeMillis();
    // 设置closed和active这两个标识的值
    this.closed.set(false);
    this.active.set(true);

    ...
    // Initialize any placeholder property sources in the context environment
    initPropertySources();
    // 校验XML配置文件
    getEnvironment().validateRequiredProperties();

    this.earlyApplicationEvents = new LinkedHashSet<>();
    }
  • org.springframework.context.support.AbstractApplicationContext#obtainFreshBeanFactory

    1
    2
    3
    4
    5
    6
    7
    protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
    //这里使用了委派设计模式,父类定义了抽象的refreshBeanFactory()方法,具体实现调用子类容器的refreshBeanFactory()方法
    // 关闭旧的BeanFactory,创建新的BeanFactory并返回
    refreshBeanFactory();
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    return beanFactory;
    }

    这里使用到了refreshBeanFactory这个方法,所以再来一下这个方法,找到其实现类:org.springframework.context.support.AbstractRefreshableApplicationContext#refreshBeanFactory

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    protected final void refreshBeanFactory() throws BeansException {
    //如果当前ApplicationContext已经有容器,销毁容器中的bean,关闭容器
    if (hasBeanFactory()) {
    destroyBeans();
    closeBeanFactory();
    }
    try {
    //创建IOC容器:DefaultListableBeanFactory
    DefaultListableBeanFactory beanFactory = createBeanFactory();
    // bean的序列化
    beanFactory.setSerializationId(getId());
    //对IOC容器进行定制化,如设置启动参数,开启注解的自动装配等,设置是否允许bean覆盖、循环引用。
    customizeBeanFactory(beanFactory);
    //调用载入Bean定义的方法,主要这里又使用了一个委派模式,在当前类中只定义了抽象的loadBeanDefinitions方法,具体的实现调用子类容器
    loadBeanDefinitions(beanFactory);
    synchronized (this.beanFactoryMonitor) {
    this.beanFactory = beanFactory;
    }
    }
    catch (IOException ex) {
    throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
    }
    }

    可以看到这里使用的是DefaultListableBeanFactory这个实例来作为bean容器,这个类基本具有了BeanFactory所有子类的特性(从前面的UML图可以得知)。

深入里面看这个方法org.springframework.context.support.AbstractRefreshableApplicationContext#customizeBeanFactory

1
2
3
4
5
6
7
8
protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
if (this.allowBeanDefinitionOverriding != null) {
beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
if (this.allowCircularReferences != null) {
beanFactory.setAllowCircularReferences(this.allowCircularReferences);
}
}

这个方法是:设置bean是否允许覆盖和是否允许循环依赖。

  • 前面refreshBeanFactory方法调用了loadBeanDefinitions,所以我们再来看看这个方法:org.springframework.context.support.AbstractXmlApplicationContext#loadBeanDefinitions(org.springframework.beans.factory.support.DefaultListableBeanFactory)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    @Override
    protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
    //创建XmlBeanDefinitionReader,即创建Bean读取器,并通过回调设置到容器中去,容器使用该读取器读取Bean定义资源
    XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

    // Configure the bean definition reader with this context's
    // resource loading environment.
    //为Bean读取器设置Spring资源加载器,AbstractXmlApplicationContext的
    //祖先父类AbstractApplicationContext继承DefaultResourceLoader,因此,容器本身也是一个资源加载器
    beanDefinitionReader.setEnvironment(this.getEnvironment());
    beanDefinitionReader.setResourceLoader(this);
    //为Bean读取器设置SAX xml解析器
    beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

    // Allow a subclass to provide custom initialization of the reader,
    // then proceed with actually loading the bean definitions.
    //当Bean读取器读取Bean定义的Xml资源文件时,启用Xml的校验机制
    initBeanDefinitionReader(beanDefinitionReader);
    //Bean读取器真正实现加载的方法
    loadBeanDefinitions(beanDefinitionReader);
    }
  • 继续看这个真正实现加载的方法:org.springframework.context.support.AbstractXmlApplicationContext#loadBeanDefinitions(org.springframework.beans.factory.xml.XmlBeanDefinitionReader)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
    //获取Bean定义资源的定位
    Resource[] configResources = getConfigResources();
    if (configResources != null) {
    //Xml Bean读取器调用其父类AbstractBeanDefinitionReader读取定位
    //的Bean定义资源
    reader.loadBeanDefinitions(configResources);
    }
    //如果子类中获取的Bean定义资源定位为空,则获取FileSystemXmlApplicationContext构造方法中setConfigLocations方法设置的资源
    String[] configLocations = getConfigLocations();
    if (configLocations != null) {
    //Xml Bean读取器调用其父类AbstractBeanDefinitionReader读取定位
    //的Bean定义资源
    reader.loadBeanDefinitions(configLocations);
    }
    }

这里有两个分支,第一个调用的org.springframework.beans.factory.support.AbstractBeanDefinitionReader#loadBeanDefinitions(org.springframework.core.io.Resource…)方法,这个方法往下走调用的是loadBeanDefinitions方法,这个方法有多个实现,我们直接看org.springframework.beans.factory.xml.XmlBeanDefinitionReader#loadBeanDefinitions(org.springframework.core.io.Resource)这个。

继续深挖,走到这里org.springframework.beans.factory.xml.XmlBeanDefinitionReader#loadBeanDefinitions(org.springframework.core.io.support.EncodedResource)这个方法主要通过EncodedResource将资源文件转为InputStream的IO流。

继续走,里面调用了org.springframework.beans.factory.xml.XmlBeanDefinitionReader#doLoadBeanDefinitions将XML转换为Document对象。

接着,将document转换为容器的数据结构:org.springframework.beans.factory.xml.XmlBeanDefinitionReader#registerBeanDefinitions

1
2
3
4
5
6
7
8
9
10
11
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
//得到BeanDefinitionDocumentReader来对xml格式的BeanDefinition解析
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
//获得容器中注册的Bean数量
int countBefore = getRegistry().getBeanDefinitionCount();
//解析过程入口,这里使用了委派模式,BeanDefinitionDocumentReader只是个接口,
//具体的解析实现过程有实现类DefaultBeanDefinitionDocumentReader完成
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
//统计解析的Bean数量
return getRegistry().getBeanDefinitionCount() - countBefore;
}

这里registerBeanDefinitions的使用的是org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader#registerBeanDefinitions这个实现。

1
2
3
4
5
6
7
8
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
//获得XML描述符
this.readerContext = readerContext;
logger.debug("Loading bean definitions");
//获得Document的根元素
Element root = doc.getDocumentElement();
doRegisterBeanDefinitions(root);
}

来到org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader#doRegisterBeanDefinitions方法:

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
protected void doRegisterBeanDefinitions(Element root) {
//具体的解析过程由BeanDefinitionParserDelegate实现,
//BeanDefinitionParserDelegate中定义了Spring Bean定义XML文件的各种元素
BeanDefinitionParserDelegate parent = this.delegate;
this.delegate = createDelegate(getReaderContext(), root, parent);

if (this.delegate.isDefaultNamespace(root)) {
String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
if (StringUtils.hasText(profileSpec)) {
String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
if (logger.isInfoEnabled()) {
...
}
return;
}
}
}

//在解析Bean定义之前,进行自定义的解析,增强解析过程的可扩展性
preProcessXml(root);
//从Document的根元素开始进行解析Bean定义的Document对象
parseBeanDefinitions(root, this.delegate);
//在解析Bean定义之后,进行自定义的解析,增加解析过程的可扩展性
postProcessXml(root);

this.delegate = parent;
}

上面方法实例化了一个BeanDefinitionParserDelegate对象,这个类包含了标签的所有属性,在上面代码中,主要关注的是parseBeanDefinitions方法:

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
//使用Spring的Bean规则从Document的根元素开始进行Bean定义的Document对象
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
//Bean定义的Document对象使用了Spring默认的XML命名空间
if (delegate.isDefaultNamespace(root)) {
//获取Bean定义的Document对象根元素的所有子节点
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
//获得Document节点是XML元素节点
if (node instanceof Element) {
Element ele = (Element) node;
//Bean定义的Document的元素节点使用的是Spring默认的XML命名空间
if (delegate.isDefaultNamespace(ele)) {
//使用Spring的Bean规则解析元素节点
parseDefaultElement(ele, delegate);
}
else {
//没有使用Spring默认的XML命名空间,则使用用户自定义的解析规则解析元素节点
delegate.parseCustomElement(ele);
}
}
}
}
else {
//Document的根节点没有使用Spring默认的命名空间,则使用用户自定义的
//解析规则解析Document根节点
delegate.parseCustomElement(root);
}
}

parseDefaultElement解析的是** **、 这几个标签

delegate.parseCustomElement解析的是 标签

来看parseDefaultElement方法里面调用的org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader#processBeanDefinition方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
	//解析Bean定义资源Document对象的普通元素
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
// BeanDefinitionHolder是对BeanDefinition的封装,即Bean定义的封装类
//对Document对象中<Bean>元素的解析由BeanDefinitionParserDelegate实现
// BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
if (bdHolder != null) {
bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
try {
// Register the final decorated instance.
//向Spring IOC容器注册解析得到的Bean定义,这是Bean定义向IOC容器注册的入口
BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
}
catch (BeanDefinitionStoreException ex) {
...
}
// Send registration event.
//在完成向Spring IOC容器注册解析得到的Bean定义之后,发送注册事件
getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
}
}

我们看到这个方法parseBeanDefinitionElement:org.springframework.beans.factory.xml.BeanDefinitionParserDelegate#parseBeanDefinitionElement(org.w3c.dom.Element) 它内部又调用了org.springframework.beans.factory.xml.BeanDefinitionParserDelegate#parseBeanDefinitionElement(org.w3c.dom.Element, org.springframework.beans.factory.config.BeanDefinition):

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
	@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
//获取<Bean>元素中的id属性值
String id = ele.getAttribute(ID_ATTRIBUTE);
//获取<Bean>元素中的name属性值
String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);

//获取<Bean>元素中的alias属性值
List<String> aliases = new ArrayList<>();

//将<Bean>元素中的所有name属性值存放到别名中
if (StringUtils.hasLength(nameAttr)) {
String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
aliases.addAll(Arrays.asList(nameArr));
}

String beanName = id;
//如果<Bean>元素中没有配置id属性时,并且设置了别名,将别名中的第一个值赋值给beanName
if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
beanName = aliases.remove(0);
...
}

//检查<Bean>元素所配置的id或者name的唯一性,containingBean标识<Bean>
//元素中是否包含子<Bean>元素
if (containingBean == null) {
//检查<Bean>元素所配置的id、name或者别名是否重复
checkNameUniqueness(beanName, aliases, ele);
}

//详细对<Bean>元素中配置的Bean定义进行解析的地方
AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
if (beanDefinition != null) {
if (!StringUtils.hasText(beanName)) {
try {
if (containingBean != null) {
//如果<Bean>元素中没有配置id、别名或者name,且没有包含子元素<Bean>元素,为解析的Bean生成一个唯一beanName并注册
beanName = BeanDefinitionReaderUtils.generateBeanName(
beanDefinition, this.readerContext.getRegistry(), true);
}
else {
//如果<Bean>元素中没有配置id、别名或者name,且包含了子元素
//<Bean>元素,为解析的Bean使用别名向IOC容器注册
beanName = this.readerContext.generateBeanName(beanDefinition);
//为解析的Bean使用别名注册时,为了向后兼容
//Spring1.2/2.0,给别名添加类名后缀
String beanClassName = beanDefinition.getBeanClassName();
if (beanClassName != null &&
beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() &&
!this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
aliases.add(beanClassName);
}
}
if (logger.isDebugEnabled()) {
...
}
}
catch (Exception ex) {
error(ex.getMessage(), ele);
return null;
}
}
String[] aliasesArray = StringUtils.toStringArray(aliases);
return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
}
//当解析出错时,返回null
return null;
}

这个方法主要对name,id,别名 进行了解析。同时调用了org.springframework.beans.factory.xml.BeanDefinitionParserDelegate#parseBeanDefinitionElement(org.w3c.dom.Element, java.lang.String, org.springframework.beans.factory.config.BeanDefinition)进行其他属性的解析。所以接着来看parseBeanDefinitionElement方法:

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
public AbstractBeanDefinition parseBeanDefinitionElement(
Element ele, String beanName, @Nullable BeanDefinition containingBean) {
//记录解析的<Bean>
this.parseState.push(new BeanEntry(beanName));

//这里只读取<Bean>元素中配置的class名字,然后载入到BeanDefinition中去
//只是记录配置的class名字,不做实例化,对象的实例化在依赖注入时完成
String className = null;

//如果<Bean>元素中配置了parent属性,则获取parent属性的值
if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
}
String parent = null;
if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
parent = ele.getAttribute(PARENT_ATTRIBUTE);
}

try {
//根据<Bean>元素配置的class名称和parent属性值创建BeanDefinition
//为载入Bean定义信息做准备
AbstractBeanDefinition bd = createBeanDefinition(className, parent);

//对当前的<Bean>元素中配置的一些属性进行解析和设置,如配置的单态(singleton)属性等
parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
//为<Bean>元素解析的Bean设置description信息
bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));

//对<Bean>元素的meta(元信息)属性解析
parseMetaElements(ele, bd);
//对<Bean>元素的lookup-method属性解析
parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
//对<Bean>元素的replaced-method属性解析
parseReplacedMethodSubElements(ele, bd.getMethodOverrides());

//解析<Bean>元素的构造方法设置
parseConstructorArgElements(ele, bd);
//解析<Bean>元素的<property>设置
parsePropertyElements(ele, bd);
//解析<Bean>元素的qualifier属性
parseQualifierElements(ele, bd);

//为当前解析的Bean设置所需的资源和依赖对象
bd.setResource(this.readerContext.getResource());
bd.setSource(extractSource(ele));

return bd;
}
...
finally {
this.parseState.pop();
}

//解析<Bean>元素出错时,返回null
return null;
}

该类该方法中主要处理除这name,id,别名三个以外的其他属性数据。回到org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader#processBeanDefinition方法,来看调用的org.springframework.beans.factory.support.BeanDefinitionReaderUtils#registerBeanDefinition方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//将解析的BeanDefinitionHold注册到容器中
public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {

// Register bean definition under primary name.
//获取解析的BeanDefinition的名称
String beanName = definitionHolder.getBeanName();
//向IOC容器注册BeanDefinition
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());

// Register aliases for bean name, if any.
//如果解析的BeanDefinition有别名,向容器为其注册别名
String[] aliases = definitionHolder.getAliases();
if (aliases != null) {
for (String alias : aliases) {
registry.registerAlias(beanName, alias);
}
}
}

继续走,来到这个方法org.springframework.beans.factory.support.DefaultListableBeanFactory#registerBeanDefinition:

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
public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
throws BeanDefinitionStoreException {

Assert.hasText(beanName, "Bean name must not be empty");
Assert.notNull(beanDefinition, "BeanDefinition must not be null");

//校验解析的BeanDefiniton
if (beanDefinition instanceof AbstractBeanDefinition) {
try {
((AbstractBeanDefinition) beanDefinition).validate();
}
catch (BeanDefinitionValidationException ex) {
...
}

BeanDefinition oldBeanDefinition;

oldBeanDefinition = this.beanDefinitionMap.get(beanName);

if (oldBeanDefinition != null) {
// 处理重复名称bean定义问题
if (!isAllowBeanDefinitionOverriding()) {
// 不允许覆盖,将抛出异常
throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
"Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
"': There is already [" + oldBeanDefinition + "] bound.");
}
else if (oldBeanDefinition.getRole() < beanDefinition.getRole()) {
// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
...
}
else if (!beanDefinition.equals(oldBeanDefinition)) {
...
}
else {
...
}
this.beanDefinitionMap.put(beanName, beanDefinition);
}
else {
// map中没有,则将beanName和beanDefinition存放到map中
if (hasBeanCreationStarted()) {
// Cannot modify startup-time collection elements anymore (for stable iteration)
//注册的过程中需要线程同步,以保证数据的一致性
synchronized (this.beanDefinitionMap) {
this.beanDefinitionMap.put(beanName, beanDefinition);
List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
updatedDefinitions.addAll(this.beanDefinitionNames);
updatedDefinitions.add(beanName);
this.beanDefinitionNames = updatedDefinitions;
if (this.manualSingletonNames.contains(beanName)) {
Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
updatedSingletons.remove(beanName);
this.manualSingletonNames = updatedSingletons;
}
}
}
else {
// Still in startup registration phase
this.beanDefinitionMap.put(beanName, beanDefinition);
this.beanDefinitionNames.add(beanName);
this.manualSingletonNames.remove(beanName);
}
this.frozenBeanDefinitionNames = null;
}

//检查是否有同名的BeanDefinition已经在IOC容器中注册
if (oldBeanDefinition != null || containsSingleton(beanName)) {
//重置所有已经注册过的BeanDefinition的缓存
resetBeanDefinition(beanName);
}
}
  • 回到这里org.springframework.context.support.AbstractApplicationContext#refresh,来看里面使用到的org.springframework.context.support.AbstractApplicationContext#prepareBeanFactory方法,代码就不贴了。主要是做了几项工作:设置类的加载器、自动装配时,忽略指定接口,自动进行注册相关bean。

  • 再看refresh方法使用到的org.springframework.context.support.AbstractApplicationContext#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
    protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
    //这是Spring3以后新加的代码,为容器指定一个转换服务(ConversionService)
    //在对某些Bean属性进行转换时使用
    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));
    }

    if (!beanFactory.hasEmbeddedValueResolver()) {
    beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
    }

    // 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.
    //缓存容器中所有注册的BeanDefinition元数据,以防被修改
    beanFactory.freezeConfiguration();

    // Instantiate all remaining (non-lazy-init) singletons.
    //对配置了lazy-init属性的单态模式Bean进行预实例化处理
    beanFactory.preInstantiateSingletons();
    }
  • 上面方法最后一行调用了org.springframework.beans.factory.support.DefaultListableBeanFactory#preInstantiateSingletons方法,该方法对配置lazy-init属性单态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
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    public void preInstantiateSingletons() throws BeansException {
    ...
    List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

    for (String beanName : beanNames) {
    //获取指定名称的Bean定义
    RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
    //Bean不是抽象的,是单态模式的,且lazy-init属性配置为false
    if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
    //如果指定名称的bean是创建容器的Bean
    if (isFactoryBean(beanName)) {
    //FACTORY_BEAN_PREFIX=”&”,当Bean名称前面加”&”符号
    //时,获取的是产生容器对象本身,而不是容器产生的Bean.
    //调用getBean方法,触发容器对Bean实例化和依赖注入过程
    final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
    //标识是否需要预实例化
    boolean isEagerInit;
    if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
    //一个匿名内部类
    isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>) () ->
    ((SmartFactoryBean<?>) factory).isEagerInit(),
    getAccessControlContext());
    }
    else {
    isEagerInit = (factory instanceof SmartFactoryBean &&
    ((SmartFactoryBean<?>) factory).isEagerInit());
    }
    if (isEagerInit) {
    //调用getBean方法,触发容器对Bean实例化和依赖注入过程
    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((PrivilegedAction<Object>) () -> {
    smartSingleton.afterSingletonsInstantiated();
    return null;
    }, getAccessControlContext());
    }
    else {
    smartSingleton.afterSingletonsInstantiated();
    }
    }
    }
    }
  • 接着看org.springframework.beans.factory.support.AbstractBeanFactory#getBean(java.lang.String)这个方法。它实际调用的org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean这个方法:

    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
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
    @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {

    //根据指定的名称获取被管理Bean的名称,剥离指定名称中对容器的相关依赖
    //如果指定的是别名,将别名转换为规范的Bean名称
    final String beanName = transformedBeanName(name);
    Object bean;

    // Eagerly check singleton cache for manually registered singletons.
    //先从缓存中取是否已经有被创建过的单态类型的Bean
    //对于单例模式的Bean整个IOC容器中只创建一次,不需要重复创建
    Object sharedInstance = getSingleton(beanName);
    //IOC容器创建单例模式Bean实例对象
    if (sharedInstance != null && args == null) {
    if (logger.isDebugEnabled()) {
    //如果指定名称的Bean在容器中已有单例模式的Bean被创建
    //直接返回已经创建的Bean
    if (isSingletonCurrentlyInCreation(beanName)) {
    ...
    }
    else {
    ...
    }
    }
    //获取给定Bean的实例对象,主要是完成FactoryBean的相关处理
    //注意:BeanFactory是管理容器中Bean的工厂,而FactoryBean是
    //创建创建对象的工厂Bean,两者之间有区别
    bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    }

    else {
    //缓存没有正在创建的单例模式Bean
    //缓存中已经有已经创建的原型模式Bean
    //但是由于循环引用的问题导致实例化对象失败
    if (isPrototypeCurrentlyInCreation(beanName)) {
    throw new BeanCurrentlyInCreationException(beanName);
    }

    //对IOC容器中是否存在指定名称的BeanDefinition进行检查,首先检查是否
    //能在当前的BeanFactory中获取的所需要的Bean,如果不能则委托当前容器
    //的父级容器去查找,如果还是找不到则沿着容器的继承体系向父级容器查找
    BeanFactory parentBeanFactory = getParentBeanFactory();
    //当前容器的父级容器存在,且当前容器中不存在指定名称的Bean
    if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
    // Not found -> check parent.
    //解析指定Bean名称的原始名称
    String nameToLookup = originalBeanName(name);
    if (parentBeanFactory instanceof AbstractBeanFactory) {
    return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
    nameToLookup, requiredType, args, typeCheckOnly);
    }
    else if (args != null) {
    // Delegation to parent with explicit args.
    //委派父级容器根据指定名称和显式的参数查找
    return (T) parentBeanFactory.getBean(nameToLookup, args);
    }
    else {
    // No args -> delegate to standard getBean method.
    //委派父级容器根据指定名称和类型查找
    return parentBeanFactory.getBean(nameToLookup, requiredType);
    }
    }

    //创建的Bean是否需要进行类型验证,一般不需要
    if (!typeCheckOnly) {
    //向容器标记指定的Bean已经被创建
    markBeanAsCreated(beanName);
    }

    try {
    //根据指定Bean名称获取其父级的Bean定义
    //主要解决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();
    //如果当前Bean有依赖Bean
    if (dependsOn != null) {
    for (String dep : dependsOn) {
    if (isDependent(beanName, dep)) {
    throw new BeanCreationException(mbd.getResourceDescription(), beanName,
    "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
    }
    //递归调用getBean方法,获取当前Bean的依赖Bean
    registerDependentBean(dep, beanName);
    //把被依赖Bean注册给当前依赖的Bean
    getBean(dep);
    }
    }

    // Create bean instance.
    //创建单例模式Bean的实例对象
    if (mbd.isSingleton()) {
    //这里使用了一个匿名内部类,创建Bean实例对象,并且注册给所依赖的对象
    sharedInstance = getSingleton(beanName, () -> {
    try {
    //创建一个指定Bean实例对象,如果有父级继承,则合并子类和父类的定义
    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.
    //显式地从容器单例模式Bean缓存中清除实例对象
    destroySingleton(beanName);
    throw ex;
    }
    });
    //获取给定Bean的实例对象
    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
    }

    //IOC容器创建原型模式Bean实例对象
    else if (mbd.isPrototype()) {
    // It's a prototype -> create a new instance.
    //原型模式(Prototype)是每次都会创建一个新的对象
    Object prototypeInstance = null;
    try {
    //回调beforePrototypeCreation方法,默认的功能是注册当前创建的原型对象
    beforePrototypeCreation(beanName);
    //创建指定Bean对象实例
    prototypeInstance = createBean(beanName, mbd, args);
    }
    finally {
    //回调afterPrototypeCreation方法,默认的功能告诉IOC容器指定Bean的原型对象不再创建
    afterPrototypeCreation(beanName);
    }
    //获取给定Bean的实例对象
    bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
    }

    //要创建的Bean既不是单例模式,也不是原型模式,则根据Bean定义资源中
    //配置的生命周期范围,选择实例化Bean的合适方法,这种在Web应用程序中
    //比较常用,如:request、session、application等生命周期
    else {
    String scopeName = mbd.getScope();
    final Scope scope = this.scopes.get(scopeName);
    //Bean定义资源中没有配置生命周期范围,则Bean定义不合法
    if (scope == null) {
    throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
    }
    try {
    //这里又使用了一个匿名内部类,获取一个指定生命周期范围的实例
    Object scopedInstance = scope.get(beanName, () -> {
    beforePrototypeCreation(beanName);
    try {
    return createBean(beanName, mbd, args);
    }
    finally {
    afterPrototypeCreation(beanName);
    }
    });
    //获取给定Bean的实例对象
    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);
    }
    }
    }
    catch (BeansException ex) {
    cleanupAfterBeanCreationFailure(beanName);
    throw ex;
    }
    }

    // Check if required type matches the type of the actual bean instance.
    //对创建的Bean实例对象进行类型检查
    if (requiredType != null && !requiredType.isInstance(bean)) {
    try {
    T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
    if (convertedBean == null) {
    throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
    }
    return convertedBean;
    }
    catch (TypeMismatchException ex) {
    if (logger.isDebugEnabled()) {
    ...
    }
    throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
    }
    }
    return (T) bean;
    }
  • org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(java.lang.String, org.springframework.beans.factory.support.RootBeanDefinition, java.lang.Object[])

    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
    protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
    throws BeanCreationException {

    if (logger.isDebugEnabled()) {
    logger.debug("Creating instance of bean '" + beanName + "'");
    }
    RootBeanDefinition mbdToUse = mbd;

    // Make sure bean class is actually resolved at this point, and
    // clone the bean definition in case of a dynamically resolved Class
    // which cannot be stored in the shared merged bean definition.
    //判断需要创建的Bean是否可以实例化,即是否可以通过当前的类加载器加载
    Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
    if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
    mbdToUse = new RootBeanDefinition(mbd);
    mbdToUse.setBeanClass(resolvedClass);
    }

    // Prepare method overrides.
    //校验和准备Bean中的方法覆盖
    try {
    mbdToUse.prepareMethodOverrides();
    }
    catch (BeanDefinitionValidationException ex) {
    ...
    }

    try {
    // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
    //如果Bean配置了初始化前和初始化后的处理器,则试图返回一个需要创建Bean的代理对象
    Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
    if (bean != null) {
    return bean;
    }
    }
    catch (Throwable ex) {
    ...
    }

    try {
    //创建Bean的入口
    Object beanInstance = doCreateBean(beanName, mbdToUse, args);
    if (logger.isDebugEnabled()) {

    }
    return beanInstance;
    }
    ...
    }
  • org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean

    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
    protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
    throws BeanCreationException {

    //封装被创建的Bean对象
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
    instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
    // 说明不是 FactoryBean
    instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    final Object bean = instanceWrapper.getWrappedInstance();
    //获取实例化对象的类型
    Class<?> beanType = instanceWrapper.getWrappedClass();
    if (beanType != NullBean.class) {
    mbd.resolvedTargetType = beanType;
    }

    // Allow post-processors to modify the merged bean definition.
    //调用PostProcessor后置处理器
    synchronized (mbd.postProcessingLock) {
    if (!mbd.postProcessed) {
    try {
    applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
    }
    catch (Throwable ex) {
    throw new BeanCreationException(mbd.getResourceDescription(), beanName,
    "Post-processing of merged bean definition failed", ex);
    }
    mbd.postProcessed = true;
    }
    }

    // Eagerly cache singletons to be able to resolve circular references
    // even when triggered by lifecycle interfaces like BeanFactoryAware.
    //向容器中缓存单例模式的Bean对象,以防循环引用
    boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
    isSingletonCurrentlyInCreation(beanName));
    if (earlySingletonExposure) {
    ...
    }
    //这里是一个匿名内部类,为了防止循环引用,尽早持有对象的引用
    addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
    }

    // Initialize the bean instance.
    //Bean对象的初始化,依赖注入在此触发
    //这个exposedObject在初始化完成之后返回作为依赖注入完成后的Bean
    Object exposedObject = bean;
    try {
    //将Bean实例对象封装,并且Bean定义中配置的属性值赋值给实例对象
    populateBean(beanName, mbd, instanceWrapper);
    //初始化Bean对象,完成各种回调
    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) {
    //获取指定名称的已注册的单例模式Bean对象
    Object earlySingletonReference = getSingleton(beanName, false);
    if (earlySingletonReference != null) {
    //根据名称获取的已注册的Bean和正在实例化的Bean是同一个
    if (exposedObject == bean) {
    //当前实例化的Bean初始化完成
    exposedObject = earlySingletonReference;
    }
    //当前Bean依赖其他Bean,并且当发生循环引用时不允许新创建实例对象
    else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
    String[] dependentBeans = getDependentBeans(beanName);
    Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
    //获取当前Bean所依赖的其他Bean
    for (String dependentBean : dependentBeans) {
    //对依赖Bean进行类型检查
    if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
    actualDependentBeans.add(dependentBean);
    }
    }
    if (!actualDependentBeans.isEmpty()) {
    ...
    }
    }
    }
    }

    // Register bean as disposable.
    //注册完成依赖注入的Bean
    try {
    registerDisposableBeanIfNecessary(beanName, bean, mbd);
    }
    catch (BeanDefinitionValidationException ex) {
    throw new BeanCreationException(
    mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
    }

    return exposedObject;
    }

    接下来对上面使用到几个方法作分析:

  • org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance

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
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
//检查确认Bean是可实例化的
Class<?> beanClass = resolveBeanClass(mbd, beanName);

//使用工厂方法对Bean进行实例化
// 检查类的访问权限
if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
}

Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}

if (mbd.getFactoryMethodName() != null) {
//调用工厂方法实例化
return instantiateUsingFactoryMethod(beanName, mbd, args);
}

//使用容器的自动装配方法进行实例化
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
if (autowireNecessary) {
//配置了自动装配属性,使用容器的自动装配实例化
//容器的自动装配是根据参数类型匹配Bean的构造方法
return autowireConstructor(beanName, mbd, null, null);
}
else {
//使用默认的无参构造方法实例化
return instantiateBean(beanName, mbd);
}
}

//使用Bean的构造方法进行实例化
// 判断是否采用有参构造方法
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null ||
mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
//使用容器的自动装配特性,调用匹配的构造方法实例化
return autowireConstructor(beanName, mbd, ctors, args);
}


//使用默认的无参构造方法实例化
return instantiateBean(beanName, mbd);
}

createBeanInstance创建bean实例:首先判断能否实例化以及检查其访问权限。其次根据不同条件来对bean进行实例化,有工厂方法的则使用工厂实例化,后根据是否配置了自动装配属性来进行自动装配实例化,否则使用无参构造方法实例化。

以无参构造instantiateBean(beanName, mbd)为例,我们可以挖到这里org.springframework.beans.factory.support.SimpleInstantiationStrategy#instantiate(org.springframework.beans.factory.support.RootBeanDefinition, java.lang.String, org.springframework.beans.factory.BeanFactory)

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
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {	//如果Bean定义中没有方法覆盖,则就不需要CGLIB父类类的方法
if (!bd.hasMethodOverrides()) {
Constructor<?> constructorToUse;
synchronized (bd.constructorArgumentLock) {
//获取对象的构造方法或工厂方法
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
//如果没有构造方法且没有工厂方法
if (constructorToUse == null) {
//使用JDK的反射机制,判断要实例化的Bean是否是接口
final Class<?> clazz = bd.getBeanClass();
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
if (System.getSecurityManager() != null) {
//这里是一个匿名内置类,使用反射机制获取Bean的构造方法
constructorToUse = AccessController.doPrivileged(
(PrivilegedExceptionAction<Constructor<?>>) () -> clazz.getDeclaredConstructor());
}
else {
constructorToUse = clazz.getDeclaredConstructor();
}
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
}
catch (Throwable ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
}
}
//使用BeanUtils实例化,通过反射机制调用”构造方法.newInstance(arg)”来进行实例化
return BeanUtils.instantiateClass(constructorToUse);
}
else {
// Must generate CGLIB subclass.
//使用CGLIB来实例化对象
return instantiateWithMethodInjection(bd, beanName, owner);
}
}

注意:这里实例化了对象,但是还没有对属性进行赋值的。

  • 接下来看org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean方法中使用到的org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean

    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
    //将Bean属性设置到生成的实例对象上
    protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
    if (bw == null) {
    if (mbd.hasPropertyValues()) {
    throw new BeanCreationException(
    mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
    }
    else {
    // Skip property population phase for null instance.
    return;
    }
    }

    boolean continueWithPropertyPopulation = true;

    if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
    // 获取所有后置处理器
    for (BeanPostProcessor bp : getBeanPostProcessors()) {
    if (bp instanceof InstantiationAwareBeanPostProcessor) {
    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
    if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
    // 表示不需要后续对属性进行设置,不需要经过BeanPostProcessor处理
    continueWithPropertyPopulation = false;
    break;
    }
    }
    }
    }

    if (!continueWithPropertyPopulation) {
    return;
    }
    //获取容器在解析Bean定义资源时为BeanDefiniton中设置的属性值
    PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

    //对依赖注入处理,首先处理autowiring自动装配的依赖注入
    if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
    mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
    MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

    //根据Bean名称进行autowiring自动装配处理
    if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
    autowireByName(beanName, mbd, bw, newPvs);
    }

    //根据Bean类型进行autowiring自动装配处理
    if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
    autowireByType(beanName, mbd, bw, newPvs);
    }

    pvs = newPvs;
    }

    //对非autowiring的属性进行依赖注入处理

    boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
    boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);

    if (hasInstAwareBpps || needsDepCheck) {
    if (pvs == null) {
    pvs = mbd.getPropertyValues();
    }
    PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
    if (hasInstAwareBpps) {
    for (BeanPostProcessor bp : getBeanPostProcessors()) {
    if (bp instanceof InstantiationAwareBeanPostProcessor) {
    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
    pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
    if (pvs == null) {
    return;
    }
    }
    }
    }
    if (needsDepCheck) {
    checkDependencies(beanName, mbd, filteredPds, pvs);
    }
    }

    if (pvs != null) {
    //对属性进行注入
    applyPropertyValues(beanName, mbd, bw, pvs);
    }
    }

    该方法的作用就是将Bean属性设置到生成的实例对象上

  • 最后看到org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean(java.lang.String, java.lang.Object, org.springframework.beans.factory.support.RootBeanDefinition)这个方法

    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
    //初始容器创建的Bean实例对象,为其添加BeanPostProcessor后置处理器
    protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
    //JDK的安全机制验证权限
    if (System.getSecurityManager() != null) {
    //实现PrivilegedAction接口的匿名内部类
    AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
    invokeAwareMethods(beanName, bean);
    return null;
    }, getAccessControlContext());
    }
    else {
    //为Bean实例对象包装相关属性,如名称,类加载器,所属容器等信息
    invokeAwareMethods(beanName, bean);
    }

    Object wrappedBean = bean;
    //对BeanPostProcessor后置处理器的postProcessBeforeInitialization
    //回调方法的调用,为Bean实例初始化前做一些处理
    if (mbd == null || !mbd.isSynthetic()) {
    wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    }

    //调用Bean实例对象初始化的方法,这个初始化方法是在Spring Bean定义配置
    //文件中通过init-method属性指定的
    try {
    invokeInitMethods(beanName, wrappedBean, mbd);
    }
    catch (Throwable ex) {
    throw new BeanCreationException(
    (mbd != null ? mbd.getResourceDescription() : null),
    beanName, "Invocation of init method failed", ex);
    }
    //对BeanPostProcessor处理器的postProcessAfterInitialization
    //回调方法的调用,为Bean实例初始化之后做一些处理
    if (mbd == null || !mbd.isSynthetic()) {
    wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }

    return wrappedBean;
    }
  • 几个重要的类:BeanDefinitionHolder、BeanDefinition、BeanDefinitionParserDelegate、AbstractBeanDefinition、FactoryBean、BeanFactory