您好,欢迎访问代理记账网站
  • 价格透明
  • 信息保密
  • 进度掌控
  • 售后无忧

SpringIOC源码分析

IOC容器介绍

Spring 通过一个配置文件描述 Bean 及 Bean 之间的依赖关系,利用 Java 语言的反射功能实例化 Bean 并建立 Bean 之间的依赖关系。 Spring 的 IoC 容器在完成这些底层工作的基础上,还提供了 Bean 实例缓存、生命周期管理、 Bean 实例代理、事件发布、资源装载等高级服务

  • BeanFactory 是 Spring 框架的基础设施,面向 Spring 本身;
  • ApplicationContext 面向使用 Spring 框架的开发者,几乎所有的应用场合我们都直接使用 ApplicationContext 而非底层的 BeanFactory。

IOC容器的创建过程
在这里插入图片描述

查看Spring启动时IOC容器初始化源码

  1. 在resource目录下新建一个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="a" class="com.zh.source.A"></bean>
    <bean id="b" class="com.zh.source.B"></bean>
</beans>
  1. 在src的下面新建了两个类A,B
public class A {
}

public class B {
}
  1. 在src下面新建一个测试类
public class TestSpring {
    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("test.xml");
        System.out.println(context.getBean("a"));
    }
}
  1. debug启动查看源码
//ClassPathXmlApplicationContext类
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
		this(new String[] {configLocation}, true, null);
}
// 由上面方法调用
public ClassPathXmlApplicationContext(
			String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
			throws BeansException {
		// 1. 调用父类,资源路径匹配
		super(parent);
    	// 2. 解析配置文件,configLocations就是读到的xml配置文件
		setConfigLocations(configLocations);
		if (refresh) {
            //3.
			refresh();
		}
}
  1. setConfigLocations
//2 AbstractRefreshableConfigApplicationContext类
public void setConfigLocations(@Nullable String... locations) {
    	// 如果读取到的配置文件不为空,则进行下一步处理
		if (locations != null) {
			Assert.noNullElements(locations, "Config locations must not be null");
			this.configLocations = new String[locations.length];
            // 将读取到了配置文件遍历赋值给configLocations
			for (int i = 0; i < locations.length; i++) {
                // 2.1
				this.configLocations[i] = resolvePath(locations[i]).trim();
			}
		}
		else {
			this.configLocations = null;
		}
}
// 2.1
protected String resolvePath(String path) {
    	// 2.2 getEnvironment():获取环境变量等
    	//resolveRequiredPlaceholders(path) 将配置文件中变量做一个替换
		return getEnvironment().resolveRequiredPlaceholders(path);
}

2.2 getEnvironment

// 2.2 AbstractApplicationContext, 获取环境变量等
public ConfigurableEnvironment getEnvironment() {
		if (this.environment == null) {
            // 2.3
			this.environment = createEnvironment();
		}
		return this.environment;
}

// 2.3 查询环境变量,
protected ConfigurableEnvironment createEnvironment() {
		return new StandardEnvironment();
}

3 refresh

// 3 AbstractApplicationContext
@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

			// Prepare this context for refreshing.
            // 3.1 为刷新准备这个上下文
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
            // 3.2 创建Bean工厂
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
            // 3.3 准备在此上下文中使用的bean工厂
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
                // BeanFactory的增强器扩展接口
				postProcessBeanFactory(beanFactory);

				StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
				// Invoke factory processors registered as beans in the context.
                // 3.4 调用在上下文中注册的bean的工厂处理器(增强器)
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
                // 注册Bean的处理器(增强器)
				registerBeanPostProcessors(beanFactory);
				beanPostProcess.end();

				// 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.
                // 实例化所有剩余的(非懒加载)单例
				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();
				contextRefresh.end();
			}
		}
	}

3.1 prepareRefresh

// 3.1 AbstractApplicationContext类,该方法主要是为刷新上下文做准备
protected void prepareRefresh() {
		// Switch to active.
		this.startupDate = System.currentTimeMillis(); // 获取当前时间
		this.closed.set(false);  // 设置默认值 
		this.active.set(true);   // 设置默认值
		// 日志的打印
		if (logger.isDebugEnabled()) {
			if (logger.isTraceEnabled()) {
				logger.trace("Refreshing " + this);
			}
			else {
				logger.debug("Refreshing " + getDisplayName());
			}
		}

		// Initialize any placeholder property sources in the context environment.
		// 扩展方法
    	initPropertySources();

		// Validate that all properties marked as required are resolvable:
		// see ConfigurablePropertyResolver#setRequiredProperties
		// getEnvironment(): 如果有当前环境变量就直接使用,没有的话就创建一个StandardEnvironment()
    	// validateRequiredProperties(): 对属性做基本的验证
    	getEnvironment().validateRequiredProperties();

		// Store pre-refresh ApplicationListeners...
    	// 创建存储监听器的集合
		if (this.earlyApplicationListeners == null) {
			this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
		}
		else {
			// Reset local application listeners to pre-refresh state.
			this.applicationListeners.clear();
			this.applicationListeners.addAll(this.earlyApplicationListeners);
		}

		// Allow for the collection of early ApplicationEvents,
		// to be published once the multicaster is available...
		this.earlyApplicationEvents = new LinkedHashSet<>();
	}

