Spring 框架的启动过程是其核心机制之一,主要涉及 IoC 容器的初始化、Bean 的加载和生命周期管理。

以下是 Spring 启动过程的详细步骤

环境准备

项目结构:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId>
<artifactId>springlearn</artifactId>
<version>1.0-SNAPSHOT</version> <dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.25.RELEASE</version>
</dependency>
</dependencies> <properties>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
</project>
package org.example;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Main {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:application.xml");
HelloWorldService helloWorldService = (HelloWorldService) context.getBean("helloWorldService");
System.out.println(helloWorldService.getMessage());
}
}
package org.example;

public interface HelloWorldService {
String getMessage();
}
package org.example;

public class HelloWorldServiceImpl implements HelloWorldService {
@Override
public String getMessage() {
return "hello world";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="helloWorldService" class="org.example.HelloWorldServiceImpl"/>
</beans>

上面就是一个简单的Spring

1. 初始化 ApplicationContext

1.1构造函数调用:

  • 调用 super(parent) 初始化父上下文(若无父上下文则为 null)。
  • 调用 setConfigLocations(configLocations) 设置 XML 配置文件路径。
  • 关键方法:refresh()(核心启动逻辑)。
	public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[] {configLocation}, true, null);
} public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException { // 调用 super(parent) 初始化父上下文(若无父上下文则为 null)。
super(parent);
// 调用 setConfigLocations(configLocations) 设置 XML 配置文件路径。
setConfigLocations(configLocations);
if (refresh) {
// 关键方法:refresh()(核心启动逻辑)
refresh();
}
}

2. 执行 refresh() 方法

refresh() 是 AbstractApplicationContext 的核心方法,定义了 Spring 容器的完整启动流程:

	@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
// 步骤1: 准备上下文
prepareRefresh(); // Tell the subclass to refresh the internal bean factory.
// 步骤2: 创建 BeanFactory 并加载 Bean 定义
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context.
// 步骤3: 配置 BeanFactory(如类加载器、EL解析器等)
prepareBeanFactory(beanFactory); try {
// Allows post-processing of the bean factory in context subclasses.
// 步骤4: 后处理 BeanFactory(子类扩展点)
postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context.
// 步骤5: 调用 BeanFactoryPostProcessor
invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation.
// 步骤6: 注册 BeanPostProcessor
registerBeanPostProcessors(beanFactory); // Initialize message source for this context.
// 步骤7: 初始化消息源(国际化)
initMessageSource(); // Initialize event multicaster for this context.
// 步骤8: 初始化事件广播器
initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses.
// 步骤9: 初始化特定子类的特殊 Bean(空方法,留给子类扩展)
onRefresh(); // Check for listener beans and register them.
// 步骤10: 注册事件监听器
registerListeners(); // Instantiate all remaining (non-lazy-init) singletons.
// 步骤11: 完成 BeanFactory 初始化,实例化所有非懒加载单例 Bean
finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event.
// 步骤12: 完成刷新,发布 ContextRefreshedEvent 事件
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();
}
}
}

2.1 prepareRefresh()

  • 初始化启动时间戳和活跃状态标志。
  • 初始化 Environment(环境变量、系统属性等)。
  • 校验必需的配置属性(通过 Environment)。
	protected void prepareRefresh() {
// Switch to active.
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true); if (logger.isDebugEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
}
else {
logger.debug("Refreshing " + getDisplayName());
}
} // Initialize any placeholder property sources in the context environment.
initPropertySources(); // Validate that all properties marked as required are resolvable:
// see ConfigurablePropertyResolver#setRequiredProperties
getEnvironment().validateRequiredProperties(); // Store pre-refresh ApplicationListeners...
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
}
else {
// Reset local application listeners to pre-refresh state.
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
} // Allow for the collection of early ApplicationEvents,
// to be published once the multicaster is available...
this.earlyApplicationEvents = new LinkedHashSet<>();
}

2.2 obtainFreshBeanFactory()

  • 创建 DefaultListableBeanFactory:Spring 默认的 Bean 工厂。
  • 加载 Bean 定义:通过 XmlBeanDefinitionReader 解析 XML 文件。
  • 解析 标签、context:component-scan 等。
  • 注册 Bean 定义到 BeanFactory 的 beanDefinitionMap。
	protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
} @Override
protected final void refreshBeanFactory() throws BeansException {
// 销毁旧的 BeanFactory, 确保每次刷新都从一个干净的状态开始,避免残留的 Bean 定义或实例干扰。
//检查当前上下文是否已存在 BeanFactory(例如重复调用 refresh() 时)。
if (hasBeanFactory()) {
// 销毁所有已创建的 Bean 实例,清空单例缓存。
destroyBeans();
// 关闭旧的 BeanFactory,释放资源。
closeBeanFactory();
}
try {
// 创建 DefaultListableBeanFactory 实例(Spring 默认的 BeanFactory 实现类)。
DefaultListableBeanFactory beanFactory = createBeanFactory();
// 返回当前 ApplicationContext 的唯一 ID(通常通过 setId() 方法设置,默认自动生成)。
// 为 BeanFactory 设置唯一标识符(ID),用于序列化和反序列化场景(如分布式环境)。
beanFactory.setSerializationId(getId());
// 定制 BeanFactory
customizeBeanFactory(beanFactory);
// 加载 Bean 定义
loadBeanDefinitions(beanFactory);
// 绑定新的 BeanFactory
this.beanFactory = beanFactory;
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}

2.2.1 createBeanFactory

	protected DefaultListableBeanFactory createBeanFactory() {
// 继承父上下文的 BeanFactory(若有),支持层次化容器。
return new DefaultListableBeanFactory(getInternalParentBeanFactory());
}

先来看下DefaultListableBeanFactory

  • DefaultListableBeanFactory 是 Spring 最核心的 Bean 工厂,负责管理 Bean 定义和实例。

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable

2.2.2 customizeBeanFactory

允许子类对 BeanFactory 进行扩展配置

	protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
// 设置是否允许 Bean 定义覆盖:
if (this.allowBeanDefinitionOverriding != null) {
beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
// 设置是否允许循环依赖:
if (this.allowCircularReferences != null) {
beanFactory.setAllowCircularReferences(this.allowCircularReferences);
}
}

2.2.3 loadBeanDefinitions

将 XML 配置(或其他配置源)解析为 BeanDefinition,并注册到 BeanFactory

实现细节(以 ClassPathXmlApplicationContext 为例):

  • 调用 XmlBeanDefinitionReader.loadBeanDefinitions() 解析 XML 文件。
  • 解析 标签、context:component-scan、 等配置。
  • 注册 BeanDefinition 到 beanFactory 的 beanDefinitionMap。
	protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory); // Configure the bean definition reader with this context's
// resource loading environment.
beanDefinitionReader.setEnvironment(this.getEnvironment());
beanDefinitionReader.setResourceLoader(this);
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this)); // Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
initBeanDefinitionReader(beanDefinitionReader);
loadBeanDefinitions(beanDefinitionReader);
}

这一块代码主要任务是解析XML配置文件 转为 BeanDefinition,过程较为复杂,学有余力的朋友可以细看

	protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
Resource[] configResources = getConfigResources();
if (configResources != null) {
reader.loadBeanDefinitions(configResources);
}
// 走这里
String[] configLocations = getConfigLocations();
if (configLocations != null) {
reader.loadBeanDefinitions(configLocations);
}
}
@Override
public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
Assert.notNull(locations, "Location array must not be null");
int count = 0;
// 项目中可能有多个xml配置文件
for (String location : locations) {
count += loadBeanDefinitions(location);
}
return count;
} @Override
public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
return loadBeanDefinitions(location, null);
} public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
// Spring 资源加载器接口,用于根据路径(如类路径、文件系统、URL)获取 Resource 对象。
ResourceLoader resourceLoader = getResourceLoader();
if (resourceLoader == null) {
throw new BeanDefinitionStoreException(
"Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
}
// 处理资源模式匹配(支持通配符) ResourceLoader 的子接口,支持通配符(如 classpath*: 或 Ant 风格路径 **/*.xml)
if (resourceLoader instanceof ResourcePatternResolver) {
// Resource pattern matching available.
try {
// 解析路径为多个资源文件(如 `classpath*:com/example/**/*.xml`)
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
// 加载所有资源的 Bean 定义
int count = loadBeanDefinitions(resources); // 记录实际加载的资源(如果参数 actualResources 不为空)
if (actualResources != null) {
Collections.addAll(actualResources, resources);
}
// 日志记录(仅当 Trace 级别启用时)
if (logger.isTraceEnabled()) {
logger.trace("Loaded " + count + " bean definitions from location pattern [" + location + "]");
}
return count;
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"Could not resolve bean definition resource pattern [" + location + "]", ex);
}
}
//处理单一资源(不支持通配符)
else {
// Can only load single resources by absolute URL.
// 直接加载单个资源(如 classpath:beans.xml 或 file:/config/app.xml)
Resource resource = resourceLoader.getResource(location);
// 记录实际加载的资源
int count = loadBeanDefinitions(resource);
if (actualResources != null) {
actualResources.add(resource);
}
// 日志记录
if (logger.isTraceEnabled()) {
logger.trace("Loaded " + count + " bean definitions from location [" + location + "]");
}
return count;
}
}

