Spring框架IOC的源码阅读[上]

写在前面的话,之前对Spring也仅仅会用的程度,偶然朋友提到过想实现Spring的IOC和AOP功能,看了git上面tiny-spring的实现,前辈的思路很清晰,于是便有了基于当前Spring最新版本Spring-5.1.4.RELEASE源码阅读和仿写的想法。

首先我们看看使用官方框架IOC如何使用

// 1.读取配置
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("simpleioc.xml");
// 2.获取bean
HelloWorldService helloWorldService = (HelloWorldService) applicationContext.getBean("helloWorldService");
// 3.用bean打工
helloWorldService.playWork();

简单来说三部曲

  • 1.读取配置
  • 2.获取bean
  • 3.用bean打工

IOC源码读取配置追踪

先来看一下ClassPathXmlApplicationContext类图
Spring框架IOC的源码阅读[上]_第1张图片
很明显 ClassPathXmlApplicationContext基于BeanFactory接口扩展而来,ResourceLoader接口没什么好说的(去搞资源文件的,不展开介绍)

1.IOC是怎么读取配置的

先看看ClassPathXmlApplicationContext的构造器

public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContext {
@Nullable
	private Resource[] configResources;
	...省略部分源码...
	// 这是我们上面例子跳转进去的构造,传入一个配置路径
	public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
		this(new String[] {configLocation}, true, null);
	}
	// 看看重载的构造方法里面有个setConfigLocations,
	// 那肯定就是设置配置路径了
	// 还有个refresh方法
	public ClassPathXmlApplicationContext(
			String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
			throws BeansException {

		super(parent);
		setConfigLocations(configLocations);
		if (refresh) {
			refresh();
		}
	}
}

两个核心方法,一个设置配置、一个刷新的方法

2.这里我们着重看下refresh方法

public abstract class AbstractApplicationContext extends DefaultResourceLoader
		implements ConfigurableApplicationContext {

    @Override
    public void refresh() throws BeansException, IllegalStateException {
        // startupShutdownMonitor就是个同步锁对象、不用管
    	synchronized (this.startupShutdownMonitor) {
    		// 1.刷新前的一些准备工作
    		prepareRefresh();
    
    		// 2.告知子类刷新内部的bean工厂
    		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
            
    		// 3.上下文的内部工厂准备工作
    		prepareBeanFactory(beanFactory);
    
    		try {
    			// 4.允许在上下文子类中对bean工厂进行后处理
    			postProcessBeanFactory(beanFactory);
    
    			// 5.在上下文中调用注册为bean的工厂处理器
    			invokeBeanFactoryPostProcessors(beanFactory);
    
    			// 6.注册拦截bean创建的bean处理器
    			registerBeanPostProcessors(beanFactory);
    
    			// 7.初始化此上下文的消息源
    			initMessageSource();
    
    			// 8.初始化此上下文的事件多播器
    			initApplicationEventMulticaster();
    
    			// 9.在特定的上下文子类中初始化其他特殊bean
    			onRefresh();
    
    			// 10.检查监听器bean并注册它们
    			registerListeners();
    
    			// 11.实例化所有剩余(非延迟初始化)单例
    			finishBeanFactoryInitialization(beanFactory);
    
    			// 12.最后一步:发布相应的事件
    			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();
    		}
    	}
    }
}

草图

Spring框架IOC的源码阅读[上]_第2张图片

refresh方法有12个步骤、我们主要研究一下obtainFreshBeanFactory(因为它是bean初始化的硬核)

2.1 先通过时序图了解一下加载bean初始化代码的流程(省略了一些中间类)

Spring框架IOC的源码阅读[上]_第3张图片
(1)resource定位,解析定义bean的xml文件
(2)将(1)的解析结果转成BeanDifinition
(3)将(2)的结果往IOC容器map进行put操作

2.1.1 resource定位、解析定义bean的xml文件

  • 设置配置路径属性
org.springframework.context.support.AbstractRefreshableConfigApplicationContext#setConfigLocations

2.1.2 将(1)的解析结果转成BeanDifinition

  • XmlBeanDefinitionReader.loadBeanDefinitions 加载configResources
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);
		}
}
  • XmlBeanDefinitionReader.doLoadBeanDefinitions 将Resource解析成Document
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
		throws BeanDefinitionStoreException {
	try {
		Document doc = doLoadDocument(inputSource, resource);
		int count = registerBeanDefinitions(doc, resource);
		if (logger.isDebugEnabled()) {
			logger.debug("Loaded " + count + " bean definitions from " + resource);
		}
		return count;
	}
	...
}
  • DefaultBeanDefinitionDocumentReader#doRegisterBeanDefinitions 方法里面的parseBeanDefinitions对Document解析成BeanDifinition
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);
	parseBeanDefinitions(root, this.delegate);
	postProcessXml(root);
	this.delegate = parent;
}
// 解析doc
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) {
				Element ele = (Element) node;
				if (delegate.isDefaultNamespace(ele)) {
					parseDefaultElement(ele, delegate);
				}
				else {
					delegate.parseCustomElement(ele);
				}
			}
		}
	}
	else {
		delegate.parseCustomElement(root);
	}
}
// parseDefaultElement#processBeanDefinition 实际的解析BeanDefinition操作
... parseDefaultElement方法省略
/**
 * Process the given bean element, parsing the bean definition
 * and registering it with the registry.
 */
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
	BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
	if (bdHolder != null) {
		bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
		try {
			// Register the final decorated instance.
			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));
	}
}

2.1.3 将(2)的结果往IOC容器map进行put操作

  • DefaultListableBeanFactory#registerBeanDefinition BeanDefinition赋值操作
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");

	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 + "]");
			}
		}
		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);
				List updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
				updatedDefinitions.addAll(this.beanDefinitionNames);
				updatedDefinitions.add(beanName);
				this.beanDefinitionNames = updatedDefinitions;
				if (this.manualSingletonNames.contains(beanName)) {
					Set updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
					updatedSingletons.remove(beanName);
					this.manualSingletonNames = updatedSingletons;
				}
			}
		}
		else {
			// Still in startup registration phase
			this.beanDefinitionMap.put(beanName, beanDefinition);
			this.beanDefinitionNames.add(beanName);
			this.manualSingletonNames.remove(beanName);
		}
		this.frozenBeanDefinitionNames = null;
	}

	if (existingDefinition != null || containsSingleton(beanName)) {
		resetBeanDefinition(beanName);
	}
}

关于getBean的流程下一章节介绍

你可能感兴趣的:(Java,Java,Spring)