1. 程式人生 > >Spring源碼分析總結(一)-IOC容器初始化

Spring源碼分析總結(一)-IOC容器初始化

Spring源碼分析總結

一、IOC容器的初始化過程

IOC容器的初始化是由refresh()方法啟動。經常使用的ApplicationContext 有:ClassPathXmlApplicationContext和FileSystemXmlApplicationContext、XmlWebApplicationContext等。都有refresh()方法。

技術分享圖片

refresh()方法的這個啟動分為三個基本過程:

	/**
	 * Create a new ClassPathXmlApplicationContext with the given parent,
	 * loading the definitions from the given XML files.
	 * @param configLocations array of resource locations
	 * @param refresh whether to automatically refresh the context,
	 * loading all bean definitions and creating all singletons.
	 * Alternatively, call refresh manually after further configuring the context.
	 * @param parent the parent context
	 * @throws BeansException if context creation failed
	 * @see #refresh()
	 */
	public ClassPathXmlApplicationContext(
			String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
			throws BeansException {

		super(parent);
		setConfigLocations(configLocations);
		if (refresh) {
			refresh();
		}
	}
	
public abstract class AbstractApplicationContext extends DefaultResourceLoader
		implements ConfigurableApplicationContext {
@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			//準備刷新的上下文環境 Prepare this context for refreshing.
			prepareRefresh();

			//初始化BeanFactory,並進行xml文件讀取 Tell the subclass to refresh the internal bean factory.
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			//對BeanFactory進行各種功能填充 Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory);

			try {
				//子類覆蓋方法做額外的處理Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);

				//激活各種BeanFactory處理器器,這裏只是註冊調用在getBean()的時候 Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);

				//註冊攔截Bean創建的Bean處理,這裏只是註冊調用在getBean()的時候
                                 //Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory);

				//為上下文初始化message源,即不同語言的消息體,國際化處理 Initialize message source for this context.
				initMessageSource();

				//初始化應用消息廣播器,並放入(applicationEventMulticaster) Initialize event multicaster for this context.
				initApplicationEventMulticaster();

				//留給子類來初始化其他的Bean Initialize other special beans in specific context subclasses.
				onRefresh();

				//在所有註冊的bean中查找Listener bean註冊到消息廣播器中。 Check for listener beans and register them.
				registerListeners();

				//初始化剩下的單實例(非惰性的) Instantiate all remaining (non-lazy-init) singletons.
				finishBeanFactoryInitialization(beanFactory);

				//完成刷新過程,通知生命周期處理器lifecycleProcessor刷新過程, 同時發出ContextRefreshEvent通知別人。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();
			}
		}
	}

}

技術分享圖片





 ApplicationContext factory = new FileSystemXmlApplicationContext("F:/workspace/example/src/appcontext.xml");
    IHelloWorld hw = (IHelloWorld)factory.getBean("helloworldbean");
    log.info(hw.getContent("luoshifei"));

//用classpath路徑
ApplicationContext factory = new ClassPathXmlApplicationContext("classpath:appcontext.xml");

Ioc容器的初始化

技術分享圖片

1、第一個過程 BeanDefinition的Resource定位

FileSystemXmlApplicationContext/ClassPathXmlApplicationContext ->AbstractApplicationContext類refresh()

->調用AbstractRefreshableApplicationContext類的refreshBeanFactory()->調用了loadBeanDefinitions(beanFactory);

->XmlWebApplicationContext類的loadBeanDefinitions->XmlBeanDefinitionReader類的loadBeanDefinitions

->AbstractBeanDefinitionReader類的loadBeanDefinitions

==>1.調用DefaultResourceLoader的getResource完成具體的Resource定位(Resource resource = resourceLoader.getResource(location);)

->DefaultResourceLoader類的getResourceByPath(location)完成Resource的定位

==>2.如果跟ResourcePatternResolver相同 ->調用PathMatchingResourcePatternResolver類的getResources方法


在XmlBeanDefinitionReader的基類AbstractBeanDefinition加載讀入BeanDefinition

技術分享圖片

2、第二個過程 BeanDefinition的載入和解析

AbstractRefreshableApplicationContext類的refreshBeanFactory()->XmlWebApplicationContext類的loadBeanDefinitions

->AbstractBeanDefinitionReader類的loadBeanDefinitions

->XmlBeanDefinitionReader類的loadBeanDefinitions()->loadBeanDefinitions()-裏面的doLoadBeanDefinitions

->registerBeanDefinitions(doc, resource)->documentReader.registerBeanDefinitions(doc, createReaderContext(resource));

->DefaultBeanDefinitionDocumentReader類的registerBeanDefinitions方法->doRegisterBeanDefinitions(root);

->parseBeanDefinitions(root, this.delegate);->parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate)

->parseDefaultElement(ele, delegate);->processBeanDefinition(ele, delegate);

->delegate.parseBeanDefinitionElement(ele);->BeanDefinitionParserDelegate類的parseBeanDefinitionElement(ele, null);

->BeanDefinitionParserDelegate類parseBeanDefinitionElement方法

技術分享圖片

3、第三個過程 BeanDefinition在IOC容器中的註冊

把解析得到的BeanDefinition設置到hashMap中去。

在DefaultListableBeanFactory中,事通過一個HashMap來持有載入的BeanDefinition的,這個HashMap的定義在DefaultListableBeanFactory中可以看到。

技術分享圖片



IOC容器的依賴註入

技術分享圖片

技術分享圖片



1、當用戶向IOC容器索要Bean時,也就是如:

 IHelloWorld hw = (IHelloWorld)factory.getBean("helloworldbean");

從DefaultListableBeanFactory的基類AbstractBeanFactory類可以看getBean的實現。

//---------------------------------------------------------------------
	// Implementation of BeanFactory interface
	//---------------------------------------------------------------------

	@Override
	public Object getBean(String name) throws BeansException {
		return doGetBean(name, null, null, false);
	}

技術分享圖片


在createBeanInstance中生成了Bean所包含的java對象,這個對象的生成方式有很多方式,可以通過工廠方法,也可以通過容器的Autowire特性生成,由相關的BeanDefinition來指定。

SimpleInstantiationStrategy類,這個Strategy是spring用來生成bean對象的默認類,它提供了兩種實例化Java對象的方法,一種是通過BeanUtils,它提供了JVM的反射功能,一種是通過CGLIB生成。


技術分享圖片


版權聲明:轉載請註明出處


Spring源碼分析總結(一)-IOC容器初始化