接下来看 org.springframework.beans.factory.xml.XmlBeanDefinitionReader#loadBeanDefinitions(org.springframework.core.io.Resource)

  • 循环加载防御:通过 ThreadLocal 确保资源加载的线程安全。
  • 编码与流管理:支持指定编码读取资源,避免乱码问题。
  • 异常与资源清理:确保资源流关闭和状态清理。
  • 委托解析:最终通过 doLoadBeanDefinitions 完成 XML 到 Bean 定义的转换。
	@Override
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
return loadBeanDefinitions(new EncodedResource(resource));
} public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
Assert.notNull(encodedResource, "EncodedResource must not be null");
if (logger.isTraceEnabled()) {
logger.trace("Loading XML bean definitions from " + encodedResource);
}
// 一个 ThreadLocal<Set<EncodedResource>>,记录当前线程正在加载的资源,用于检测循环加载。
Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
if (!currentResources.add(encodedResource)) {
// 循环加载场景:例如,XML 配置文件中通过 <import> 标签间接或直接引用了自身,导致无限递归。
throw new BeanDefinitionStoreException(
"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
} // 通过 encodedResource.getResource().getInputStream() 获取资源输入流
// 使用 try-with-resources 语法确保流自动关闭。
try (InputStream inputStream = encodedResource.getResource().getInputStream()) {
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
// 实际解析 XML 并注册 Bean 定义的方法
return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"IOException parsing XML document from " + encodedResource.getResource(), ex);
}
finally {
// 资源清理
currentResources.remove(encodedResource);
if (currentResources.isEmpty()) {
this.resourcesCurrentlyBeingLoaded.remove();
}
}
}

接下来继续往下看 org.springframework.beans.factory.xml.XmlBeanDefinitionReader#doLoadBeanDefinitions 方法

	protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException { try {
// 加载 XML 为 Document 对象
Document doc = doLoadDocument(inputSource, resource);
// 注册 BeanDefinitions
int count = registerBeanDefinitions(doc, resource);
if (logger.isDebugEnabled()) {
logger.debug("Loaded " + count + " bean definitions from " + resource);
}
return count;
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
...

接下来是org.springframework.beans.factory.xml.XmlBeanDefinitionReader#registerBeanDefinitions

	public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
// 记录当前已注册的 Bean 数量
// getRegistry():返回 BeanDefinitionRegistry(通常是 DefaultListableBeanFactory),负责管理 Bean 定义的注册。
// getBeanDefinitionCount():获取当前容器中已注册的 Bean 定义总数(用于计算本次新增数量)。
int countBefore = getRegistry().getBeanDefinitionCount();
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
// 计算并返回新增的 Bean 定义数量
return getRegistry().getBeanDefinitionCount() - countBefore;
} public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
this.readerContext = readerContext;
doRegisterBeanDefinitions(doc.getDocumentElement());
}

此方法用于解析 XML 配置中的根元素 ,处理 Profile 激活条件 和 嵌套 的递归解析,并将 BeanDefinition注册到 Spring 容器中。核心逻辑包括:

  • 委托链管理:处理嵌套 的默认属性继承。
  • Profile 过滤:根据环境配置决定是否加载当前 XML 块。
  • 解析扩展点:提供 XML 解析前后的扩展钩子。
  • 标签解析:解析 、 等标签生成 Bean 定义。
	protected void doRegisterBeanDefinitions(Element root) {
// Any nested <beans> elements will cause recursion in this method. In
// order to propagate and preserve <beans> default-* attributes correctly,
// keep track of the current (parent) delegate, which may be null. Create
// the new (child) delegate with a reference to the parent for fallback purposes,
// then ultimately reset this.delegate back to its original (parent) reference.
// this behavior emulates a stack of delegates without actually necessitating one.
// 委托链管理(处理嵌套 <beans>)
BeanDefinitionParserDelegate parent = this.delegate;
this.delegate = createDelegate(getReaderContext(), root, parent);
// Profile 过滤(条件加载配置) 检查 <beans profile="..."> 中的 Profile 是否与当前环境匹配,若不匹配则跳过该配置块的解析。
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);
// We cannot use Profiles.of(...) since profile expressions are not supported
// in XML config. See SPR-12458 for details.
if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
if (logger.isDebugEnabled()) {
logger.debug("Skipped XML bean definition file due to specified profiles [" + profileSpec +
"] not matching: " + getReaderContext().getResource());
}
return;
}
}
} // 解析扩展点(钩子方法)
preProcessXml(root); // 解析前扩展点 空方法,子类可覆盖以在解析前修改 DOM 或校验 用于扩展。
parseBeanDefinitions(root, this.delegate); // 核心解析逻辑
postProcessXml(root); // 解析后扩展点 空方法,子类可覆盖以在解析后执行清理或统计 用于扩展。 this.delegate = parent;
}

先来看下委托链管理

BeanDefinitionParserDelegate parent = this.delegate;
this.delegate = createDelegate(getReaderContext(), root, parent);

问题背景:

XML 允许嵌套 标签,每层可定义不同的默认属性(如 default-lazy-init="true"),子层需继承父层的默认值

解决方案:

  • 保存当前委托(parent)作为父级上下文。
  • 创建新的子委托(this.delegate)并关联父级,形成链式结构。

例如:

<!-- 外层定义默认懒加载 -->
<beans default-lazy-init="true">
<bean id="serviceA" class="com.example.ServiceA"/> <!-- 内层覆盖为不懒加载 -->
<beans default-lazy-init="false">
<bean id="serviceB" class="com.example.ServiceB"/>
</beans>
</beans>
  • 解析外层时,delegate 设置 default-lazy-init="true"。
  • 解析内层时,新 delegate 覆盖为 default-lazy-init="false",解析完成后恢复父级委托。

继续看org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader#parseBeanDefinitions

	/**
* Parse the elements at the root level in the document:
* "import", "alias", "bean".
* @param root the DOM root element of the document
*/
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
// 处理根元素下的子节点
if (delegate.isDefaultNamespace(root)) {
NodeList nl = root.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (node instanceof Element) {
// 子元素属于默认命名空间 → 调用 parseDefaultElement()
Element ele = (Element) node;
if (delegate.isDefaultNamespace(ele)) {
parseDefaultElement(ele, delegate);
}
// 子元素属于自定义命名空间 → 调用 delegate.parseCustomElement()
else {
delegate.parseCustomElement(ele);
}
}
}
}
// 根元素不属于默认命名空间 → 直接按自定义元素解析整个根元素
else {
delegate.parseCustomElement(root);
}
} private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
importBeanDefinitionResource(ele);
}
else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
processAliasRegistration(ele);
}
else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
processBeanDefinition(ele, delegate);
}
else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
// recurse
doRegisterBeanDefinitions(ele);
}
}

默认命名空间与自定义命名空间的分离

parseDefaultElement():

处理默认命名空间的 4 种核心标签:

<bean>:解析 Bean 定义。

<import>:导入其他 XML 配置文件。

<alias>:定义 Bean 的别名。

<beans>:递归解析嵌套的配置块。

delegate.parseCustomElement():

通过 NamespaceHandler 解析自定义标签,支持 Spring 的模块化扩展(如 AOP、事务、Context 模块)。

自定义命名空间实现与其他框架(如 MyBatis、Dubbo)的集成。

挑其中的<bean>来解析

	/**
* Process the given bean element, parsing the bean definition
* and registering it with the registry.
*/
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
// 解析 XML 元素生成 BeanDefinition
BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
if (bdHolder != null) {
// 根据 XML 元素中的 自定义属性或子元素,对 Bean 定义进行装饰或增强
// 占位符替换:解析 ${...} 占位符(需配合 PropertySourcesPlaceholderConfigurer)
// AOP 代理包装:处理 <aop:config> 标签,生成代理对象的 Bean 定义。
// 自定义命名空间处理:如 <tx:annotation-driven> 对事务管理的增强。
bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
try {
// Register the final decorated instance.
// 注册 BeanDefinition 到容器
BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error("Failed to register bean definition with name '" +
bdHolder.getBeanName() + "'", ele, ex);
}
// Send registration event.
// 触发组件注册事件
// 监控:跟踪 Bean 的注册过程。
// 扩展处理:某些模块(如 Spring Boot Actuator)可能监听此事件进行健康检查或指标收集。
getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
}
}