3.2 obtainFreshBeanFactory

// AbstractApplicationContext 类
// 3.2 创建Bean工厂
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
    	// 3.2.1 刷新BeanFactory
		refreshBeanFactory();
    	// 获取beanFactory,这时候BeanFactory以及创建过了,这里只是判断非空返回
		return getBeanFactory();
}

3.2.1 refreshBeanFactory

// AbstractRefreshableApplicationContext类
// 3.2.1  刷新BeanFactory
protected final void refreshBeanFactory() throws BeansException {
    	// 判断是否以及存在Bean工厂,true:已存在,false: 不存在
		if (hasBeanFactory()) {
            // 存在Bean工厂了,则销毁Bean工厂
			destroyBeans();
			closeBeanFactory();
		}
		try {
            // createBeanFactory():创建BeanFactory
			DefaultListableBeanFactory beanFactory = createBeanFactory();
			beanFactory.setSerializationId(getId());
			// 定制化BeanFactory
            customizeBeanFactory(beanFactory);
            // 3.2.1.1 加载Bean的定义信息
			loadBeanDefinitions(beanFactory);
			this.beanFactory = beanFactory;
		}
		catch (IOException ex) {
			throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
		}
	}

// 创建一个DefaultListableBeanFactory,
protected DefaultListableBeanFactory createBeanFactory() {
		return new DefaultListableBeanFactory(getInternalParentBeanFactory());
}

注意:loadBeanDefinitions(beanFactory)是一个重点,表示加载bean的定义信息
3.2.1.1 loadBeanDefinitions

// AbstractXmlApplicationContext类,因为用的是xml配置文件,所有进入的是这个类
// 3.2.1.1 
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
		// Create a new XmlBeanDefinitionReader for the given BeanFactory.
    	// 创建一个xmlBean定义信息读取类
		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

		// Configure the bean definition reader with this context's
		// resource loading environment.
    	// 设置环境
		beanDefinitionReader.setEnvironment(this.getEnvironment());
    	// 设置当前处理类
		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.
    	// 初始化Bean定义类型
		initBeanDefinitionReader(beanDefinitionReader);
    	// 加载bean定义信息
		loadBeanDefinitions(beanDefinitionReader);
}

// 加载bean定义信息
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
    	// 将配置文件放入数组
		Resource[] configResources = getConfigResources();
		if (configResources != null) {
            // 读取bean定义信息
			reader.loadBeanDefinitions(configResources);
		}
		String[] configLocations = getConfigLocations();
		if (configLocations != null) {
			reader.loadBeanDefinitions(configLocations);
		}
	}

3.3 准备在此上下文中使用的bean工厂

// AbstractApplicationContext类
// 3.3 准备在此上下文中使用的bean工厂
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		// Tell the internal bean factory to use the context's class loader etc.
		// 设置beanFactory的类加载器等参数
    	beanFactory.setBeanClassLoader(getClassLoader());
		if (!shouldIgnoreSpel) {
			beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
		}
		beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

		// Configure the bean factory with context callbacks.
    	// 向beanFactory 注入Bean增强器(BeanPostProcessor)
		beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
		beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
		beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
		beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
		beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
		beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
		beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
		beanFactory.ignoreDependencyInterface(ApplicationStartupAware.class);

		// BeanFactory interface not registered as resolvable type in a plain factory.
		// MessageSource registered (and found for autowiring) as a bean.
		beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
		beanFactory.registerResolvableDependency(ResourceLoader.class, this);
		beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
		beanFactory.registerResolvableDependency(ApplicationContext.class, this);

		// Register early post-processor for detecting inner beans as ApplicationListeners.
		beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

		// Detect a LoadTimeWeaver and prepare for weaving, if found.
		if (!NativeDetector.inNativeImage() && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
			beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
			// Set a temporary ClassLoader for type matching.
			beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
		}

		// Register default environment beans.
		if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
			beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
		}
		if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
			beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
		}
		if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
			beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
		}
		if (!beanFactory.containsLocalBean(APPLICATION_STARTUP_BEAN_NAME)) {
			beanFactory.registerSingleton(APPLICATION_STARTUP_BEAN_NAME, getApplicationStartup());
		}
	}

3.4 调用在上下文中注册为bean的工厂处理器(增强器)

// AbstractApplicationContext
// 3.4 调用在上下文中注册为bean的工厂处理器(增强器)
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    	// getBeanFactoryPostProcessors(): 获取beanFactory的增强器
    	// invokeBeanFactoryPostProcessors:执行beanFactory的增强器
    PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

		// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
		// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
		if (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
			beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
			beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
		}
}

分享:

低价透明

统一报价,无隐形消费

金牌服务

一对一专属顾问7*24小时金牌服务

信息保密

个人信息安全有保障

售后无忧

服务出问题客服经理全程跟进