• Spring源码(一)IOC之ClassPathXmlApplicationContext


    1.前言

    手写ClassPathXmlApplicationContext
    在没手写一遍之前,看了十多次ClassPathXmlApplicationContext创建Bean过程,刚开始学习Spring在没有引导的情况下,虽然有收获,抓不住Spring核心,建议初学spring最好手写一遍,了解每个类、接口负责什么功能
    由于Spring类较多,只列举个人认为关键部分,具体细节需要自己体会

    代码

    	ApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
    	Person person = (Person) ctx.getBean("person");
    
    • 1
    • 2

    xml配置

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
        <bean id="person" class="domain.Person">
    		<property name="name" value="wangwu"></property>
    		<property name="age" value="18"></property>
    	</bean>
        <bean id="person1" class="domain.Person">
    		<property name="name" value="list"></property>
    		<property name="age" value="20"></property>
    	</bean>
    
    </beans>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    分为两个阶段 :

    • 1.读取配置到注册表
      • ApplicationContext ctx = new ClassPathXmlApplicationContext(“/applicationContext.xml”)
    • 2.根据注册表反射创建bean
      • Person person = (Person) ctx.getBean(“person”);

    2. 源码阅读

    debug很快进来最关键的部分AbstractApplicationContext中的refresh()方法

    2.1.refresh()方法

    @Override
    	public void refresh() throws BeansException, IllegalStateException {
    		synchronized (this.startupShutdownMonitor) {
    			// Prepare this context for refreshing.
    			// 准备此上下文以进行刷新。
    			//锁,日志,存储刷新前的ApplicationListeners
    			prepareRefresh();
    
    			// Tell the subclass to refresh the internal bean factory.
    			//告诉子类刷新内部bean工厂。
    			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
    
    			// Prepare the bean factory for use in this context.
    			// 准备bean工厂以便在此上下文中使用。
    			prepareBeanFactory(beanFactory);
    
    			try {
    				// Allows post-processing of the bean factory in context subclasses.
    				// 允许在上下文子类中对bean工厂进行后处理。
    				postProcessBeanFactory(beanFactory);
    
    				// Invoke factory processors registered as beans in the context.
    				// 调用在上下文中注册为bean的工厂处理器。
    				invokeBeanFactoryPostProcessors(beanFactory);
    
    				// Register bean processors that intercept bean creation.
    				// 注册拦截bean创建的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.
    				// 检查侦听器bean并注册它们。
    				registerListeners();
    
    				// Instantiate all remaining (non-lazy-init) singletons.
    				// 实例化所有剩余的(不是懒汉式加载)单例。
    				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
    				// 重置Spring核心中的常用自检缓存,因为我们
    				// might not ever need metadata for singleton beans anymore...
    				// 可能不再需要单例bean的元数据。。。
    				resetCommonCaches();
    			}
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82

    2.1.1 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

    abstract class AbstractRefreshableApplicationContext extends AbstractApplicationContext{
    /**
    	 * This implementation performs an actual refresh of this context's underlying
    	 * bean factory, shutting down the previous bean factory (if any) and
    	 * initializing a fresh bean factory for the next phase of the context's lifecycle.
    	 *
    	 * 此实现执行此上下文底层的实际刷新
    	 * bean工厂,关闭前一个bean工厂(如果有的话),并为上下文生命周期的下一阶段初始化新的bean工厂
    	 *
    	 */
    	@Override
    	protected final void refreshBeanFactory() throws BeansException {
    		if (hasBeanFactory()) {
    			destroyBeans();
    			closeBeanFactory();
    		}
    		try {
    			DefaultListableBeanFactory beanFactory = createBeanFactory();
    			beanFactory.setSerializationId(getId());
    			customizeBeanFactory(beanFactory);
    			//加载配置xml
    			loadBeanDefinitions(beanFactory);
    			this.beanFactory = beanFactory;
    		}
    		catch (IOException ex) {
    			throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
    		}
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    debugger细心可以发现
    在这里插入图片描述
    在这里插入图片描述
    可以看到loadBeanDefinitions(beanFactory);加载配置到注册表当中,可以深入研究是如何加载配置的

    2.1.2 XmlBeanDefinitionReader具体的读取配置类流

    因为配置可以有yml、xml等多种形式

    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();
    			}
    		}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    2.1.3 DefaultBeanDefinitionDocumentReader

    作用读取具体的bean定义,常量分别为import、alias、bean、beans

    	private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
    		if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
    			importBeanDefinitionResource(ele);
    		}
    		else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
    			processAliasRegistration(ele);
    		}
    		else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
    			processBeanDefinition(ele, delegate);
    		}
    		else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
    			// recurse
    			doRegisterBeanDefinitions(ele);
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    2.1.4 DefaultListableBeanFactory

    DefaultListableBeanFactory 里面存放注册好的bean配置

    DefaultListableBeanFactory 
    {
    /** Map of bean definition objects, keyed by bean name. */
    	private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    registerBeanDefinition 方法中将读取到的配置放入注册表
    可以发现类

    this.beanDefinitionMap.put(beanName, beanDefinition);
    
    • 1

    根据这个方法可以发现springboot用于读取配置的实体类
    在这里插入图片描述

    2.2 创建bean

    2.2.1 AbstractBeanFactory

    AbstractBeanFactory.doGetBean方法负责反射创建bean

    其中一段代码检查bean依赖的bean优先创建

    // Guarantee initialization of beans that the current bean depends on.
    				String[] dependsOn = mbd.getDependsOn();
    				if (dependsOn != null) {
    					for (String dep : dependsOn) {
    						if (isDependent(beanName, dep)) {
    							throw new BeanCreationException(mbd.getResourceDescription(), beanName,
    									"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
    						}
    						registerDependentBean(dep, beanName);
    						try {
    							getBean(dep);
    						}
    						catch (NoSuchBeanDefinitionException ex) {
    							throw new BeanCreationException(mbd.getResourceDescription(), beanName,
    									"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
    						}
    					}
    				}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18

    2.2.2 AbstractAutowireCapableBeanFactory

    /**
    	 * Central method of this class: creates a bean instance,
    	 * populates the bean instance, applies post-processors, etc.
    	 * @see #doCreateBean
    	 */
    	@Override
    	protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
    			throws BeanCreationException {
    
    		if (logger.isTraceEnabled()) {
    			logger.trace("Creating instance of bean '" + beanName + "'");
    		}
    		RootBeanDefinition mbdToUse = mbd;
    
    		// Make sure bean class is actually resolved at this point, and
    		// clone the bean definition in case of a dynamically resolved Class
    		// which cannot be stored in the shared merged bean definition.
    		Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
    		if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
    			mbdToUse = new RootBeanDefinition(mbd);
    			mbdToUse.setBeanClass(resolvedClass);
    		}
    
    		// Prepare method overrides.
    		try {
    			mbdToUse.prepareMethodOverrides();
    		}
    		catch (BeanDefinitionValidationException ex) {
    			throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
    					beanName, "Validation of method overrides failed", ex);
    		}
    
    		try {
    			// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
    			Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
    			if (bean != null) {
    				return bean;
    			}
    		}
    		catch (Throwable ex) {
    			throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
    					"BeanPostProcessor before instantiation of bean failed", ex);
    		}
    
    		try {
    			Object beanInstance = doCreateBean(beanName, mbdToUse, args);
    			if (logger.isTraceEnabled()) {
    				logger.trace("Finished creating instance of bean '" + beanName + "'");
    			}
    			return beanInstance;
    		}
    		catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
    			// A previously detected exception with proper bean creation context already,
    			// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
    			throw ex;
    		}
    		catch (Throwable ex) {
    			throw new BeanCreationException(
    					mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
    		}
    	}
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
  • 相关阅读:
    GCP设置Proxy来连接Cloud SQL
    使用RabbitMQ异步执行业务
    GCN 链结预测 负采样 想要请教链结预测当中的负采样问题
    使用vscode编辑markdown文件(可粘贴截图)
    斜拉桥智慧施工数字孪生 | 图扑赛博朋克
    Python中的索引和切片
    优盘格式化了怎么恢复里面的数据?
    什么是Python选择结构
    旧物回收小程序开发,开启绿色生活新篇章
    如何简单的获取Bean对象?
  • 原文地址:https://blog.csdn.net/qq_43751489/article/details/127415530