org.springframework.beans.factory.xml.BeanDefinitionParserDelegate#parseBeanDefinitionElement(org.w3c.dom.Element)

		/**
* Parses the supplied {@code <bean>} element. May return {@code null}
* if there were errors during parse. Errors are reported to the
* {@link org.springframework.beans.factory.parsing.ProblemReporter}.
*/
@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) {
return parseBeanDefinitionElement(ele, null);
} /**
* Parses the supplied {@code <bean>} element. May return {@code null}
* if there were errors during parse. Errors are reported to the
* {@link org.springframework.beans.factory.parsing.ProblemReporter}.
*/
@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
String id = ele.getAttribute(ID_ATTRIBUTE); // 获取 id 属性
String nameAttr = ele.getAttribute(NAME_ATTRIBUTE); // 获取 name 属性
// id 与 name 的区别:
// id 是 Bean 的唯一标识符,必须唯一。
// name 可为 Bean 定义多个别名(多个别名用逗号/分号分隔)。
// <bean id="userService" name="service,userCore" class="..."/>
// id="userService",别名列表为 ["service", "userCore"]。 List<String> aliases = new ArrayList<>();
if (StringUtils.hasLength(nameAttr)) {
// 将 name 按逗号/分号分割为别名列表
String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
aliases.addAll(Arrays.asList(nameArr));
} String beanName = id;
// 若未指定 id 但 name 存在 → 取第一个 name 作为 beanName,其余作为别名
if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
beanName = aliases.remove(0);
if (logger.isTraceEnabled()) {
// 日志:使用第一个 name 作为 beanName
logger.trace("No XML 'id' specified - using '" + beanName +
"' as bean name and " + aliases + " as aliases");
}
} // 唯一性校验
// 若当前 <bean> 是嵌套在另一个 Bean 内部的(如 <property> 中的内联 Bean),则无需全局唯一性检查。
if (containingBean == null) {
// 确保 beanName 和所有 aliases 在容器中未被注册过
checkNameUniqueness(beanName, aliases, ele);
} // 解析 <bean> 标签的详细属性(如 class、scope、lazy-init)及子元素(如 <property>、<constructor-arg>),生成 GenericBeanDefinition 或 RootBeanDefinition。
AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
if (beanDefinition != null) {
if (!StringUtils.hasText(beanName)) {
try {
if (containingBean != null) {
// 内部 Bean → 基于包含 Bean 生成名称
// 内部 Bean(如内联在 <property> 中的 Bean):名称格式为 父Bean名称#编号(如 userService#0)
beanName = BeanDefinitionReaderUtils.generateBeanName(
beanDefinition, this.readerContext.getRegistry(), true);
}
else {
// 独立 Bean → 由 ReaderContext 生成名称
// 默认使用类名 + 哈希后缀(如 com.example.UserService#a1b2c3)
beanName = this.readerContext.generateBeanName(beanDefinition);
// Register an alias for the plain bean class name, if still possible,
// if the generator returned the class name plus a suffix.
// This is expected for Spring 1.2/2.0 backwards compatibility.
// 兼容旧版本:尝试将类名作为别名
String beanClassName = beanDefinition.getBeanClassName();
if (beanClassName != null &&
beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() &&
!this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
aliases.add(beanClassName);
}
}
if (logger.isTraceEnabled()) {
logger.trace("Neither XML 'id' nor 'name' specified - " +
"using generated bean name [" + beanName + "]");
}
}
catch (Exception ex) {
error(ex.getMessage(), ele);
return null;
}
}
String[] aliasesArray = StringUtils.toStringArray(aliases);
// 封装 Bean 定义、名称和别名,便于后续注册到容器。
return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
} return null;
}

此方法用于解析 XML 中的 <bean> 元素,生成 Bean 定义(AbstractBeanDefinition)及其 元信息(名称、别名),最终封装为 BeanDefinitionHolder 对象。核心逻辑包括:

  • 解析 Bean 名称和别名:处理 id 和 name 属性。

  • 唯一性校验:确保 Bean 名称和别名未被重复注册。

  • 生成 Bean 定义:解析 <bean> 标签的属性和子元素。

  • 自动生成 Bean 名称:当未指定 id 和 name 时生成唯一名称。

  • 别名处理:兼容旧版本逻辑,将类名作为别名(特定条件下)。

走完这个方法,就通过解析 <bean> new 出了相应的BeanDefinitionHolder

org.springframework.beans.factory.support.BeanDefinitionReaderUtils#registerBeanDefinition

	/**
* Register the given bean definition with the given bean factory.
* @param definitionHolder the bean definition including name and aliases
* @param registry the bean factory to register with
* @throws BeanDefinitionStoreException if registration failed
*/
public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException { // Register bean definition under primary name.
// 将 Bean 名称与定义注册到容器。
String beanName = definitionHolder.getBeanName();
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition()); // Register aliases for bean name, if any.
// 遍历别名列表,将每个别名关联到主名称
String[] aliases = definitionHolder.getAliases();
if (aliases != null) {
for (String alias : aliases) {
registry.registerAlias(beanName, alias);
}
}
}

org.springframework.beans.factory.support.DefaultListableBeanFactory#registerBeanDefinition

这是 Spring 容器中注册 BeanDefinition的核心方法,负责将 BeanDefinition 存入容器,并处理 名称冲突、线程安全、缓存清理 等复杂场景。其核心逻辑可概括为:

  • 参数校验:确保 Bean 名称和定义合法。
  • Bean 定义验证:检查配置完整性。
  • 覆盖处理:根据策略处理同名 Bean 的覆盖。
  • 新增处理:分阶段(启动前/后)安全地添加新 Bean。
  • 状态清理:重置相关缓存,保证后续操作正确性。
	@Override
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"); // Bean 定义验证
if (beanDefinition instanceof AbstractBeanDefinition) {
try {
((AbstractBeanDefinition) beanDefinition).validate();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
"Validation of bean definition failed", ex);
}
} BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
if (existingDefinition != null) {
// 不允许覆盖 → 抛出异常
if (!isAllowBeanDefinitionOverriding()) {
throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
}
// 角色优先级检查(框架定义覆盖用户定义)
else if (existingDefinition.getRole() < beanDefinition.getRole()) {
// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
if (logger.isInfoEnabled()) {
logger.info("Overriding user-defined bean definition for bean '" + beanName +
"' with a framework-generated bean definition: replacing [" +
existingDefinition + "] with [" + beanDefinition + "]");
}
}
// 不同定义 → 调试日志
else if (!beanDefinition.equals(existingDefinition)) {
if (logger.isDebugEnabled()) {
logger.debug("Overriding bean definition for bean '" + beanName +
"' with a different definition: replacing [" + existingDefinition +
"] with [" + beanDefinition + "]");
}
}
// 等效定义 → 跟踪日志
else {
if (logger.isTraceEnabled()) {
logger.trace("Overriding bean definition for bean '" + beanName +
"' with an equivalent definition: replacing [" + existingDefinition +
"] with [" + beanDefinition + "]");
}
}
// 更新 Map
this.beanDefinitionMap.put(beanName, beanDefinition);
}
else {
if (hasBeanCreationStarted()) {
// Cannot modify startup-time collection elements anymore (for stable iteration)
// 启动后注册 → 同步保证线程安全
synchronized (this.beanDefinitionMap) {
// 运行时动态注册:通过同步块和拷贝列表保证线程安全。
this.beanDefinitionMap.put(beanName, beanDefinition);
// 更新 beanDefinitionNames 列表(拷贝-修改-替换)
List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
updatedDefinitions.addAll(this.beanDefinitionNames);
updatedDefinitions.add(beanName);
this.beanDefinitionNames = updatedDefinitions;
// 手动单例清理:removeManualSingletonName() 确保单例实例重新创建(若存在)。
removeManualSingletonName(beanName);
}
}
else {
// Still in startup registration phase
// 启动前注册 → 直接操作
// 启动阶段(hasBeanCreationStarted() 为 false):直接操作列表,无并发问题。 // 将 BeanDefinition 放到这个 map 中,这个 map 保存了所有的 BeanDefinition
this.beanDefinitionMap.put(beanName, beanDefinition);
// 这是个 ArrayList,所以会按照 bean 配置的顺序保存每一个注册的 Bean 的名字
this.beanDefinitionNames.add(beanName);
removeManualSingletonName(beanName);
}
this.frozenBeanDefinitionNames = null; // 解冻缓存
} if (existingDefinition != null || containsSingleton(beanName)) {
// 若 Bean 已实例化或存在旧定义,清除其合并定义缓存。
resetBeanDefinition(beanName);
}
else if (isConfigurationFrozen()) {
// 配置冻结后,清除按类型查找的缓存(如 getBeansOfType 结果)。
clearByTypeCache();
}
}

