Spring IOC源码分析(上)

在看源码之前,我们先明白一个问题
为什么要看Spring源码?
1.解决在使用Spring框架时,出现的一些莫名其妙的问题。
2.体会框架作者的设计思路,理解用到的设计模式。
3.是砸门程序员必须迈过的坎,面试经常问。

分析的入口就是ClassPathXmlApplicationContext有个构造方法

public ClassPathXmlApplicationContext(
			String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
			throws BeansException {

		super(parent);
		setConfigLocations(configLocations);
		if (refresh) {
			//逻辑就在这个方法里面
			refresh();
		}
	}
	

如果是注解上下文对象AnnotationConfigApplicationContext,最终也是走的refresh方法,只是多了一步注册注解bean。

public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
		this();
		register(annotatedClasses);
		refresh();
	}

接下来,就是重量级的方法了AbstractApplicationContext -> refresh()方法

	// 完成IoC容器的创建及初始化工作
	@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
            // 1: 刷新预处理逻辑
			prepareRefresh();
			
			//重点步骤
            // 2.1 创建IoC容器(DefaultListableBeanFactory)
            // 2.2 加载解析XML文件(最终存储到Document对象中)
            // 2.3读取Document对象,并完成BeanDefinition的加载和注册工作
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            // 3: 对beanFactory设置一些公共属性
			prepareBeanFactory(beanFactory);

			try {
                //  4: 钩子函数,空实现
				postProcessBeanFactory(beanFactory);

				//  5: 调用BeanFactoryPostProcessor后置处理器对BeanDefinition处理(实现了BeanFactoryPostProcessor接口的类)
                invokeBeanFactoryPostProcessors(beanFactory);

				//  6: 注册BeanPostProcessor后置处理器(实现了BeanPostProcessor接口的类)
                registerBeanPostProcessors(beanFactory);

				//  7: 初始化一些消息源(比如处理国际化的i18n等消息源,其实就是往beanFactory中注册bean)
                initMessageSource();

				//  8: 初始化事件广播器(往beanFactory中注册bean)
                initApplicationEventMulticaster();

				//  9: 初始化一些特殊的bean(ThemeSource 在某些情况下没有找到bean,会采用这里注册的bean)
                onRefresh();

				// 10: 注册监听器(实现了ApplicationListener接口)
                registerListeners();
				
				//重点步骤
				// 11: 实例化剩余的单例bean(非懒加载方式)
                // 注意事项:Bean的IoC、DI和AOP都是发生在此步骤
                finishBeanFactoryInitialization(beanFactory);

				// 12:容器初始化完成,加上一些生命周期逻辑,发布完成事件
                finishRefresh();
			}

			catch (BeansException ex) {
				if (logger.isWarnEnabled()) {
					logger.warn("Exception encountered during context initialization - " +
							"cancelling refresh attempt: " + ex);
				}

				//如果bean实现了DisposableBean,会调用
				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();
			}
		}
	}

整个刷新步骤有12大步,下面主要分析第2,11两个重要步骤的源码。其它步骤大家可以自行脑补。

下面就来看上诉第二步:ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();创建ioc容器,完成beanDefinition的加载和注册

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
		// 主要是通过该方法完成IoC容器的刷新
		refreshBeanFactory();
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		if (logger.isDebugEnabled()) {
			logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
		}
		return beanFactory;
	}

先看refreshBeanFactory()方法

@Override
	protected final void refreshBeanFactory() throws BeansException {
		// 如果之前有IoC容器,则销毁
    	if (hasBeanFactory()) {
			destroyBeans();
			closeBeanFactory();
		}
		try {
       		// 创建IoC容器,也就是DefaultListableBeanFactory
			DefaultListableBeanFactory beanFactory = createBeanFactory();
			beanFactory.setSerializationId(getId());
			// 设置工厂属性:是否允许BeanDefinition覆盖和是否允许循环依赖
			customizeBeanFactory(beanFactory);
            // 加载bean定义,当前类这个方法是个abstract方法
            //下面看这个方法
			loadBeanDefinitions(beanFactory);
			synchronized (this.beanFactoryMonitor) {
				this.beanFactory = beanFactory;
			}
		}
		catch (IOException ex) {
			throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
		}
	}

由AbstractXmlApplicationContext -> 实现方法 loadBeanDefinitions()

@Override
	protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
		// 创建一个BeanDefinition阅读器,用于读取和加载beanDefinition
		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

		beanDefinitionReader.setEnvironment(this.getEnvironment());
		beanDefinitionReader.setResourceLoader(this);
		beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

		//设置reader的validate
		initBeanDefinitionReader(beanDefinitionReader);
	
		// 委托给beanDefinitionReader去加载BeanDefinition
		//下面看这个方法
		loadBeanDefinitions(beanDefinitionReader);
	}

     protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
		// 获取资源的定位
		//获取的是ClassPathXmlApplicationContext类的 configResources属性值
		Resource[] configResources = getConfigResources();
		if (configResources != null) {
			// XML B调用其父类AbstractBeanDefinitionReader读取定位的资源
			reader.loadBeanDefinitions(configResources);
		}
		// 如果子类中获取的资源定位为空,则获取FileSystemXmlApplicationContext构造方法中setConfigLocations方法设置的资源
		String[] configLocations = getConfigLocations();
		if (configLocations != null) {
			// XML 调用其父类AbstractBeanDefinitionReader读取定位的资源
			reader.loadBeanDefinitions(configLocations);
		}
	}

