【spring源码分析】IOC容器初始化(一)

时间:2023-07-11 21:31:38

前言:spring主要就是对bean进行管理,因此IOC容器的初始化过程非常重要,搞清楚其原理不管在实际生产或面试过程中都十分的有用。在【spring源码分析】准备工作中已经搭建好spring的环境,并利用xml配置形式对类进行了实例化。在test代码中有一个非常关键的类ClassPathXmlApplicationContext,在这个类中实现了IOC容器的初始化,因此我们从ClassPathXmlApplicationContext着手开始研究IOC的初始化过程。


ClassPathXmlApplicationContext类继承关系

【spring源码分析】IOC容器初始化(一)

ClassPathXmlApplicationContext类的继承关系非常的庞大,在IOC容器初始化的过程中,经常使用委派的方式进行函数的调用,因此需特别注意类之间的继承关系。通过阅读源码,可粗略的将IOC容器初始化过程分为两步:

① 解析xml文件,导入bean

② 通过反射生成bean

因此下面将从这两大步对IOC初始化进行分析。

导入bean阶段程序调用链

首先给出导入bean的调用链:

【spring源码分析】IOC容器初始化(一)

通过程序调用链可知:

#1.导入bean的过程大致分为三个阶段:

①导入bean(loadBeanDefinitions)

②解析bean(parseBeanDefinition)

③注册bean(registerBeanDefinition)

#2.最终bean是存储在beanDefinitionMap中:键为类名(beanName),值为GenericBeanDefinition(BeanDefinition)。

下面对导入bean的三个阶段进行分析。

导入bean阶段源码分析

首先来看ClassPathXmlApplicationContext构造函数,具体代码如下:

 public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
// 初始化父类相关资源
super(parent);
// 解析配置文件路径,并设置资源路径
setConfigLocations(configLocations);
if (refresh) {
// 核心方法 ioc容器初始化在此方法中实现
refresh();
}
}

看似寥寥的几行代码,其实也非常重要,从这里我们可以了解到spring是如何解析配置文件中的占位符信息的,这里关注PropertyResolver接口。

首先我们看PropertyResolver接口源码:

 public interface PropertyResolver {

     /**
* 是否包含某个属性<br/>
* Return whether the given property key is available for resolution,
* i.e. if the value for the given key is not {@code null}.
*/
boolean containsProperty(String key); /**
* 获取属性值 如果找不到则返回null<br/>
* Return the property value associated with the given key,
* or {@code null} if the key cannot be resolved.
*
* @param key the property name to resolve
* @see #getProperty(String, String)
* @see #getProperty(String, Class)
* @see #getRequiredProperty(String)
*/
@Nullable
String getProperty(String key); /**
* 获取属性值,如果找不到则返回默认值<br/>
* Return the property value associated with the given key, or
* {@code defaultValue} if the key cannot be resolved.
*
* @param key the property name to resolve
* @param defaultValue the default value to return if no value is found
* @see #getRequiredProperty(String)
* @see #getProperty(String, Class)
*/
String getProperty(String key, String defaultValue); /**
* 获取指定类型的属性值,找不到则返回null<br/>
* Return the property value associated with the given key,
* or {@code null} if the key cannot be resolved.
*
* @param key the property name to resolve
* @param targetType the expected type of the property value
* @see #getRequiredProperty(String, Class)
*/
@Nullable
<T> T getProperty(String key, Class<T> targetType); /**
* 获取指定类型的属性值,找不到则返回默认值<br/>
* Return the property value associated with the given key,
* or {@code defaultValue} if the key cannot be resolved.
*
* @param key the property name to resolve
* @param targetType the expected type of the property value
* @param defaultValue the default value to return if no value is found
* @see #getRequiredProperty(String, Class)
*/
<T> T getProperty(String key, Class<T> targetType, T defaultValue); /**
* 获取属性值,找不到则抛出异常IllegalStateException<br/>
* Return the property value associated with the given key (never {@code null}).
*
* @throws IllegalStateException if the key cannot be resolved
* @see #getRequiredProperty(String, Class)
*/
String getRequiredProperty(String key) throws IllegalStateException; /**
* 获取指定类型的属性值,找不到则抛出异常IllegalStateException<br/>
* Return the property value associated with the given key, converted to the given
* targetType (never {@code null}).
*
* @throws IllegalStateException if the given key cannot be resolved
*/
<T> T getRequiredProperty(String key, Class<T> targetType) throws IllegalStateException; /**
* 替换文本中的占位符(${key})到属性值,找不到则不解析
* Resolve ${...} placeholders in the given text, replacing them with corresponding
* property values as resolved by {@link #getProperty}. Unresolvable placeholders with
* no default value are ignored and passed through unchanged.
*
* @param text the String to resolve
* @return the resolved String (never {@code null})
* @throws IllegalArgumentException if given text is {@code null}
* @see #resolveRequiredPlaceholders
* @see org.springframework.util.SystemPropertyUtils#resolvePlaceholders(String)
*/
String resolvePlaceholders(String text); /**
* 替换文本中占位符(${key})到属性值,找不到则抛出异常IllegalArgumentException
* Resolve ${...} placeholders in the given text, replacing them with corresponding
* property values as resolved by {@link #getProperty}. Unresolvable placeholders with
* no default value will cause an IllegalArgumentException to be thrown.
*
* @return the resolved String (never {@code null})
* @throws IllegalArgumentException if given text is {@code null}
* or if any placeholders are unresolvable
* @see org.springframework.util.SystemPropertyUtils#resolvePlaceholders(String, boolean)
*/
String resolveRequiredPlaceholders(String text) throws IllegalArgumentException; }