执行完上面方法,注册了各个 BeanDefinition 到注册中心,并且发送了注册事件。

2.3 prepareBeanFactory

	/**
* 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) {
// Tell the internal bean factory to use the context's class loader etc.
// 类加载器:确保BeanFactory使用与应用上下文相同的类加载器。
beanFactory.setBeanClassLoader(getClassLoader());
// 表达式解析器:支持SpEL(Spring Expression Language)表达式解析(如#{...})
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
// 属性编辑器:注册资源相关的属性编辑器(如将字符串路径转换为Resource对象)
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment())); // Configure the bean factory with context callbacks.
// 后置处理器:ApplicationContextAwareProcessor负责向实现了Aware接口
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
// 防止Spring通过自动装配机制注入这些Aware接口的依赖,改为由后置处理器显式处理。
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class); // BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
// 当Bean需要注入BeanFactory、ResourceLoader等接口时,直接返回当前上下文或BeanFactory实例,无需查找。
beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
beanFactory.registerResolvableDependency(ResourceLoader.class, this);
beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
beanFactory.registerResolvableDependency(ApplicationContext.class, this); // Register early post-processor for detecting inner beans as ApplicationListeners.
// 检测实现了ApplicationListener接口的Bean,并自动将其注册为应用事件监听器,确保它们能接收事件通知。
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); // Detect a LoadTimeWeaver and prepare for weaving, if found.
if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
// LTW处理:如果启用了加载时织入(如AspectJ的LTW),添加后置处理器将LoadTimeWeaver实例注入到实现了LoadTimeWeaverAware的Bean中。
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// Set a temporary ClassLoader for type matching.
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
} // Register default environment beans.
// 将Environment、系统属性、系统环境变量注册为单例Bean,方便通过名称或类型注入
if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
}
if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
}
if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
}
}

主要目的是为应用上下文准备标准的Bean工厂环境

2.4 postProcessBeanFactory

	/**
* Modify the application context's internal bean factory after its standard
* initialization. All bean definitions will have been loaded, but no beans
* will have been instantiated yet. This allows for registering special
* BeanPostProcessors etc in certain ApplicationContext implementations.
* @param beanFactory the bean factory used by the application context
*/
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}

允许子类定制BeanFactory

子类可以覆盖此方法,在BeanFactory初始化完成后(但尚未创建任何Bean实例时)进行以下操作:

  • 注册特殊的BeanPostProcessor

    例如:添加自定义的后置处理器,影响Bean的创建过程。

  • 修改Bean定义(BeanDefinition)

    例如:动态调整某些Bean的属性或作用域。

  • 添加环境特定的配置

    例如:在Web应用中注册与Servlet相关的Scope(如RequestScope、SessionScope)。

2.5 invokeBeanFactoryPostProcessors

	/**
* Instantiate and invoke all registered BeanFactoryPostProcessor beans,
* respecting explicit order if given.
* <p>Must be called before singleton instantiation.
*/
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
// 触发所有BeanFactoryPostProcessor,完成对BeanDefinition的最终调整
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors()); // Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
// 添加后置处理器
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
// 设置临时类加载器
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}

PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors

	public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) { // Invoke BeanDefinitionRegistryPostProcessors first, if any.
Set<String> processedBeans = new HashSet<>(); if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>(); for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
// 调用postProcessBeanDefinitionRegistry()
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
} // Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// Separate between BeanDefinitionRegistryPostProcessors that implement
// PriorityOrdered, Ordered, and the rest.
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>(); // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.\ // 按优先级处理自动检测的BeanDefinitionRegistryPostProcessor // PriorityOrdered优先
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear(); // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered. // Ordered次之
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear(); // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
// 剩余处理器循环处理:
boolean reiterate = true;
while (reiterate) {
reiterate = false;
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
} // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
// 调用所有处理器的postProcessBeanFactory()
// 所有BeanDefinitionRegistryPostProcessor和手动注册的普通BeanFactoryPostProcessor的postProcessBeanFactory()方法在此统一调用。
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
} else {
// Invoke factory processors registered with the context instance.
// 若beanFactory不是BeanDefinitionRegistry,直接调用手动注册的普通处理器:
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
} // Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false); // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) {
// skip - already processed in first phase above
// 已处理(如BeanDefinitionRegistryPostProcessor)
}
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
} // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory); // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory); // Finally, invoke all other BeanFactoryPostProcessors.
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory); // Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values...
// 后置处理器可能修改了Bean定义(如占位符解析),需清除缓存以确保后续操作使用最新元数据。
beanFactory.clearMetadataCache();
}

2.6 registerBeanPostProcessors

该方法负责注册所有 BeanPostProcessor 到 BeanFactory,确保它们在后续 Bean 的实例化、初始化过程中生效

核心目标包括:

  • 按优先级排序:确保 PriorityOrdered > Ordered > 无顺序的处理器依次注册。
  • 处理内部专用处理器:如 MergedBeanDefinitionPostProcessor。
  • 支持监听器自动检测:通过 ApplicationListenerDetector 识别实现了 ApplicationListener 的 Bean。
	/**
* Instantiate and register all BeanPostProcessor beans,
* respecting explicit order if given.
* <p>Must be called before any instantiation of application beans.
*/
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
} public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) { String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false); // Register BeanPostProcessorChecker that logs an info message when
// a bean is created during BeanPostProcessor instantiation, i.e. when
// a bean is not eligible for getting processed by all BeanPostProcessors.
// 添加BeanPostProcessorChecker 监控 BeanPostProcessor 初始化期间意外创建的 Bean。
// 如果某个 Bean 在此时被创建(如通过 @Bean 方法),它可能无法被所有 BeanPostProcessor 处理。
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount)); // Separate between BeanPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// 处理PriorityOrdered
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp); // 标记为内部处理器
}
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
} // First, register the BeanPostProcessors that implement PriorityOrdered.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); // Next, register the BeanPostProcessors that implement Ordered.
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String ppName : orderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
orderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
sortPostProcessors(orderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, orderedPostProcessors); // Now, register all regular BeanPostProcessors.
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String ppName : nonOrderedPostProcessorNames) {
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
nonOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors); // Finally, re-register all internal BeanPostProcessors.
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors); // Re-register post-processor for detecting inner beans as ApplicationListeners,
// moving it to the end of the processor chain (for picking up proxies etc).
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

看起来代码跟invokeBeanFactoryPostProcessors 有点相似,但它们的作用对象、执行时机和目的完全不同。

区别:

  1. 作用对象不同
  • invokeBeanFactoryPostProcessors的对象是BeanFactoryPostProcessor用于修改或增强 BeanDefinition
  • registerBeanPostProcessors的对像是BeanPostProcessor用于修改或增强 Bean 的实例
  1. 执行时机不同
  • invokeBeanFactoryPostProcessors 在所有 Bean 的定义(BeanDefinition)加载完成后、任何 Bean 实例化之前。立即执行 BeanFactoryPostProcessor 的逻辑,直接修改 Bean 工厂的元数据。
  • registerBeanPostProcessors 在 BeanFactoryPostProcessor 执行完毕后,但在 Bean 实例化之前。
  • 仅将 BeanPostProcessor 注册到 Bean 工厂中,暂不执行。它们的逻辑会在后续 Bean 的实例化过程中被调用。
  1. 实际用途
  • BeanFactoryPostProcessor

    • 解析 @Configuration 类,注册 @Bean 方法定义的 Bean(ConfigurationClassPostProcessor)。
    • 替换属性占位符(PropertySourcesPlaceholderConfigurer)。
    • 动态添加或修改 Bean 定义(如基于条件注册 Bean)。
  • BeanPostProcessor

    • 依赖注入(如 @Autowired 处理,由 AutowiredAnnotationBeanPostProcessor 实现)。
    • AOP 代理生成(如 AnnotationAwareAspectJAutoProxyCreator)。
    • 初始化回调(如 @PostConstruct 处理,由 CommonAnnotationBeanPostProcessor 实现)。

2.7 initMessageSource

