天天看点

SpringIOC源码解析一

准备

将spring5.1源码导入到idea编写几个测试类

public class Main {

	public static void main(String[] args) {
		ApplicationContext app =	new ClassPathXmlApplicationContext("spring.xml");
	    Text02 text02=	(Text02)app.getBean("text02");
	    text02.text();
	}
}
           
public class Text02 {
	@Autowired
	private MZZ02 mzz02;

	public Text02(){
		System.out.println("构造器Text02");
	}
	public void text(){
		String text02 = mzz02.demo("Text02");
		System.out.println("text02:"+text02);
	}
           
@Component
public class MZZ02 {

	public MZZ02(){
		System.out.println("MZZ02");
	}
	public String demo(String text){
		System.out.println("MZZ02接收:"+text);
		return text+":MZZ02";
	}
}
           

spring.xml配置如下

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:context="http://www.springframework.org/schema/context"
	   xmlns:p="http://www.springframework.org/schema/p"
	   xmlns:mvc="http://www.springframework.org/schema/mvc"
	   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-3.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/mvc
      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
	<bean id="text02" class="laixx.bean.Text02"></bean>
	//扫包
	<context:component-scan base-package="laixx.cont"/>
</beans>
           

进入ClassPathXmlApplicationContext类

public ClassPathXmlApplicationContext(
			String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
			throws BeansException {
		super(parent);
		//将配置文件注入到AbstractRefreshableConfigApplicationContext类的成员属性中
		setConfigLocations(configLocations);
		//refresh为true
		if (refresh) {
			refresh();
		}
	}
	//这个是上面的setConfigLocations方法,目的是把配置文件设置到configLocations数组中
		public void setConfigLocations(@Nullable String... locations) {
		if (locations != null) {
			Assert.noNullElements(locations, "Config locations must not be null");
			this.configLocations = new String[locations.length];
			for (int i = 0; i < locations.length; i++) {
				this.configLocations[i] = resolvePath(locations[i]).trim();
			}
		}
		else {
			this.configLocations = null;
		}
	}
           

进入refresh();方法

@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.

			//为刷新准备新的 context,设置其启动日期和活动标志以及执行一些属性的初始化。
			// 主要是一些准备工作,不是很重要的方法
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			//初始化beanfactroy
			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.
				//实例化所有剩余的(非lazy init)单例。
				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...
				//重置Spring核心中常见的内省缓存,因为我们
                //可能不再需要用于单例bean的元数据了…
				resetCommonCaches();
			}
		}
	}

           

其中主要的方法有

  1. obtainFreshBeanFactory();//初始化beanfactory,并解析xml
  2. invokeBeanFactoryPostProcessors(beanFactory);//调用在上下文中注册为bean的工厂处理器
  3. registerBeanPostProcessors(beanFactory);//注册拦截bean创建的bean处理器
  4. finishBeanFactoryInitialization(beanFactory);//实例化所有剩余的(非lazy init)单例。

继续阅读