一、写在前面
本文均为个人观点,如有错误,跪求指正,共同学习进步。此系列文章所涉及源码为spring-5.0.2.RELEASE版本。
二、梦开始的地方-spring容器启动
无论阅读什么框架的源码,最好的方式就是从启动入口开始,逐步分析启动的阶段分别作了什么事情。对于spring,常见的启动方式为使用如下代码:
new ClassPathXmlApplicationContext("beans.xml");
通过传入一个或者多个配置文件作为参数,来启动spring。我们不妨进入此构造方法查看查看:
public ClassPathXmlApplicationContext(String configLocation)
throws BeansException {
this(new String[] {configLocation}, true, null);
}
可以发现,调用的是一个重载的构造方法,如下:
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
//调用父类的构造函数,最终定位到AbstractApplicationContext,
//主要是设置父context的逻辑,并且共享父context中的environment
super(parent);
//解析传入的资源路径
setConfigLocations(configLocations);
//定位到AbstractApplicationContext中的refresh()
if (refresh) {
refresh();
}
}
分为三部分:首先调用父类构造方法,处理如果有父容器的情况,其次解析传入的资源路径,最后调用刷新容器方法。
我们一步步来看:
1.super(parent)
此方法我们一路追踪,最终定位到了ClassPathXmlApplicationContext继承链的AbstractApplicationContext类中,方法如下:
public AbstractApplicationContext() {
this.resourcePatternResolver = getResourcePatternResolver();
}
/**
* Create a new AbstractApplicationContext with the given parent context.
* @param parent the parent context
*/
public AbstractApplicationContext(@Nullable ApplicationContext parent) {
this();
//设置父context
setParent(parent);
}
@Override
public void setParent(@Nullable ApplicationContext parent) {
this.parent = parent;
//共享父context的环境信息
if (parent != null) {
Environment parentEnvironment = parent.getEnvironment();
if (parentEnvironment instanceof ConfigurableEnvironment) {
getEnvironment().merge((ConfigurableEnvironment) parentEnvironment);
}
}
}
可以看出,对于父容器,子容器所做的就是将父容器的环境配置信息进行合并。
2.setConfigLocations(configLocations)
紧接着便是解析启动spring容器时传入的配置文件名称,此方法是ClassPathXmlApplicationContext父类AbstractRefreshableConfigApplicationContext中定义的方法,内容如下:
public void setConfigLocation(String location){
//String CONFIG_LOCATION_DELIMITERS = ",; \t\n";
//按照分隔符组成一个string数组传入
setConfigLocations(StringUtils.tokenizeToStringArray(location,
CONFIG_LOCATION_DELIMITERS));
}
public void setConfigLocations(@Nullable String... locations) {
if (locations != null) {
Assert.noNullElements(locations, "Config locations must not be null");
this.configLocations = new String[locations.length];
//循环遍历配置文件进行解析
for (int i = 0; i < locations.length; i++) {
this.configLocations[i] = resolvePath(locations[i]).trim();
}
}
else {
this.configLocations = null;
}
}
protected String resolvePath(String path) {
return getEnvironment().resolveRequiredPlaceholders(path);
}
如果传入多个配置文件,循环调用resolvePath方法进行解析,此方法中调用getEnvironment方法获取environment对象并调用解析方法,getEnvironment定义在继承链的AbstractApplicationContext类中:
@Override
public ConfigurableEnvironment getEnvironment() {
if (this.environment == null) {
this.environment = createEnvironment();
}
return this.environment;
}
protected ConfigurableEnvironment createEnvironment() {
return new StandardEnvironment();
}
获得的其实是StandardEnvironment对象,然后调用此对象的resolveRequiredPlaceholders方法,跟踪代码可知,此方法定义在其父类AbstractEnvironment中,追踪最终调用链,锁定到PropertyPlaceholderHelper的replacePlaceholders方法:
public String replacePlaceholders(String value, PlaceholderResolver placeholderResolver) {
//这里的placeholderResolver为AbstractPropertyResolver类调用时传入的
//replacePlaceholders(text, this::getPropertyAsRawString);
//而AbstractPropertyResolver的getPropertyAsRawString方法最终实现在
//PropertySourcesPropertyResolver中
Assert.notNull(value, "'value' must not be null");
return parseStringValue(value, placeholderResolver, new HashSet<>());
}
protected String parseStringValue(
String value, PlaceholderResolver placeholderResolver, Set<String> visitedPlaceholders) {
StringBuilder result = new StringBuilder(value);
//placeholderPrefix的值为${,此类是在AbstractPropertyResolver类中创建的
//当时传入的placeholderPrefix值为SystemPropertyUtils类中定义的前缀
//用于解析${}表达式
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);
// 此处最终调用的是PropertySourcesPropertyResolver类的getProperty方法
String propVal = placeholderResolver.resolvePlaceholder(placeholder);
if (propVal == null && this.valueSeparator != null) {
//是否有:存在
int separatorIndex = placeholder.indexOf(this.valueSeparator);
if (separatorIndex != -1) {
//将字符串从:分成两部分
String actualPlaceholder = placeholder.substring(0, separatorIndex);
String defaultValue = placeholder.substring(separatorIndex + this.valueSeparator.length());
//再次解析前半部分,如果也是null就赋默认值,也就是:后面跟的
propVal = placeholderResolver.resolvePlaceholder(actualPlaceholder);
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.
//如果上面解析的值为null,即无法解析,此时判断是否需要忽略,如果是就继续解析下一个${位置
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;
}
}
return result.toString();
}
//PropertySourcesPropertyResolver类中的getProperty方法如下
@Nullable
protected <T> T getProperty(String key, Class<T> targetValueType, boolean resolveNestedPlaceholders) {
if (this.propertySources != null) {
//此处我们并没有传入过任何的PropertySource,所以此方法最终返回null,因为我们传入的配置文件中并没有任何需要解析的内容
for (PropertySource<?> propertySource : this.propertySources) {
if (logger.isTraceEnabled()) {
logger.trace("Searching for key '" + key + "' in PropertySource '" +
propertySource.getName() + "'");
}
Object value = propertySource.getProperty(key);
if (value != null) {
if (resolveNestedPlaceholders && value instanceof String) {
value = resolveNestedPlaceholders((String) value);
}
logKeyFound(key, propertySource, value);
return convertValueIfNecessary(value, targetValueType);
}
}
}
if (logger.isDebugEnabled()) {
logger.debug("Could not find key '" + key + "' in any property source");
}
return null;
}
上面就是解析配置文件名称的代码内容,整体还是比较清晰的。
3.refresh()
refresh方法在AbstractApplicationContext类中实现,代码如下:
@Override
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.
//注册一些beanFactory的后置处理器
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
//执行beanFactory的后置处理器回调
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
//注册bean的后置处理器
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
//初始化信息源(国际化相关)
initMessageSource();
// Initialize event multicaster for this context.
//初始化事件传播器
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
//调用子类的某些特殊bean的初始化方法
onRefresh();
// Check for listener beans and register them.
//注册事件监听器
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
//实例化其他所有的单例bean
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
//发布一些事件
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
//销毁所有的bean
destroyBeans();
// Reset 'active' flag.
//结束刷新方法,重置容器的同步标识
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();
}
}
}
代码内容很简洁,调用了n多个方法,我们一个个分析:
a.prepareRefresh()
protected void prepareRefresh() {
//首先获取当前时间
this.startupDate = System.currentTimeMillis();
//设置容器状态,调整为活动状态
this.closed.set(false);
this.active.set(true);
if (logger.isInfoEnabled()) {
logger.info("Refreshing " + this);
}
//初始化环境中的占位符属性(${})默认什么都不做,用于子类扩展方法
initPropertySources();
//校验属性(验证必要的属性都是可解析的)
getEnvironment().validateRequiredProperties();
this.earlyApplicationEvents = new LinkedHashSet<>();
}
b.obtainFreshBeanFactory()
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
//刷新bean工厂,加载bean配置
//(在子类AbstractRefreshableApplicationContext中实现的)
refreshBeanFactory();
//在子类中实现
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (logger.isDebugEnabled()) {
logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
}
return beanFactory;
}
其中刷新bean工厂的方法在子类AbstractRefreshableApplicationContext中实现,代码如下:
@Override
protected final void refreshBeanFactory() throws BeansException {
//如果已经有beanFactory存在,则先进行销毁
if (hasBeanFactory()) {
//销毁所有创建的bean
destroyBeans();
//关闭beanFactory
closeBeanFactory();
}
try {
//创建beanFactory
DefaultListableBeanFactory beanFactory = createBeanFactory();
//设置序列化id
beanFactory.setSerializationId(getId());
//对ioc容器进行定制化,如设置启动参数,开启注解的自动装配等
customizeBeanFactory(beanFactory);
//加载bean的定义信息(这里也是委派模式,此类中此方法为抽象方法)
loadBeanDefinitions(beanFactory);
//线程安全,修改beanFactory的值
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
首先判断是否已经有beanFactory实例,此方法内容如下:
protected final boolean hasBeanFactory() {
synchronized (this.beanFactoryMonitor) {
return (this.beanFactory != null);
}
}
上锁,避免方法执行过程中beanFactory属性的值发生变化。
紧接着,如果返回true,就调用destroyBeans方法,销毁其中注册的bean,而此方法最终追溯到源头是在继承链中父类DefaultSingletonBeanRegistry中的destroySingletons方法,内容如下:
public void destroySingletons() {
if (logger.isDebugEnabled()) {
logger.debug("Destroying singletons in " + this);
}
//将singletonsCurrentlyInDestruction标识设置为true,标识当前处于销毁bean状态
synchronized (this.singletonObjects) {
this.singletonsCurrentlyInDestruction = true;
}
String[] disposableBeanNames;
synchronized (this.disposableBeans) {
disposableBeanNames = StringUtils.toStringArray(this.disposableBeans.keySet());
}
//遍历销毁每个bean,调用destroySingleton方法,主要是调用bean的销毁方法(如果定义了的话)
for (int i = disposableBeanNames.length - 1; i >= 0; i--) {
destroySingleton(disposableBeanNames[i]);
}
//清除所有与bean相关的内容
this.containedBeanMap.clear();
this.dependentBeanMap.clear();
this.dependenciesForBeanMap.clear();
synchronized (this.singletonObjects) {
this.singletonObjects.clear();
this.singletonFactories.clear();
this.earlySingletonObjects.clear();
this.registeredSingletons.clear();
this.singletonsCurrentlyInDestruction = false;
}
}
销毁bean的逻辑就到此,紧接着调用关闭beanFactory方法:closeBeanFactory,内容如下:
@Override
protected final void closeBeanFactory() {
//内容比较简单,清空beanFactory属性值
synchronized (this.beanFactoryMonitor) {
if (this.beanFactory != null) {
this.beanFactory.setSerializationId(null);
this.beanFactory = null;
}
}
}
销毁结束后,紧接着就是创建新BeanFactory的逻辑,我们依次分析:
try {
//创建beanFactory
DefaultListableBeanFactory beanFactory = createBeanFactory();
//设置序列化id
beanFactory.setSerializationId(getId());
//对ioc容器进行定制化,如设置启动参数,开启注解的自动装配等
customizeBeanFactory(beanFactory);
//加载bean的定义信息(这里也是委派模式,此类中此方法为抽象方法)
loadBeanDefinitions(beanFactory);
//线程安全,修改beanFactory的值
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
1)createBeanFactory()
protected DefaultListableBeanFactory createBeanFactory() {
//创建一个新的DefaultListableBeanFactory
//如果有父容器,则将父容器的beanFactory作为参数传入
return new DefaultListableBeanFactory(getInternalParentBeanFactory());
}
//DefaultListableBeanFactory构造方法
public DefaultListableBeanFactory(@Nullable BeanFactory parentBeanFactory) {
//调用父类的构造函数
super(parentBeanFactory);
}
//父类构造函数内容
public AbstractAutowireCapableBeanFactory() {
super();
//设置三种接口类型为依赖注入忽略类型,目的是在bean初始化时,手动将依赖注入
ignoreDependencyInterface(BeanNameAware.class);
ignoreDependencyInterface(BeanFactoryAware.class);
ignoreDependencyInterface(BeanClassLoaderAware.class);
}
public AbstractAutowireCapableBeanFactory(@Nullable BeanFactory parentBeanFactory) {
this();
setParentBeanFactory(parentBeanFactory);
}
以上便是创建BeanFactory方法的内容,紧接着,调用beanFactory.setSerializationId,为bean工厂设置序列化id,然后是customizeBeanFactory方法,设置beanFactory参数,内容如下:
2)customizeBeanFactory()
protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
//设置是否允许bean定义覆盖
if (this.allowBeanDefinitionOverriding != null) {
beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
}
//设置是否允许循环依赖
if (this.allowCircularReferences != null) {
beanFactory.setAllowCircularReferences(this.allowCircularReferences);
}
}
3)loadBeanDefinitions(beanFactory)
beanFactory初始化完成后,就可以开始加载bean定义信息了,loadBeanDefinitions方法采用委派模式,交给子类实现,追溯一番,发现是在子类AbstractXmlApplicationContext中实现的,如下:
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
// 创建XML的bean定义读取器,并设置到容器中,后续通过此读取器读取bean定义
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's
// resource loading environment.
//为bean定义读取器设置此context的环境信息
beanDefinitionReader.setEnvironment(this.getEnvironment());
//applicationcontext本身也属于ResourceLoader,所以直接设置进去
beanDefinitionReader.setResourceLoader(this);
//设置XML解析器
beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
//此方法中将bean定义读取器的XML校验机制打开
initBeanDefinitionReader(beanDefinitionReader);
//真正加载定义的方法
loadBeanDefinitions(beanDefinitionReader);
}
首先创建XmlBeanDefinitionReader,调用构造方法,将beanFactory传入,而构造方法中只有一句:super(beanFactory),所以最终追溯到了XmlBeanDefinitionReader的父类,也就是AbstractBeanDefinitionReader。初始化了一些属性。
protected AbstractBeanDefinitionReader(BeanDefinitionRegistry registry) {
Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
this.registry = registry;
// Determine ResourceLoader to use.
// 这两个if都走的else,因为传入的beanFactory并不实现这两个接口
if (this.registry instanceof ResourceLoader) {
this.resourceLoader = (ResourceLoader) this.registry;
}
else {
this.resourceLoader = new PathMatchingResourcePatternResolver();
}
// Inherit Environment if possible
if (this.registry instanceof EnvironmentCapable) {
this.environment = ((EnvironmentCapable) this.registry).getEnvironment();
}
else {
this.environment = new StandardEnvironment();
}
}
创建完XmlBeanDefinitionReader类以后,进行一些属性设置,最后调用loadBeanDefinitions方法真正的去读取bean定义信息:
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
//获取配置定位,并解析,此方法也是委派模式,本类中并没有实现
Resource[] configResources = getConfigResources();
if (configResources != null) {
//此方法内部是循环,循环解析每个配置文件
reader.loadBeanDefinitions(configResources);
}
//获取资源位置,并解析
String[] configLocations = getConfigLocations();
if (configLocations != null) {
//loadBeanDefinitions方法其实是调用reader的父类AbstractBeanDefinitionReader的方法
//最终将String的资源转换为Resource类型,调用loadBeanDefinitions(Resource resource)
reader.loadBeanDefinitions(configLocations);
}
}
首先是getConfigResources方法,同样是委派给子类实现,追溯一番,发现是老朋友ClassPathXmlApplicationContext中实现的,而内容很简单,直接返回this.configResources,此属性是在spring启动的构造方法中根据入参解析而成的,内容嘛,就是一些配置文件的路径,如果忘记具体过程,可以返回文章开头看看哦。
如果判断配置资源不为空,则调用读取器的加载bean定义方法进行解析。最终调用如下方法:
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
Assert.notNull(encodedResource, "EncodedResource must not be null");
if (logger.isInfoEnabled()) {
logger.info("Loading XML bean definitions from "+ encodedResource.getResource());
}
//将当前需要加载的配置资源添加到集合中
Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
if (currentResources == null) {
currentResources = new HashSet<>(4);
this.resourcesCurrentlyBeingLoaded.set(currentResources);
}
//利用set元素的不重复性,判断是否多次加载
if (!currentResources.add(encodedResource)) {
throw new BeanDefinitionStoreException(
"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
}
try {
//获取配置文件的流
InputStream inputStream = encodedResource.getResource().getInputStream();
try {
InputSource inputSource = new InputSource(inputStream);
//如果需要设置编码,设置编码
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
//真正解析bean定义的位置
return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
}
finally {
inputStream.close();
}
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(
"IOException parsing XML document from " + encodedResource.getResource(), ex);
}
finally {
currentResources.remove(encodedResource);
if (currentResources.isEmpty()) {
this.resourcesCurrentlyBeingLoaded.remove();
}
}
}
逻辑清晰,最终调用的是doLoadBeanDefinitions方法,内容如下:
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
//将配置文件解析为Dom对象
Document doc = doLoadDocument(inputSource, resource);
//解析bean定义的方法
return registerBeanDefinitions(doc, resource);
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (SAXParseException ex) {
throw new XmlBeanDefinitionStoreException(resource.getDescription(),
"Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex);
}
catch (SAXException ex) {
throw new XmlBeanDefinitionStoreException(resource.getDescription(),
"XML document from " + resource + " is invalid", ex);
}
catch (ParserConfigurationException ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"Parser configuration exception parsing XML from " + resource, ex);
}
catch (IOException ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"IOException parsing XML document from " + resource, ex);
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(resource.getDescription(),
"Unexpected exception parsing XML document from " + resource, ex);
}
}
//其中,doLoadDocument方法内容如下
protected Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception {
//调用了documentLoader(DefaultDocumentLoader)的loadDocument方法
return this.documentLoader.loadDocument(inputSource, getEntityResolver(), this.errorHandler,
getValidationModeForResource(resource), isNamespaceAware());
}
@Override
public Document loadDocument(InputSource inputSource, EntityResolver entityResolver,
ErrorHandler errorHandler, int validationMode, boolean namespaceAware) throws Exception {
//主要完成工厂的创建以及属性的设置,比如XSD校验属性等,不展开细说
DocumentBuilderFactory factory = createDocumentBuilderFactory(validationMode, namespaceAware);
if (logger.isDebugEnabled()) {
logger.debug("Using JAXP provider [" + factory.getClass().getName() + "]");
}
//最终返回的为DocumentBuilderImpl实例
DocumentBuilder builder = createDocumentBuilder(factory, entityResolver, errorHandler);
//调用解析方法,最终调用的是XML11Configuration的parse方法解析文件,再通过AbstractDOMParser类的getDocument返回解析好的Document对象,具体内容不做解析
return builder.parse(inputSource);
}
获取到Document对象以后,随之调用registerBeanDefinitions方法对bean定义进行解析:
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
//创建Bean定义dom对象的解析器,为DefaultBeanDefinitionDocumentReader实例
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
//获取容器目前注册的bean数量
int countBefore = getRegistry().getBeanDefinitionCount();
//解析bean定义,documentReader为BeanDefinitionDocumentReader类型,是接口,调用registerBeanDefinitions
//方法,最终调用的是子类DefaultBeanDefinitionDocumentReader
//此处的createReaderContext是根据resource创建的一个上下文
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
//返回解析了多少新的bean定义
return getRegistry().getBeanDefinitionCount() - countBefore;
}
@Override
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
this.readerContext = readerContext;
logger.debug("Loading bean definitions");
//获取根节点
Element root = doc.getDocumentElement();
//核心方法
doRegisterBeanDefinitions(root);
}
protected void doRegisterBeanDefinitions(Element root) {
BeanDefinitionParserDelegate parent = this.delegate;
this.delegate = createDelegate(getReaderContext(), root, parent);
if (this.delegate.isDefaultNamespace(root)) {
//些许校验
String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
if (StringUtils.hasText(profileSpec)) {
String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
profileSpec,BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
if (logger.isInfoEnabled()) {
logger.info("Skipped XML bean definition file due to specified profiles [" + profileSpec +
"] not matching: " + getReaderContext().getResource());
}
return;
}
}
}
//可自定义扩展解析行为,如:预处理自定义的XML元素节点,增加灵活性
preProcessXml(root);
//解析bean定义
parseBeanDefinitions(root, this.delegate);
//可自定义扩展解析行为,如:预处理自定义的XML元素节点,增加灵活性
postProcessXml(root);
this.delegate = parent;
}
上述一连串方法调用,最终的目标为parseBeanDefinitions方法,内容如下:
//根据spring的bean规则解析dom
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
//xml文档使用了spring默认的名称空间
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) {
Element ele = (Element) node;
//此节点使用的是spring的命名空间
if (delegate.isDefaultNamespace(ele)) {
//使用spring的bean规则解析
parseDefaultElement(ele, delegate);
}
else {
//否则使用用户自定义规则解析
delegate.parseCustomElement(ele);
}
}
}
}
else {
//否则使用用户自定义规则解析
delegate.parseCustomElement(root);
}
}
关于用户自定义的名称空间,自定义的bean规则,我们不做讨论,主要来看按照spring定义的bean定义规则解析的方法:
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
//如果节点是<import>导入元素,进行导入解析
if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
importBeanDefinitionResource(ele);
}
//如果节点是<alias>别名元素,进行别名解析
else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
processAliasRegistration(ele);
}
//如果节点是<bean>bean元素,进行bean定义解析
else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
processBeanDefinition(ele, delegate);
}
//如果节点是嵌套bean信息
else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
// recurse
doRegisterBeanDefinitions(ele);
}
}
可以看到,针对各类元素标签执行不同的解析方法,我们依次分析:
//总的来说就是再次根据所提供的配置文件,再次调用XmlBeanDefinitionReader类的loadBeanDefinition方法
protected void importBeanDefinitionResource(Element ele) {
//获取资源路径,也就是import标签的resource属性值
String location = ele.getAttribute(RESOURCE_ATTRIBUTE);
//路径为空,报错
if (!StringUtils.hasText(location)) {
getReaderContext().error("Resource location must not be empty", ele);
return;
}
// Resolve system properties: e.g. "${user.dir}"
//使用系统变量解析location值
//这里的getEnvironment方法获取到的其实是AbstractApplicationContext类之前分析过的refresh准备方法:prepareRefresh中调用getEnvironment方法所创建出来的StandardEnvironment类
location = getReaderContext().getEnvironment().resolveRequiredPlaceholders(location);
Set<Resource> actualResources = new LinkedHashSet<>(4);
// Discover whether the location is an absolute or relative URI
//标识location是绝对URI还是相对URI
boolean absoluteLocation = false;
try {
absoluteLocation = ResourcePatternUtils.isUrl(location) || ResourceUtils.toURI(location).isAbsolute();
}
catch (URISyntaxException ex) {
//无法转为URI
// cannot convert to an URI, considering the location relative
// unless it is the well-known Spring prefix "classpath*:"
}
// Absolute or relative?
if (absoluteLocation) {
try {
//如果是绝对路径
int importCount = getReaderContext().getReader().loadBeanDefinitions(location, actualResources);
if (logger.isDebugEnabled()) {
logger.debug("Imported " + importCount + " bean definitions from URL location [" + location + "]");
}
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error(
"Failed to import bean definitions from URL location [" + location + "]", ele, ex);
}
}
else {
//相对路径
// No URL -> considering resource location as relative to the current file.
try {
int importCount;
//封装为相对路径资源
Resource relativeResource = getReaderContext().getResource().createRelative(location);
if (relativeResource.exists()) {
importCount = getReaderContext().getReader().loadBeanDefinitions(relativeResource);
actualResources.add(relativeResource);
}
else {
//获取ioc资源读取器的基本路径
String baseLocation = getReaderContext().getResource().getURL().toString();
//根据基本路径解析应用相对路径
importCount = getReaderContext().getReader().loadBeanDefinitions(
StringUtils.applyRelativePath(baseLocation, location), actualResources);
}
if (logger.isDebugEnabled()) {
logger.debug("Imported " + importCount + " bean definitions from relative location [" + location + "]");
}
}
catch (IOException ex) {
getReaderContext().error("Failed to resolve current resource location", ele, ex);
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error("Failed to import bean definitions from relative location [" + location + "]",
ele, ex);
}
}
Resource[] actResArray = actualResources.toArray(new Resource[actualResources.size()]);
//解析完成后,发送解析完成事件
getReaderContext().fireImportProcessed(location, actResArray, extractSource(ele));
}
这段代码中需要注意的是
location = getReaderContext().getEnvironment().resolveRequiredPlaceholders(location);
这里的getEnvironment方法获取到的其实是AbstractApplicationContext类之前分析过的refresh准备方法:prepareRefresh中调用getEnvironment方法所创建出来的StandardEnvironment类,而resolveRequiredPlaceholders方法则在其父类AbstractEnvironment中定义的,追溯一番,其实最终是我们开头分析的在解析配置文件路径时候,所提到过的PropertyPlaceholderHelper类的parseStringValue方法,此方法的逻辑就是解析提供的字符串中的${}符号,并用全局属性值替换括号中的内容,如果忘记了可以返回到setConfigLocation方法的解析部分,再品一品。
由上可得,此处作用就是解析location字符串中的${}占位符。
紧接着是对alias标签的解析方法:
//概括来说就是获取标签中的两个属性值,判断不为空,将别名注册到bean工厂的别名map中
protected void processAliasRegistration(Element ele) {
//获取alias元素中的name属性
String name = ele.getAttribute(NAME_ATTRIBUTE);
//获取alias元素中的alias属性
String alias = ele.getAttribute(ALIAS_ATTRIBUTE);
//标识属性值是否有效
boolean valid = true;
if (!StringUtils.hasText(name)) {
getReaderContext().error("Name must not be empty", ele);
valid = false;
}
if (!StringUtils.hasText(alias)) {
getReaderContext().error("Alias must not be empty", ele);
valid = false;
}
if (valid) {
try {
//将别名与本名注册到bean工厂的别名map中
getReaderContext().getRegistry().registerAlias(name, alias);
}
catch (Exception ex) {
getReaderContext().error("Failed to register alias '" + alias +
"' for bean with name '" + name + "'", ele, ex);
}
//发布解析完成alias节点的消息
getReaderContext().fireAliasRegistered(name, alias, extractSource(ele));
}
}
然后是解析bean标签的方法:
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
//BeanDefinitionHolder是beanDefinition类的封装类
BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
if (bdHolder != null) {
bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
try {
// Register the final decorated instance.
//向ioc中注册解析到的bean定义
BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error("Failed to register bean definition with name '" +
bdHolder.getBeanName() + "'", ele, ex);
}
// Send registration event.
//发布注册信息
getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
}
}
其中重点就是parseBeanDefinitionElement方法,是BeanDefinitionDelegate中定义的,内容如下:
@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) {
return parseBeanDefinitionElement(ele, null);
}
@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
//获取id与name
String id = ele.getAttribute(ID_ATTRIBUTE);
String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
List<String> aliases = new ArrayList<>();
//如果name 中有,;分割,则解析为name数组
if (StringUtils.hasLength(nameAttr)) {
String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
aliases.addAll(Arrays.asList(nameArr));
}
String beanName = id;
//如果id为空并且别名数组不为空,则移除别名数组中的第一个别名当作beanName
if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
beanName = aliases.remove(0);
if (logger.isDebugEnabled()) {
logger.debug("No XML 'id' specified - using '" + beanName +
"' as bean name and " + aliases + " as aliases");
}
}
if (containingBean == null) {
//检查此bean中的名称,别名是否重复
//如果没重复,就加入到此次解析的已使用名称集合中
//方法内容简单,不再详细解析
checkNameUniqueness(beanName, aliases, ele);
}
AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
if (beanDefinition != null) {
if (!StringUtils.hasText(beanName)) {
try {
if (containingBean != null) {
//生成一个id(根据class名称或者parent名称或者factoryBean名称)内容不难,不展开介绍
beanName = BeanDefinitionReaderUtils.generateBeanName(
beanDefinition, this.readerContext.getRegistry(), true);
}
else {
//最终与上面生成beanName的方法调用的一样,只不过true变为false
beanName = this.readerContext.generateBeanName(beanDefinition);
// 给别名中添加类名
String beanClassName = beanDefinition.getBeanClassName();
if (beanClassName != null &&
beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() &&
!this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
aliases.add(beanClassName);
}
}
if (logger.isDebugEnabled()) {
logger.debug("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);
//最终返回一个BeanDefinitionHolder对象
return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
}
return null;
}
其中的parseBeanDefinitionElement方法内容如下:
@Nullable
public AbstractBeanDefinition parseBeanDefinitionElement(
Element ele, String beanName, @Nullable BeanDefinition containingBean) {
//将当前解析的bean定义加入到缓存中,解析完成再移除
//此处的BeanEntity类只有一个属性,就是bean名称
this.parseState.push(new BeanEntry(beanName));
//解析bean标签的class属性
String className = null;
if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
}
//解析bean标签的parent属性
String parent = null;
if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
parent = ele.getAttribute(PARENT_ATTRIBUTE);
}
try {
//创建beanDefinition对象
AbstractBeanDefinition bd = createBeanDefinition(className, parent);
//解析bean标签中的各种属性
parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
//设置bean描述
bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
//解析bean的元属性meta标签
parseMetaElements(ele, bd);
//解析bean的lookup-method标签
parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
//解析bean的replaced-method标签
parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
//解析bean的constructor-arg标签
parseConstructorArgElements(ele, bd);
//解析bean的property标签
parsePropertyElements(ele, bd);
//解析bean的qualifier标签
parseQualifierElements(ele, bd);
//设置bean定义的来源
bd.setResource(this.readerContext.getResource());
//此处的最终调用为NullSourceExtractor类的extractSource方法,返回的是null
bd.setSource(extractSource(ele));
return bd;
}
catch (ClassNotFoundException ex) {
error("Bean class [" + className + "] not found", ele, ex);
}
catch (NoClassDefFoundError err) {
error("Class that bean class [" + className + "] depends on not found", ele, err);
}
catch (Throwable ex) {
error("Unexpected failure during bean definition parsing", ele, ex);
}
finally {
this.parseState.pop();
}
return null;
}
//=========================创建bean定义的方法
protected AbstractBeanDefinition createBeanDefinition(@Nullable String className, @Nullable String parentName)
throws ClassNotFoundException {
return BeanDefinitionReaderUtils.createBeanDefinition(
parentName, className, this.readerContext.getBeanClassLoader());
}
public static AbstractBeanDefinition createBeanDefinition(
@Nullable String parentName, @Nullable String className, @Nullable ClassLoader classLoader) throws ClassNotFoundException {
GenericBeanDefinition bd = new GenericBeanDefinition();
bd.setParentName(parentName);
if (className != null) {
if (classLoader != null) {
bd.setBeanClass(ClassUtils.forName(className, classLoader));
}
else {
bd.setBeanClassName(className);
}
}
return bd;
}
//================================解析bean标签属性的方法
public AbstractBeanDefinition parseBeanDefinitionAttributes(Element ele, String beanName,
@Nullable BeanDefinition containingBean, AbstractBeanDefinition bd) {
//检查bean标签是否有旧版本的属性singleton,因为新版本已经替换为scope
if (ele.hasAttribute(SINGLETON_ATTRIBUTE)) {
error("Old 1.x 'singleton' attribute in use - upgrade to 'scope' declaration", ele);
}
//解析scope属性的值
else if (ele.hasAttribute(SCOPE_ATTRIBUTE)) {
bd.setScope(ele.getAttribute(SCOPE_ATTRIBUTE));
}
//如果有包含的bean定义,则取包含bean定义的scope值
else if (containingBean != null) {
// Take default from containing bean in case of an inner bean definition.
bd.setScope(containingBean.getScope());
}
//解析abstract属性值
if (ele.hasAttribute(ABSTRACT_ATTRIBUTE)) {
bd.setAbstract(TRUE_VALUE.equals(ele.getAttribute(ABSTRACT_ATTRIBUTE)));
}
//解析lazy-init属性值值
String lazyInit = ele.getAttribute(LAZY_INIT_ATTRIBUTE);
if (DEFAULT_VALUE.equals(lazyInit)) {
lazyInit = this.defaults.getLazyInit();
}
bd.setLazyInit(TRUE_VALUE.equals(lazyInit));
//解析autowire模式
String autowire = ele.getAttribute(AUTOWIRE_ATTRIBUTE);
bd.setAutowireMode(getAutowireMode(autowire));
//解析bean依赖
if (ele.hasAttribute(DEPENDS_ON_ATTRIBUTE)) {
String dependsOn = ele.getAttribute(DEPENDS_ON_ATTRIBUTE);
bd.setDependsOn(StringUtils.tokenizeToStringArray(dependsOn, MULTI_VALUE_ATTRIBUTE_DELIMITERS));
}
//解析此bean是否配置了首要匹配,如果配置了,容器中存在同类型的bean,优先选此bean
String autowireCandidate = ele.getAttribute(AUTOWIRE_CANDIDATE_ATTRIBUTE);
if ("".equals(autowireCandidate) || DEFAULT_VALUE.equals(autowireCandidate)) {
String candidatePattern = this.defaults.getAutowireCandidates();
//一般是空
if (candidatePattern != null) {
String[] patterns = StringUtils.commaDelimitedListToStringArray(candidatePattern);
bd.setAutowireCandidate(PatternMatchUtils.simpleMatch(patterns, beanName));
}
}
else {
bd.setAutowireCandidate(TRUE_VALUE.equals(autowireCandidate));
}
//解析primary属性
if (ele.hasAttribute(PRIMARY_ATTRIBUTE)) {
bd.setPrimary(TRUE_VALUE.equals(ele.getAttribute(PRIMARY_ATTRIBUTE)));
}
//解析init-method方法
if (ele.hasAttribute(INIT_METHOD_ATTRIBUTE)) {
String initMethodName = ele.getAttribute(INIT_METHOD_ATTRIBUTE);
bd.setInitMethodName(initMethodName);
}
//如果有指定默认的init方法名,则使用默认的init方法名
else if (this.defaults.getInitMethod() != null) {
bd.setInitMethodName(this.defaults.getInitMethod());
bd.setEnforceInitMethod(false);
}
//解析destroy-method属性值
if (ele.hasAttribute(DESTROY_METHOD_ATTRIBUTE)) {
String destroyMethodName = ele.getAttribute(DESTROY_METHOD_ATTRIBUTE);
bd.setDestroyMethodName(destroyMethodName);
}
//如果有指定默认的destroy方法名,则使用默认的destroy方法名
else if (this.defaults.getDestroyMethod() != null) {
bd.setDestroyMethodName(this.defaults.getDestroyMethod());
bd.setEnforceDestroyMethod(false);
}
//解析factory-method属性
if (ele.hasAttribute(FACTORY_METHOD_ATTRIBUTE)) {
bd.setFactoryMethodName(ele.getAttribute(FACTORY_METHOD_ATTRIBUTE));
}
//解析factory-bean属性
if (ele.hasAttribute(FACTORY_BEAN_ATTRIBUTE)) {
bd.setFactoryBeanName(ele.getAttribute(FACTORY_BEAN_ATTRIBUTE));
}
return bd;
}
至此,整个bean工厂刷新以及解析配置文件的过程就分析完成了,这一部分就到这里,马上编写下一部分。具体内容为refresh后续的逻辑。
结语:长路漫漫,各位最好能够跟着文章,打开源码,手动追一下逻辑,能够加深对源码的理解,碰到逻辑复杂的部分,拆分成一行一行的读,莫要因为长篇大论的源码而胆怯,加油!