这段代码是 Spring 框架中用于初始化 消息源(MessageSource) 的核心逻辑,主要目的是为应用上下文提供国际化(i18n)支持和消息解析能力。

	/**
* Initialize the MessageSource.
* Use parent's if none defined in this context.
*/
protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// Make MessageSource aware of parent MessageSource.
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
if (hms.getParentMessageSource() == null) {
// Only set parent context as parent MessageSource if no parent MessageSource
// registered already.
hms.setParentMessageSource(getInternalParentMessageSource());
}
}
if (logger.isTraceEnabled()) {
logger.trace("Using MessageSource [" + this.messageSource + "]");
}
}
else {
// Use empty MessageSource to be able to accept getMessage calls.
DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(getInternalParentMessageSource());
this.messageSource = dms;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
if (logger.isTraceEnabled()) {
logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
}
}
}

2.8 initApplicationEventMulticaster

初始化事件广播器

  • 负责将应用事件(ApplicationEvent)广播给所有注册的事件监听器(ApplicationListener),例如容器启动、Bean初始化等事件的传播。
  • 如果用户显式定义了名为applicationEventMulticaster的Bean(需实现ApplicationEventMulticaster接口),Spring会优先使用它。
  • 如果未定义,Spring会默认创建一个SimpleApplicationEventMulticaster实例。
	/**
* Initialize the ApplicationEventMulticaster.
* Uses SimpleApplicationEventMulticaster if none defined in the context.
* @see org.springframework.context.event.SimpleApplicationEventMulticaster
*/
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster =
beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
if (logger.isTraceEnabled()) {
logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
}
}
else {
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
if (logger.isTraceEnabled()) {
logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
}
}
}

2.9 onRefresh

模板方法,在Spring框架中,重写onRefresh()方法主要用于在容器刷新的特定阶段(Bean定义加载完成后、单例Bean实例化前)插入自定义逻辑。

例如:

  • 启动嵌入式服务器(如Tomcat)
  • 初始化全局资源(如连接池、配置中心)
	/**
* Template method which can be overridden to add context-specific refresh work.
* Called on initialization of special beans, before instantiation of singletons.
* <p>This implementation is empty.
* @throws BeansException in case of errors
* @see #refresh()
*/
protected void onRefresh() throws BeansException {
// For subclasses: do nothing by default.
}

2.10 registerListeners

注册事件监听器

可以用于:

  1. 注册静态监听器
  • 添加通过编程方式手动注册的监听器(非 Spring Bean 形式)。
  1. 注册 Bean 监听器
  • 自动扫描容器中所有实现 ApplicationListener 接口的 Bean,并注册到多播器。
  1. 处理早期事件
  • 发布在事件多播器初始化之前被触发的积压事件(earlyApplicationEvents),确保事件不丢失
	/**
* Add beans that implement ApplicationListener as listeners.
* Doesn't affect other listeners, which can be added without being beans.
*/
protected void registerListeners() {
// Register statically specified listeners first.
for (ApplicationListener<?> listener : getApplicationListeners()) {
getApplicationEventMulticaster().addApplicationListener(listener);
} // Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let post-processors apply to them!
String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
for (String listenerBeanName : listenerBeanNames) {
getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
} // Publish early application events now that we finally have a multicaster...
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (!CollectionUtils.isEmpty(earlyEventsToProcess)) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}

2.11 finishBeanFactoryInitialization

负责 完成 BeanFactory 的最终配置并实例化所有非延迟加载的单例 Bean

到目前为止,应该说 BeanFactory 已经创建完成,并且所有的实现了 BeanFactoryPostProcessor 接口的 Bean 都已经初始化并且其中的 postProcessBeanFactory(factory) 方法已经得到回调执行了。而且 Spring 已经“手动”注册了一些特殊的 Bean,如 environment、systemProperties 等。剩下的就是初始化 singleton beans 了,我们知道它们是单例的,如果没有设置懒加载,那么 Spring 会在接下来初始化所有的 singleton beans。

	/**
* Finish the initialization of this context's bean factory,
* initializing all remaining singleton beans.
*/
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
// 注册用户自定义的类型转换服务,用于处理 @Value 注解、XML 配置中的类型转换(如将字符串转换为对象)。
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));
} // Register a default embedded value resolver if no BeanFactoryPostProcessor
// (such as a PropertySourcesPlaceholderConfigurer bean) registered any before:
// at this point, primarily for resolution in annotation attribute values.
if (!beanFactory.hasEmbeddedValueResolver()) {
// 如果没有其他 BeanFactoryPostProcessor(如 PropertySourcesPlaceholderConfigurer)注册过值解析器,则添加一个默认解析器,用于处理占位符 ${...}。
// 例如:解析 @Value("${app.name}") 时,会从 Environment 中获取 app.name 的值。
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
} // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
// 提前初始化所有实现 LoadTimeWeaverAware 接口的 Bean,确保它们的类加载器(用于 LTW,Load-Time Weaving)在 AOP 代理创建前就绪。
// 例如:使用 AspectJ 的 Load-Time Weaving 时,Spring 的 InstrumentationLoadTimeWeaver 需要在此阶段初始化。
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
} // Stop using the temporary ClassLoader for type matching.
// 清理临时类加载器,在 Bean 定义加载阶段,Spring 可能使用临时类加载器进行类型匹配。此步骤释放资源,避免内存泄漏。
beanFactory.setTempClassLoader(null); // Allow for caching all bean definition metadata, not expecting further changes.
// 冻结所有 Bean 定义,禁止后续修改。此时容器已完全加载完所有配置,进入不可变状态,为后续优化(如缓存元数据)做准备。
beanFactory.freezeConfiguration(); // Instantiate all remaining (non-lazy-init) singletons.
// 触发所有非延迟(lazy-init=false)单例 Bean 的实例化、依赖注入和初始化回调(如 @PostConstruct)。
beanFactory.preInstantiateSingletons();
}
sequenceDiagram
participant finishBeanFactoryInitialization
participant BeanFactory
finishBeanFactoryInitialization->>BeanFactory: 设置ConversionService
finishBeanFactoryInitialization->>BeanFactory: 添加默认值解析器
finishBeanFactoryInitialization->>BeanFactory: 初始化LoadTimeWeaverAware Beans
finishBeanFactoryInitialization->>BeanFactory: 清理临时类加载器
finishBeanFactoryInitialization->>BeanFactory: 冻结配置
finishBeanFactoryInitialization->>BeanFactory: 实例化所有非延迟单例
BeanFactory-->>finishBeanFactoryInitialization: 完成初始化
  • 在此阶段可能暴露循环依赖,若存在无法解决的循环依赖,会抛出 BeanCurrentlyInCreationException
  • 标记为 lazy-init=true 的 Bean 不会在此阶段创建,直到首次被请求时才初始化

2.11.1 preInstantiateSingletons

	public void preInstantiateSingletons() throws BeansException {
if (logger.isTraceEnabled()) {
logger.trace("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.
// 防止在迭代过程中,Bean 的初始化逻辑(如 @PostConstruct 方法)动态注册新 Bean,导致 ConcurrentModificationException。
// 若初始化 BeanA 时通过 BeanFactory.registerSingleton() 动态注册了 BeanB,原列表会变化,但迭代的是拷贝的旧列表。
List<String> beanNames = new ArrayList<>(this.beanDefinitionNames); // Trigger initialization of all non-lazy singleton beans...
for (String beanName : beanNames) {
RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
if (isFactoryBean(beanName)) {
// 处理 FactoryBean 逻辑
Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
if (bean instanceof FactoryBean) {
FactoryBean<?> factory = (FactoryBean<?>) bean;
boolean isEagerInit;
// 仅当实现 SmartFactoryBean 且 isEagerInit() 返回 true 时,立即初始化其生产的 Bean。
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(beanName);
}
}
}
else {
getBean(beanName); // 直接初始化普通 Bean
}
}
} // Trigger post-initialization callback for all applicable beans...
// SmartInitializingSingleton 回调
for (String beanName : beanNames) {
Object singletonInstance = getSingleton(beanName);
if (singletonInstance instanceof SmartInitializingSingleton) {
SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
smartSingleton.afterSingletonsInstantiated();
return null;
}, getAccessControlContext());
}
else {
smartSingleton.afterSingletonsInstantiated();
}
}
}
}
sequenceDiagram
participant preInstantiateSingletons
participant BeanFactory
preInstantiateSingletons->>BeanFactory: 遍历所有Bean定义
loop 每个Bean
BeanFactory->>BeanFactory: 合并Bean定义
alt 是普通单例Bean
BeanFactory->>BeanFactory: getBean(beanName)
else 是FactoryBean且需急切实例化
BeanFactory->>BeanFactory: getBean(&beanName) 获取FactoryBean
BeanFactory->>BeanFactory: getBean(beanName) 初始化产品Bean
end
end
preInstantiateSingletons->>BeanFactory: 触发SmartInitializingSingleton回调

