Spring源码分析总结-IOC容器初始化
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring源码分析总结-IOC容器初始化相关的知识,希望对你有一定的参考价值。
一、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容器初始化的主要内容,如果未能解决你的问题,请参考以下文章