该接口定义了一些与属性(解析占位符/获取属性)相关的方法,以ClassPathXmlApplicationContext构造函数的第7行代码为Debug入口,下面会通过调试的形式进行分析

PropertyResolver继承关系如下,注意AbstractPropertyResolver与StandardEnvironment都间接的实现了PropertyResolver接口。

【spring源码分析】IOC容器初始化(一)

在setConfigLocations(String)打断点,进行Debug,会走到AbstractRefreshableConfigApplicationContext#resolvePath处:

 protected String resolvePath(String path) {
return getEnvironment().resolveRequiredPlaceholders(path);
}

这里getEnvironment()调用的是父类AbstractApplicationContext的方法:

     public ConfigurableEnvironment getEnvironment() {
if (this.environment == null) {
// 创建一个ConfigurableEnvironment对象
this.environment = createEnvironment();
}
return this.environment;
}
protected ConfigurableEnvironment createEnvironment() {
return new StandardEnvironment();
}

注意这里返回的是一个ConfigurableEnvironment 对象,继续debug,进入resolveRequiredPlaceholders(String)函数:

    private final ConfigurablePropertyResolver propertyResolver =new PropertySourcesPropertyResolver(this.propertySources);

     public String resolveRequiredPlaceholders(String text) throws IllegalArgumentException {
// 委派给AbstractPropertyResolver执行
return this.propertyResolver.resolveRequiredPlaceholders(text);
}

由于函数调用过程太细,所以这里给出解析配置文件中占位符的最终核心点:PropertyPlaceholderHelper#parseStringValue方法上:

 protected String parseStringValue(
String value, PlaceholderResolver placeholderResolver, Set<String> visitedPlaceholders) { StringBuilder result = new StringBuilder(value);
// 获取前缀"${"的索引位置
int startIndex = value.indexOf(this.placeholderPrefix);
while (startIndex != -1) {
// 获取后缀"}"的索引位置
int endIndex = findPlaceholderEndIndex(result, startIndex);
if (endIndex != -1) {
// 截取"${"和"}"中间的内容,即配置文件中对应的值
String placeholder = result.substring(startIndex + this.placeholderPrefix.length(), endIndex);
String originalPlaceholder = placeholder;
if (!visitedPlaceholders.add(originalPlaceholder)) {
throw new IllegalArgumentException(
"Circular placeholder reference '" + originalPlaceholder + "' in property definitions");
}
// Recursive invocation, parsing placeholders contained in the placeholder key.
// 解析占位符键中包含的占位符,真正的值
placeholder = parseStringValue(placeholder, placeholderResolver, visitedPlaceholders);
// Now obtain the value for the fully resolved key...
// 从Properties中获取placeHolder对应的propVal
String propVal = placeholderResolver.resolvePlaceholder(placeholder);
// 如果不存在
if (propVal == null && this.valueSeparator != null) {
// 查询":"的位置
int separatorIndex = placeholder.indexOf(this.valueSeparator);
// 如果存在
if (separatorIndex != -1) {
// 截取":"前面部分的actualPlaceholder
String actualPlaceholder = placeholder.substring(0, separatorIndex);
// 截取":"后面的defaulValue
String defaultValue = placeholder.substring(separatorIndex + this.valueSeparator.length());
// 从Properties中获取actualPlaceholder对应的值
propVal = placeholderResolver.resolvePlaceholder(actualPlaceholder);
// 如果不存在,则返回defaultValue
if (propVal == null) {
propVal = defaultValue;
}
}
}
if (propVal != null) {
// Recursive invocation, parsing placeholders contained in the
// previously resolved placeholder value.
propVal = parseStringValue(propVal, placeholderResolver, visitedPlaceholders);
result.replace(startIndex, endIndex + this.placeholderSuffix.length(), propVal);
if (logger.isTraceEnabled()) {
logger.trace("Resolved placeholder '" + placeholder + "'");
}
startIndex = result.indexOf(this.placeholderPrefix, startIndex + propVal.length());
}
else if (this.ignoreUnresolvablePlaceholders) {
// Proceed with unprocessed value.
// 忽略值
startIndex = result.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length());
}
else {
throw new IllegalArgumentException("Could not resolve placeholder '" +
placeholder + "'" + " in value \"" + value + "\"");
}
visitedPlaceholders.remove(originalPlaceholder);
}
else {
startIndex = -1;
}
}
// 返回propVal,就是替换之后的值
return result.toString();
}