循环依赖:若两个单例 Bean 相互依赖,Spring 通过三级缓存解决(DefaultSingletonBeanRegistry)。

性能瓶颈:大量 Bean 的初始化可能拖慢启动速度,可通过懒加载或并行化优化(需 Spring 5.1+ 的 @Lazy 改进)。

AbstractBeanFactory#getBean

	@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}

AbstractBeanFactory#doGetBean

终于要开始初始化bean了,坐稳扶好

doGetBean() 负责根据 Bean 名称和类型获取 Bean 实例,处理作用域、依赖、循环引用、父子容器等复杂场景。

核心流程:

转换 Bean 名称 → 2. 检查缓存 → 3. 处理原型循环依赖 → 4. 委托父容器 → 5. 合并 Bean 定义 → 6. 处理依赖关系 → 7. 创建 Bean 实例 → 8. 类型校验与转换。

	/**
* Return an instance, which may be shared or independent, of the specified bean.
* @param name the name of the bean to retrieve
* @param requiredType the required type of the bean to retrieve
* @param args arguments to use when creating a bean instance using explicit arguments
* (only applied when creating a new instance as opposed to retrieving an existing one)
* @param typeCheckOnly whether the instance is obtained for a type check,
* not for actual use
* @return an instance of the bean
* @throws BeansException if the bean could not be created
*/
@SuppressWarnings("unchecked")
protected <T> T doGetBean(
String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)
throws BeansException { String beanName = transformedBeanName(name); // 处理别名和FactoryBean前缀(&)
Object bean; // Eagerly check singleton cache for manually registered singletons.
Object sharedInstance = getSingleton(beanName); // 检查一级缓存 若单例已存在,直接返回(支持循环依赖,可能返回提前暴露的早期对象)
if (sharedInstance != null && args == null) {
if (logger.isTraceEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.trace("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.trace("Returning cached instance of singleton bean '" + beanName + "'");
}
}
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
} else {
// Fail if we're already creating this bean instance:
// We're assumably within a circular reference.
// Spring 不支持原型 Bean 的循环依赖,若检测到正在创建中的原型 Bean,直接抛出异常。
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
} // Check if bean definition exists in this factory.
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
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 if (requiredType != null) {
// No args -> delegate to standard getBean method.
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
else {
return (T) parentBeanFactory.getBean(nameToLookup);
}
} if (!typeCheckOnly) {
// 标记为已创建,防止重复初始化
markBeanAsCreated(beanName);
} try {
// 合并 Bean 定义
// 合并父子 Bean 定义(如 XML 中的 <bean parent="...">)
// 处理 lookup-method 和 replaced-method 等动态代理配置。
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args); // Guarantee initialization of beans that the current bean depends on.
String[] dependsOn = mbd.getDependsOn();
// 处理依赖关系
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
// 检测循环依赖(如 A depends-on B,B depends-on A)
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
// 注册依赖关系
registerDependentBean(dep, beanName);
try {
// 递归创建依赖的Bean
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
} // Create bean instance.
// 单例
if (mbd.isSingleton()) {
sharedInstance = getSingleton(beanName, () -> {
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);
}
// 原型(Prototype)
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);
}
// 每次调用 getBean() 创建新实例,不保留引用。
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
} else {
// 自定义作用域(如 Request、Session)
// 通过 Scope 接口管理生命周期(如 RequestScope 每个 HTTP 请求一个实例)。
String scopeName = mbd.getScope();
if (!StringUtils.hasLength(scopeName)) {
throw new IllegalStateException("No scope name defined for bean '" + beanName + "'");
}
Scope scope = this.scopes.get(scopeName);
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 = 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.
if (requiredType != null && !requiredType.isInstance(bean)) {
try {
// 类型检查与转换
// 若 Bean 类型不匹配,尝试通过 ConversionService 转换。
T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return convertedBean;
}
catch (TypeMismatchException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}

这里设计循环依赖,简单讲下:

通过三级缓存和提前暴露对象,解决属性注入的循环依赖(构造函数循环依赖无法解决)。

三级缓存机制:

  • 一级缓存(singletonObjects):完整 Bean。
  • 二级缓存(earlySingletonObjects):提前暴露的早期 Bean(未完成属性注入)。
  • 三级缓存(singletonFactories):ObjectFactory,用于解决循环依赖。

循环依赖示例

@Component
public class A {
@Autowired private B b;
} @Component
public class B {
@Autowired private A a;
}

解决流程:

  • 创建 A → 提前暴露 A 的 ObjectFactory(三级缓存)。
  • 注入 B → 创建 B → 注入 A(从三级缓存获取早期 A)。
  • 完成 B 的初始化 → 完成 A 的初始化。

自定义作用域示例:

public class ThreadScope implements Scope {
private final ThreadLocal<Map<String, Object>> threadLocal = ThreadLocal.withInitial(ConcurrentHashMap::new); @Override
public Object get(String name, ObjectFactory<?> objectFactory) {
Map<String, Object> scope = threadLocal.get();
return scope.computeIfAbsent(name, k -> objectFactory.getObject());
}
} // 注册作用域
context.getBeanFactory().registerScope("thread", new ThreadScope()); // 使用
@Scope("thread")
@Component
public class ThreadScopedBean {}

继续往下看

AbstractAutowireCapableBeanFactory#createBean()

  • 预处理 Bean 定义:解析 Bean 的 Class 类型,处理方法覆盖(lookup-method/replace-method)。

  • 前置拦截:允许 BeanPostProcessor 在实例化前返回代理对象(如 AOP)。

  • 实例化委托:若未拦截,调用 doCreateBean() 完成实际创建。

  • 异常处理:统一包装创建过程中的异常。

graph TD
A[开始] --> B[解析Bean的Class类型]
B --> C[处理方法覆盖校验]
C --> D{前置代理生成检查}
D -->|有代理| E[返回代理对象]
D -->|无代理| F[执行doCreateBean]
F --> G[处理异常]
G --> H[返回Bean实例]
	/**
* Central method of this class: creates a bean instance,
* populates the bean instance, applies post-processors, etc.
* @see #doCreateBean
*/
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException { if (logger.isTraceEnabled()) {
logger.trace("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 已正确解析(可能动态加载),避免后续流程因 Class 未解析而失败。
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd); // 克隆定义
mbdToUse.setBeanClass(resolvedClass); // 设置解析后的 Class
} // Prepare method overrides.
// 处理方法覆盖
// 验证并准备 lookup-method 和 replace-method 配置(XML 中定义的方法动态替换)。
// 示例:
/**
* <bean id="myBean" class="com.example.MyBean">
* <lookup-method name="createDependency" bean="dependencyBean"/>
* </bean>
* Spring 会为此生成 CGLIB 子类,覆盖 createDependency() 方法。
* 检查配置的方法是否存在,若不存在则抛出 BeanDefinitionValidationException。
**/
try {
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
} try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
// 实例化前拦截(AOP 关键入口)
// 调用 InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation(),允许返回代理对象。
// AOP 代理在此拦截,若目标 Bean 需要增强,直接返回代理对象,避免后续实例化。
// 实现声明式事务、缓存等功能的透明代理注入。
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
// 若 BeanPostProcessor 返回代理对象,直接跳过后续实例化
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
} try {
// 执行实际创建
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
// A previously detected exception with proper bean creation context already,
// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}

示例场景

  1. AOP 代理创建
@Component
public class MyService {
public void doSomething() { ... }
} @Aspect
@Component
public class MyAspect {
@Around("execution(* MyService.*(..))")
public Object around(ProceedingJoinPoint pjp) { ... }
}
  • resolveBeforeInstantiation() 调用 AOP 的 AbstractAutoProxyCreator。

  • 检测到 MyService 需代理,直接返回 JDK/CGLIB 代理对象。

  • 跳过 doCreateBean(),代理对象成为最终 Bean。

  1. 方法覆盖(lookup-method)
public abstract class CommandManager {
public Object process() {
Command command = createCommand();
return command.execute();
}
protected abstract Command createCommand(); // 动态实现
} // XML 配置
<bean id="commandManager" class="com.example.CommandManager">
<lookup-method name="createCommand" bean="myCommand"/>
</bean>

生成 CommandManager 子类,重写 createCommand() 返回 myCommand Bean。

	/**
* Actually create the specified bean. Pre-creation processing has already happened
* at this point, e.g. checking {@code postProcessBeforeInstantiation} 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 explicit arguments to use for constructor or factory method invocation
* @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(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException { // Instantiate the bean.
// Bean的实例化
// BeanWrapper是对Bean实例的包装,提供属性访问、类型转换等功能。
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
// 如果是单例Bean,尝试从factoryBeanInstanceCache缓存中获取已存在的实例包装对象(BeanWrapper)。
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
// 若缓存未命中,通过createBeanInstance方法反射创建实例(可能使用构造函数或工厂方法)。
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
} // Allow post-processors to modify the merged bean definition.
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且允许循环引用时生效。
// 向singletonFactories注册一个ObjectFactory,当其他Bean注入当前Bean时,会通过getEarlyBeanReference获取早期引用。
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
// getEarlyBeanReference可能触发AOP代理的创建(如存在SmartInstantiationAwareBeanPostProcessor)。
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
} // Initialize the bean instance.
Object exposedObject = bean;
try {
// 填充Bean属性,包括依赖注入(如通过@Autowired、XML配置的<property>)。
populateBean(beanName, mbd, instanceWrapper);
// 执行初始化逻辑
// 调用BeanPostProcessor.postProcessBeforeInitialization(如处理@PostConstruct)
// 执行InitializingBean.afterPropertiesSet或自定义的init-method
// 调用BeanPostProcessor.postProcessAfterInitialization(可能生成代理对象,如AOP)。
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);
}
} // 确保依赖注入的是最终Bean(如代理对象),而非早期原始Bean。
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<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
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 " +
"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
} // Register bean as disposable.
try {
// 注册Bean的销毁方法(如DisposableBean.destroy()或自定义的destroy-method)
// 单例Bean的销毁逻辑会被注册到DisposableBeanAdapter,在容器关闭时调用。
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
} return exposedObject;
}
1. 实例化Bean
├─ 从缓存获取或反射创建实例
2. 处理合并的Bean定义
└─ 后处理器解析注解(如@Autowired)
3. 提前暴露引用(解决循环依赖)
└─ 注册ObjectFactory到singletonFactories
4. 属性填充与初始化
├─ populateBean: 依赖注入
└─ initializeBean: 初始化回调、BeanPostProcessor处理
5. 检查早期引用冲突
└─ 确保依赖注入的是最终Bean
6. 注册销毁逻辑

AbstractAutowireCapableBeanFactory#createBeanInstance

	/**
* Create a new instance for the specified bean, using an appropriate instantiation strategy:
* factory method, constructor autowiring, or simple instantiation.
* @param beanName the name of the bean
* @param mbd the bean definition for the bean
* @param args explicit arguments to use for constructor or factory method invocation
* @return a BeanWrapper for the new instance
* @see #obtainFromSupplier
* @see #instantiateUsingFactoryMethod
* @see #autowireConstructor
* @see #instantiateBean
*/
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
// 将Bean定义中的类名解析为具体的Class对象。
Class<?> beanClass = resolveBeanClass(mbd, beanName); // 确保类的访问权限符合配置。
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());
} // 如果Bean定义中指定了Supplier,直接通过它创建实例
// 用户可通过编程式配置(如BeanDefinitionBuilder)自定义实例化逻辑。
/**
* BeanDefinitionBuilder.genericBeanDefinition(MyBean.class).setInstanceSupplier(() -> new MyBean("custom-arg"));
*/
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
} if (mbd.getFactoryMethodName() != null) { // 如果配置了工厂方法(静态工厂或实例工厂),调用工厂方法创建Bean。
return instantiateUsingFactoryMethod(beanName, mbd, args);
} // Shortcut when re-creating the same bean...
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) {
return autowireConstructor(beanName, mbd, null, null);
}
else {
return instantiateBean(beanName, mbd);
}
} // Candidate constructors for autowiring?
// 根据Bean后处理器或配置,选择合适的构造函数进行自动装配。
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
} // Preferred constructors for default construction?
// 如果Bean定义指定了首选构造函数(如通过@Lookup或自定义逻辑),优先使用它。
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
} // No special handling: simply use no-arg constructor. // 当无特殊配置时,通过反射调用无参构造函数创建实例。
return instantiateBean(beanName, mbd);
}
开始
├─ 解析Bean的Class
├─ 检查类是否为public或允许非公开访问 → 否则抛出异常
├─ 是否配置了Supplier? → 是 → 通过Supplier创建实例
├─ 是否配置了工厂方法? → 是 → 通过工厂方法创建
├─ 是否已解析过构造函数? → 是 → 复用缓存结果
├─ 是否有候选构造函数(如@Autowired)或需构造器注入? → 是 → 自动装配构造器
├─ 是否有首选构造函数? → 是 → 使用首选构造器
└─ 默认 → 使用无参构造器实例化
结束

