1. 类的层级图
- DefaultResourceLoader
- AbstractApplicationContext
- AbstractRefreshableApplicationContext
- AbstractRefreshableConfigApplicationContext
- AbstractXmlApplicationContext
- ClassPathXmlApplicationContext
2. spring容器启动入口,执行成功容器就启动完成了
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
3. 进入ClassPathXmlApplicationContext类的构造方法
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
super(parent);
//初始化配置文件xml的位置,解析configLocations,即.xml文件
//方法实现所在位置:父类 AbstractRefreshableConfigApplicationContext
setConfigLocations(configLocations);
if (refresh) {
//spring容器启动的主流程(*****重要*****)
//方法实现所在位置:父类 AbstractApplicationContext
refresh();
}
}
//此方法所在类:AbstractRefreshableConfigApplicationContext
public void setConfigLocations(@Nullable String... locations) {
if (locations != null) {
Assert.noNullElements(locations, "Config locations must not be null");
//将xml文件维护在configLocations属性上
this.configLocations = new String[locations.length];
for (int i = 0; i < locations.length; i++) {
//resolvePath方法涉及模糊匹配,先不看
this.configLocations[i] = resolvePath(locations[i]).trim();
}
}
else {
this.configLocations = null;
}
}
4. spring容器启动的核心方法refresh();
/**
* 该方法是spring容器初始化的核心方法。
* 是spring容器初始化的核心流程,是一个典型的父类模板设计模式的运用
* 根据不同的上下文对象,会掉到不同的上下文对象子类方法中
*
* 核心上下文子类有:
* ClassPathXmlApplicationContext
* FileSystemXmlApplicationContext
* AnnotationConfigApplicationContext
* EmbeddedWebApplicationContext(springboot)
*/
@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.
/*
* 1、创建BeanFactory对象
* 2、xml解析
* 传统标签解析:bean、import等
* 自定义标签解析:例如:<context:component-scan base-package="com.xiangxue.jack"/>
* 自定义标签解析流程:
* a、根据当前解析标签的头信息找到对应的namespaceUri
* b、加载spring所以jar中的spring.handlers文件。并建立映射关系
* c、根据namespaceUri从映射关系中找到对应的实现了NamespaceHandler接口的类
* d、调用类的init方法,init方法是注册了各种自定义标签的解析类
* e、根据namespaceUri找到对应的解析类,然后调用paser方法完成标签解析
* 3、把解析出来的xml标签信息封装成BeanDefinition对象
*/
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
//钩子方法,由子类实现
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
// 注册beanFactoryPostProcessor对象
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
// 注册beanPostProcessor实例,在bean创建的时候实现拦截
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
// 国际化,重要程度2
initMessageSource();
// Initialize event multicaster for this context.
// 初始化时间管理类
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
//此方法着重理解模板设计模式,因为在springboot中,这个方法是用来做内嵌tomcat启动的
onRefresh();
// Check for listener beans and register them.
// 往时间管理类中注册事件类
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
/*
* 在之前已经实例化了BeanFactoryPostProcessor以及beanPostProcessor
* 下面开始实例化剩下的所有非懒加载的单例对象
*/
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.
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();
}
}
}
5. obtainFreshBeanFactory()辨析
//父类AbstractApplicationContext方法
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
//核心方法,必须读,重要程度:5
//此方法是钩子方法,在子类中实现
refreshBeanFactory();
return getBeanFactory();
}
6. refreshBeanFactory()辨析
//AbstractRefreshableApplicationContext(继承AbstractApplicationContext)
protected final void refreshBeanFactory() throws BeansException {
//如果BeanFactory不为空,则清除BeanFactory和里面的实例
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
//创建DefaultListableBeanFactory
DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId());
//设置是否可以循环依赖 allowCircularReferences
//是否允许使用相同名称重新注册不同的bean实现.
customizeBeanFactory(beanFactory);
//解析xml,并把xml中的标签封装成BeanDefinition对象,调用子类方法
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
7. loadBeanDefinitions()辨析
//AbstractXmlApplicationContext类(继承AbstractRefreshableConfigApplicationContext)
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
//创建xml的解析器,这里是一个委托模式
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's
// resource loading environment.
beanDefinitionReader.setEnvironment(this.getEnvironment());
//这里传一个this进去,因为ApplicationContext是实现了ResourceLoader接口的
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);
//主要看这个方法 重要程度 5
loadBeanDefinitions(beanDefinitionReader);
}
//当前类
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
Resource[] configResources = getConfigResources();
if (configResources != null) {
reader.loadBeanDefinitions(configResources);
}
//获取需要加载的xml配置文件
// 在第一步classPathXmlApplicationContext构造器中,已经初始化了configLocation
String[] configLocations = getConfigLocations();
if (configLocations != null) {
reader.loadBeanDefinitions(configLocations);
}
}
8. 委托给reader来解析 reader.loadBeanDefinitions()
//AbstractBeanDefinitionReader类中方法
public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
Assert.notNull(locations, "Location array must not be null");
int count = 0;
//配置文件有多个,加载多个配置文件,循环解析
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 {
//之前AbstractXmlApplicationContext类中loadBeanDefinitions()方法中
//beanDefinitionReader.setResourceLoader(this);传入的this,用于此处拿到上下文对象
ResourceLoader resourceLoader = getResourceLoader();
if (resourceLoader == null) {
throw new BeanDefinitionStoreException(
"Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
}
if (resourceLoader instanceof ResourcePatternResolver) {
// Resource pattern matching available.
try {
//把字符串类型的xml文件路径,形如:classpath*:user/**/*-context.xml,转换成Resource对象类型,其实就是用流
//的方式加载配置文件,然后封装成Resource对象,不重要,可以不看
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
//主要看这个方法 ** 重要程度 5
//调用当前类的方法-重载
int count = loadBeanDefinitions(resources);
if (actualResources != null) {
Collections.addAll(actualResources, resources);
}
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.
// 这个Resource仅仅能够加载单个的绝对路径的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;
}
}
public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
Assert.notNull(resources, "Resource array must not be null");
int count = 0;
for (Resource resource : resources) {
//模板设计模式,调用到子类中的方法
count += loadBeanDefinitions(resource);
}
return count;
}
9. EncodedResource带编码的对Resource对象的封装,将inputSource对象封装成Documet对象
//子类XmlBeanDefinitionReader中的方法(继承AbstractBeanDefinitionReader)
//对接口BeanDefinitionReader的实现
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
//EncodedResource带编码的对Resource对象的封装
return loadBeanDefinitions(new EncodedResource(resource));
}
//从资源Resource中拿到输入流InputStream,维护到InputSource中,然后调用doLoaderBeanDefinitions解析
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);
}
Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
if (currentResources == null) {
currentResources = new HashSet<>(4);
this.resourcesCurrentlyBeingLoaded.set(currentResources);
}
if (!currentResources.add(encodedResource)) {
throw new BeanDefinitionStoreException(
"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
}
try {
//获取Resource对象中的xml文件流对象
InputStream inputStream = encodedResource.getResource().getInputStream();
try {
//InputSource是jdk中的sax xml文件解析对象
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
//主要看这个方法 ** 重要程度 5- *****加载beanDefinition*****
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();
}
}
}
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
//把inputSource 封装成Document文件对象,这是jdk的API
Document doc = doLoadDocument(inputSource, resource);
//主要看这个方法,根据解析出来的document对象,拿到里面的标签元素封装成BeanDefinition
int count = registerBeanDefinitions(doc, resource);
if (logger.isDebugEnabled()) {
logger.debug("Loaded " + count + " bean definitions from " + resource);
}
return count;
}
//异常此处略去......
}
10. 解析为document对象,之后就要注册beanDefinition了
- 在spring的加载过程中,BeanDefinition是一个重要的数据结构,它是在创建对象之前,对象数据的一种存在形式
- xml —— beanDefinition ——bean 从xml配置bean,到解析xml创建 beanDefinition,到从beanDefinition实例为 bean对象,这是一个流程。
//XmlBeanDefinitionReader类
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
//又来一记委托模式,BeanDefinitionDocumentReader委托这个类进行document的解析
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
int countBefore = getRegistry().getBeanDefinitionCount();
//主要看这个方法,createReaderContext(resource) XmlReaderContext上下文,封装了XmlBeanDefinitionReader对象
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
return getRegistry().getBeanDefinitionCount() - countBefore;
}
11. 通过上一个委托进行注册beanDefinition
- spring将xml文件封装成了Document对象,然后委托给BeanDefinitionDocumentReader来解析
//DefaultBeanDefinitionDocumentReader(实现BeanDefinitionDocumentReader接口)
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
this.readerContext = readerContext;
//主要看这个方法,把root节点传进去
//注册beanDefinition,将document中root元素传入
doRegisterBeanDefinitions(doc.getDocumentElement());
}
//委托给document的解析器,入参为document的根元素,就是spring-context.xml的beans元素:
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);
// 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);
//主要看这个方法,标签具体解析过程
//具体的解析document对象,注册beanDefinition的逻辑在这里实现
parseBeanDefinitions(root, this.delegate);
postProcessXml(root);
this.delegate = parent;
}
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
//判断根元素的命名空间是否为空或者是 xmlns="http://www.springframework.org/schema/beans"
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;
if (delegate.isDefaultNamespace(ele)) {
//默认标签解析,bean,import等
parseDefaultElement(ele, delegate);
}
else {
//自定义标签解析, context等
// a、根据当前解析标签的头信息找到对应的namespaceUri
// b、加载spring所以jar中的spring.handlers文件。并建立映射关系
// c、根据namespaceUri从映射关系中找到对应的实现了NamespaceHandler接口的类
// d、调用类的init方法,init方法是注册了各种自定义标签的解析类
// e、根据namespaceUri找到对应的解析类,然后调用paser方法完成标签解析
delegate.parseCustomElement(ele);//***********重点
}
}
}
}
else {
delegate.parseCustomElement(root);
}
}
总结:
- 上述是启动spring流程的第一步,解析配置文件,当然我们这里是以xml配置的方式分析。也可能是注解配置的方法,后续再来分析注解方式。
- 创建applicationContext对象,将xml文件的路径维护到AbstractRefreshableApplicationContext的属性上
- refresh启动spring流程,这里是spring启动的核心流程
- 第一步 obtainBeanFactory ,这这个方法里,会创建bean工厂,加载xml文件,委托给XmlBeanDefinitionReader解析
- XmlBeanDefinitionReader 将xml字符串路径封装为Resource对象,再转为InputStream流,最后把输入流生成Document对象,然后委托给BeanDefinitionDocumentReader解析。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。