分析:

该函数的主要作用就是取占位符"${}"或":"中的值进行赋值,比如在配置文件中直接使用xxx="${xxx.xx.xx}"或使用注解扫描时使用@Value("${xxx.xx.xx}")进行属性值注入的时候,都会走该函数进行解析。

接下来看非常重要的AbstractApplicationContext#refresh()函数:

 public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
// 准备刷新上下文环境
prepareRefresh(); // Tell the subclass to refresh the internal bean factory.
// 创建并初始化BeanFactory
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.
// 提供子类覆盖的额外处理,即子类处理定义的BeanFactoryPostProcess
postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context.
// 激活各种BeanFactory处理器
invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation.
// 注册拦截Bean创建的Bean处理器,即注册BeanPostProcessor
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.
// 在所有bean中查找listener bean,然后注册到广播器中
registerListeners(); // Instantiate all remaining (non-lazy-init) singletons.
// 初始化剩下的单例Bean(非延迟加载的)
finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event.
// 完成刷新过程,通知声明周期处理器lifecycleProcessor刷新过程,同时发出ContextRefreshEvent事件通知别人
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.
// 重置容器激活标签
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();
}
}
}

分析:

该函数中进行了IOC容器的初始化工作,以该函数为切入点,进行相应源码的分析,一步一步来力求搞清楚。

AbstractApplicationContext#prepareRefresh()

 protected void prepareRefresh() {
// Switch to active.
// 设置启动时间
this.startupDate = System.currentTimeMillis();
// 设置context当前状态
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.
// 初始化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<>();
}

分析:

prepareRefresh()函数,作用较为简单,主要是做一些设置操作,这里不做过多赘述。

AbstractApplicationContext#obtainFreshBeanFactory()

 protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
// 刷新BeanFactory
refreshBeanFactory();
// 返回BeanFactory
return getBeanFactory();
}

分析:

该函数主要作用:创建并初始化BeanFactory。

这里简单介绍一下BeanFactory:它是一个基本的Bean容器,其中BeanDefinition是它的基本结构,BeanFactory内部维护了一个BeanDefinitionMap(要点),BeanFactory可根据BeanDefinition的描述进行bean的创建与管理。

【spring源码分析】IOC容器初始化(一)

注:DefaultListableBeanFactory为最终默认实现,它实现了所有接口。

进入AbstractRefreshableApplicationContext#refreshBeanFactory()函数

 @Override
protected final void refreshBeanFactory() throws BeansException {
// 若已有BeanFactory,则销毁bean,并销毁BeanFactory
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
// 创建BeanFactory对象
DefaultListableBeanFactory beanFactory = createBeanFactory();
// 指定序列化编号
beanFactory.setSerializationId(getId());
// 定制BeanFactory 设置相关属性
customizeBeanFactory(beanFactory);
// 加载BeanDefinition
loadBeanDefinitions(beanFactory);
// 设置Context的BeanFactory
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
} catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}

分析:

相应代码已经给出了基本注释,这里我们主要关注第16行代码:loadBeanDefinitions(DefaultListableBeanFactory),从该函数可引申非常多重要的知识点,介于篇幅原因,将在后面进行详细分析。

总结

这里再次总结本文重点:

  • PropertyResolver,以及引申出来的PropertyPlaceholderHelper#parseStringValue(占位符解析重要函数)与日常开发也息息相关。
  • BeanFactory以及其最终实现类DefaultListableBeanFactory,基础的IoC容器,提供与bean相关的方法。
  • loadBeanDefinitions方法,这里再次强调一下,该方法非常重要。

by Shawn Chen,2018.11.24日,晚。