简单的无参构造函数构造实例

AbstractAutowireCapableBeanFactory#instantiateBean

	/**
* Instantiate the given bean using its default constructor.
* @param beanName the name of the bean
* @param mbd the bean definition for the bean
* @return a BeanWrapper for the new instance
*/
protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
try {
Object beanInstance;
if (System.getSecurityManager() != null) {
beanInstance = AccessController.doPrivileged(
(PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(mbd, beanName, this),
getAccessControlContext());
}
else {
// 实例化
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this);
}
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
initBeanWrapper(bw);
return bw;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
}
}

SimpleInstantiationStrategy#instantiate()

	@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
// Don't override the class with CGLIB if no overrides.
// hasMethodOverrides() 用于判断该 Bean 是否定义了需要被覆盖的方法(用于 Spring 的 AOP 或 Lookup/Replace 方法注入)
// false:表示普通的 Bean,可以直接通过构造方法实例化。
// true:需要 CGLIB 动态代理创建子类实例。
if (!bd.hasMethodOverrides()) {
Constructor<?> constructorToUse;
synchronized (bd.constructorArgumentLock) {
// 尝试使用已经解析好的构造函数(缓存提升性能)。
// 如果没有缓存,则尝试解析默认构造函数。
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
if (constructorToUse == null) {
final Class<?> clazz = bd.getBeanClass();
if (clazz.isInterface()) {
// 如果是接口,不能实例化,抛出异常。
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
if (System.getSecurityManager() != null) {
// 如果启用了 Java 安全管理器(SecurityManager),通过特权操作获取构造函数。
constructorToUse = AccessController.doPrivileged(
(PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
}
else {
// 否则,直接调用 getDeclaredConstructor()。
constructorToUse = clazz.getDeclaredConstructor();
}
// 将解析到的构造方法缓存到 BeanDefinition 中,后续可以复用。
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
}
catch (Throwable ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
}
}
// 使用工具类反射调用构造方法创建实例。
return BeanUtils.instantiateClass(constructorToUse);
}
else {
// Must generate CGLIB subclass.
// 如果 Bean 定义了方法注入配置,就不能直接使用构造函数实例化。
// Spring 会使用 CGLIB 创建一个子类,并注入相关逻辑(比如 @Lookup、MethodReplacer)。
return instantiateWithMethodInjection(bd, beanName, owner);
}
}

走完这个方法,bean 就实例化完了,但是还没属性注入

AbstractAutowireCapableBeanFactory#populateBean

属性注入开始

	/**
* Populate the bean instance in the given BeanWrapper with the property values
* from the bean definition.
* @param beanName the name of the bean
* @param mbd the bean definition for the bean
* @param bw the BeanWrapper with bean instance
*/
@SuppressWarnings("deprecation") // for postProcessPropertyValues
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
if (bw == null) {
// 确保Bean实例存在。若实例为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;
}
} // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// state of the bean before properties are set. This can be used, for example,
// to support styles of field injection.
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
// 在属性设置前,允许后处理器干预(如终止属性填充)
return;
}
}
}
} PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null); int resolvedAutowireMode = mbd.getResolvedAutowireMode();
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
// 按名称注入
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
// 按类型注入
autowireByType(beanName, mbd, bw, newPvs);
}
// 合并自动装配结果到属性值集合pvs中。
pvs = newPvs;
} boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE); PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
for (BeanPostProcessor bp : getBeanPostProcessors()) {
// 通过InstantiationAwareBeanPostProcessor处理注解驱动的依赖注入
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 调用postProcessProperties处理属性(如@Autowired、@Value) // postProcessProperties是Spring 5.0+的API,优先于旧的postProcessPropertyValues。
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
// 注解注入的优先级高于XML配置的属性值(通过合并后的pvs体现)。
pvs = pvsToUse;
}
}
}
if (needsDepCheck) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
// 验证所有必需的属性是否已正确注入。
checkDependencies(beanName, mbd, filteredPds, pvs);
} if (pvs != null) {
// 将最终的属性值(包括XML配置、自动装配、注解注入的结果)设置到Bean实例中。
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
开始
├─ 检查BeanWrapper是否为空 → 是且无属性值 → 返回
├─ 调用InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation → 若返回false → 终止
├─ 按名称/类型自动装配 → 合并到属性值集合
├─ 调用InstantiationAwareBeanPostProcessor.postProcessProperties → 处理注解注入
├─ 依赖检查 → 验证必需属性是否注入
└─ 应用属性值 → 类型转换 + 反射赋值
结束

示例:

  1. XML配置属性注入:
<bean class="com.example.UserService">
<property name="userDao" ref="jdbcUserDao"/>
</bean>

pvs中包含userDao的引用,最终通过applyPropertyValues设置。

  1. @Autowired注解注入:
public class UserService {
@Autowired
private UserDao userDao;
}

AutowiredAnnotationBeanPostProcessor会识别@Autowired,将userDao添加到pvs。

  1. 混合注入(XML + 注解):
  • 若XML和注解同时指定同一属性,注解的值会覆盖XML配置(取决于后处理器执行顺序)。
  1. 自动装配冲突解决:
  • 当按类型自动装配存在多个候选Bean时,结合@Primary、@Qualifier解决歧义。

属性注入完之后 会执行bean的init方法

  1. 回调 Aware 接口(BeanNameAware、BeanFactoryAware 等)。
  2. 执行 BeanPostProcessor 的前置处理逻辑。
  3. 调用 Bean 的初始化方法(afterPropertiesSet 或 init-method)。
  4. 执行 BeanPostProcessor 的后置处理逻辑(如 AOP 代理)。
	/**
* 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}, 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, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
} Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
} try {
// invokeAwareMethods:用于执行实现了以下接口的回调方法:
// BeanNameAware.setBeanName(beanName)
// BeanClassLoaderAware.setBeanClassLoader(...)
// BeanFactoryAware.setBeanFactory(...)
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()) {
// 这一步会调用所有注册的 BeanPostProcessor 的
// 用于对 Bean 在初始化前进行一些增强(比如 AOP 的切入点、资源注入等)。
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
} return wrappedBean;
}

AbstractAutowireCapableBeanFactory#invokeInitMethods

  1. 如果 Bean 实现了 InitializingBean 接口,会调用其 afterPropertiesSet() 方法。
  2. 如果在 BeanDefinition 中配置了 init-method(如 init-method="initData"),则通过反射调用对应方法。
  3. 避免重复调用(如 init-method 叫 "afterPropertiesSet" 时不会再次反射执行)。
  4. 支持安全环境下的调用(使用 AccessController.doPrivileged)。
	/**
* Give a bean a chance to react now all its properties are set,
* and a chance to know about its owning bean factory (this object).
* This means checking whether the bean implements InitializingBean or defines
* a custom init method, and invoking the necessary callback(s) if it does.
* @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 merged bean definition that the bean was created with
* (can also be {@code null}, if given an existing bean instance)
* @throws Throwable if thrown by init methods or by the invocation process
* @see #invokeCustomInitMethod
*/
protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {
// 是否实现了 InitializingBean 接口?
boolean isInitializingBean = (bean instanceof InitializingBean);
// mbd.isExternallyManagedInitMethod(...) 表示是否已被 Spring 认为不需要自己手动调用(通常用于内部管理)。
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isTraceEnabled()) {
logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
((InitializingBean) bean).afterPropertiesSet();
return null;
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
((InitializingBean) bean).afterPropertiesSet();
}
} if (mbd != null && bean.getClass() != NullBean.class) {
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}