下面继续看reader.loadBeanDefinitions(configLocations)方法
调用的是AbstractBeanDefinitionReader -> loadBeanDefinitions方法

@Override
	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 {
		ResourceLoader resourceLoader = getResourceLoader();
		if (resourceLoader == null) {
			throw new BeanDefinitionStoreException(
					"Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
		}

		if (resourceLoader instanceof ResourcePatternResolver) {
			try {
				Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
				//继续看这个方法
				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 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;
		}
	}
	
	@Override
	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;
	}

这里调用的是XmlBeanDefinitionReader - >loadBeanDefinitions

@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);
		}

		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 {
			InputStream inputStream = encodedResource.getResource().getInputStream();
			try {
				InputSource inputSource = new InputSource(inputStream);
				if (encodedResource.getEncoding() != null) {
					inputSource.setEncoding(encodedResource.getEncoding());
				}
				//继续进这个方法
				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 {
			//将resource转化为了Document对象
			Document doc = doLoadDocument(inputSource, resource);
			//终于看到注册bean的方法了,进去
			int count = registerBeanDefinitions(doc, resource);
			if (logger.isDebugEnabled()) {
				logger.debug("Loaded " + count + " bean definitions from " + resource);
			}
			return count;
		}//删除了后面的catch
	}

	public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
		//创建documentReader
		BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
		//记录之前bean数量
		int countBefore = getRegistry().getBeanDefinitionCount();
		//进去看看
		documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
		//用现在的 - 之前的 = 本次加载的bean数量
		return getRegistry().getBeanDefinitionCount() - countBefore;
	}

上面的documentReader.registerBeanDefinitions()方法
进入到了DefaultBeanDefinitionDocumentReader -> registerBeanDefinitions 方法

@Override
	public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
		this.readerContext = readerContext;
		doRegisterBeanDefinitions(doc.getDocumentElement());
	}

		@SuppressWarnings("deprecation")  // for Environment.acceptsProfiles(String...)
	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.
		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;
	}
	
	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);
		}
	}

		private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
		if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {//import
			importBeanDefinitionResource(ele);
		}
		else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {//alias
			processAliasRegistration(ele);
		}
		else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {//bean
			//下面解析bean标签
			processBeanDefinition(ele, delegate);
		}
		else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {//beans
			// recurse
			doRegisterBeanDefinitions(ele);
		}
	}
	
	protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
		//解析出来了beanName  beanDefinition alias等
		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
		if (bdHolder != null) {
			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
			try {
				// 看这个 注册方法
				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));
		}
	}

调用的是BeanDefinitionReaderUtils.registerBeanDefinition()方法

public static void registerBeanDefinition(
			BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
			throws BeanDefinitionStoreException {

		// 取出beanName和对应的beanDefinition注册
		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) {
				//注册beanName 和对应的别名
				registry.registerAlias(beanName, alias);
			}
		}
	}

registry.registerBeanDefinition()方法
调用的是DefaultListableBeanFactory -> registerBeanDefinition方法

	@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");

		if (beanDefinition instanceof AbstractBeanDefinition) {
			try {
				((AbstractBeanDefinition) beanDefinition).validate();
			}
		}

		BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
		if (existingDefinition != null) {
			if (!isAllowBeanDefinitionOverriding()) {//已经存在beanDefinition,不允许覆盖bean就报错
				throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
			}
			//中间删除了一下不重要的源码
			//到这,表示bean已经存在了,直接覆盖
			//private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256); 其实就是个
			this.beanDefinitionMap.put(beanName, beanDefinition);
		}
		else {
			if (hasBeanCreationStarted()) {//判断是否有bean正在创建
				// Cannot modify startup-time collection elements anymore (for stable iteration)
				//这个时候不能修改集合元素
				//这个地址加锁,应该是为了下面的list扩容吧
				synchronized (this.beanDefinitionMap) {
					this.beanDefinitionMap.put(beanName, beanDefinition);
					//不是很明白为什么注册bean,就创建一个list,然后复制到新的list
					List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
					updatedDefinitions.addAll(this.beanDefinitionNames);
					updatedDefinitions.add(beanName);
					//private volatile List<String> beanDefinitionNames = new ArrayList<>(256);
					this.beanDefinitionNames = updatedDefinitions;
					//里面用Set去重了
					removeManualSingletonName(beanName);
				}
			}
			else {//没有创建的就直接put
				// Still in startup registration phase
				this.beanDefinitionMap.put(beanName, beanDefinition);
				this.beanDefinitionNames.add(beanName);
				removeManualSingletonName(beanName);
			}
			this.frozenBeanDefinitionNames = null;
		}

		if (existingDefinition != null || containsSingleton(beanName)) {
			//重置beanDefinition
			resetBeanDefinition(beanName);
		}
	}

到这,第2步的主要流程算是走完了。
主要流程就是:加载配置文件,解析bean,加载bean,生成BeanDefinition对象,存放到了DefaultListableBeanFactory的beanDefinitionsMap<beanname,beanDefinition>中。

发布了42 篇原创文章 · 获赞 29 · 访问量 2538

猜你喜欢

转载自blog.csdn.net/qq_32314335/article/details/103622693
今日推荐