内容补充:

参考内容:https://javadoop.com/post/spring-ioc

Spring IOC源码解析的更多相关文章

  1. Spring IoC源码解析之invokeBeanFactoryPostProcessors

    一.Bean工厂的后置处理器 Bean工厂的后置处理器:BeanFactoryPostProcessor(触发时机:bean定义注册之后bean实例化之前)和BeanDefinitionRegistr ...

  2. Spring IoC源码解析之getBean

    一.实例化所有的非懒加载的单实例Bean 从org.springframework.context.support.AbstractApplicationContext#refresh方法开发,进入到 ...

  3. Spring系列(三):Spring IoC源码解析

    一.Spring容器类继承图 二.容器前期准备 IoC源码解析入口: /** * @desc: ioc原理解析 启动 * @author: toby * @date: 2019/7/22 22:20 ...

  4. Spring IoC源码解析——Bean的创建和初始化

    Spring介绍 Spring(http://spring.io/)是一个轻量级的Java 开发框架,同时也是轻量级的IoC和AOP的容器框架,主要是针对JavaBean的生命周期进行管理的轻量级容器 ...

  5. Spring IOC 源码解析(持续)

    如何查看源码 Spring源码下载https://github.com/spring-projects/spring-framework/tags?after=v3.1.0.RC1 eclipse关联 ...

  6. spring ioc 源码解析

    什么是ioc? 通俗的解释是:(spring)框架中,完成对象的创建和注入的容器. springIOC体系结构: spring IOC的创建是典型的工厂模式,这一系列的bean工厂如上所示. 其核心是 ...

  7. Spring系列(五):Spring AOP源码解析

    一.@EnableAspectJAutoProxy注解 在主配置类中添加@EnableAspectJAutoProxy注解,开启aop支持,那么@EnableAspectJAutoProxy到底做了什 ...

  8. Spring Boot系列(四):Spring Boot源码解析

    一.自动装配原理 之前博文已经讲过,@SpringBootApplication继承了@EnableAutoConfiguration,该注解导入了AutoConfigurationImport Se ...

  9. spring IoC源码分析 (3)Resource解析

    引自 spring IoC源码分析 (3)Resource解析 定义好了Resource之后,看到XmlFactoryBean的构造函数 public XmlBeanFactory(Resource  ...

  10. 深入Spring IOC源码之ResourceLoader

    在<深入Spring IOC源码之Resource>中已经详细介绍了Spring中Resource的抽象,Resource接口有很多实现类,我们当然可以使用各自的构造函数创建符合需求的Re ...

随机推荐

  1. MongoDB:分页查询(统计查询和分页列表查询)、排序查询、正则的复杂条件查询、比较查询、包含查询、条件连接查询

  2. 九集代码深度解析SpringBoot原理:笔记整理

    手动注册Tomcat中的servlet容器 子父容器概念

  3. 配置计算节点之间的SSH

    本文分享自天翼云开发者社区<配置计算节点之间的SSH>,作者:y****n 如果在管理程序之间调整或迁移实例,可能会遇到SSH(拒绝权限)错误.请确保每个节点都配置了SSH密钥验证,以便C ...

  4. Jenkins+Coverage的代码覆盖率集成实践

    Jenkins+Coverage的代码覆盖率集成实践 一.工具介绍 Jenkins: Jenkins是一个开源的.基于Java开发的持续集成工具,它可以帮助开发人员自动化构建.测试和部署软件项目. C ...

  5. 具体数学第六章习题选做(genshining)

    11.对于 \(n\ge 0\),求以下式子的封闭形式. \[\sum_k(-1)^k{n\brack k} \] 由于 \[\sum{n\brack k}x^k=x^{\overline n} \] ...

  6. 在table中tr的display:block显示布局错乱问题

    参考链接:https://blog.csdn.net/zj853975468/article/details/51554054?utm_medium=distribute.pc_relevant_do ...

  7. C语言中的*和&符号

    之前对*和&符号一直理解的比较浅显.只知道: *p好像表示的是一个指针: &p表示的是一个地址. 然而这次当遇到了下面这个情况的时候: int a = 10; int *b = &am ...

  8. ReviOS - 专为游戏优化的 Win11 / Win10 精简版系统

    ReviOS介绍 ReviOS 渴望重新创建作为操作系统的 Windows 应该是 - 简单.ReviOS 是一款功能强大.高效的私有操作系统,适用于游戏玩家.高级用户和发烧友.由于资源.占用内存和存 ...

  9. Linux服务器快速卸载安装node环境(简单上手)

    这篇文章主要介绍了Linux服务器快速卸载安装node环境(简单上手) 1.先卸载npm sudo npm uninstall npm -g 2.卸载node yum remove nodejs np ...

  10. 使用 SK 进行向量操作

    先祝大家 2025 新年好. 在 2024 年落地的 LLM 应用来看,基本上都是结合 RAG 技术来使用的.因为绝大多数人跟公司是没有 fine-turning 的能力的.不管是在难度还是成本的角度 ...