spring加载配置文件,AbstractApplicationContext类中的refresh方法起着重要的作用。
@Overridepublic void refresh() throws BeansException, IllegalStateException {synchronized (this.startupShutdownMonitor) {// Prepare this context for refreshing.准备刷新context prepareRefresh();// Tell the subclass to refresh the internal bean factory.刷新子类beanFactory,注册beanDefinitionConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();// Prepare the bean factory for use in this context.准备beanfactory prepareBeanFactory(beanFactory);try {// Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory);// Invoke factory processors registered as beans in the context. invokeBeanFactoryPostProcessors(beanFactory);// Register bean processors that intercept bean creation. registerBeanPostProcessors(beanFactory);// Initialize message source for this context. initMessageSource();// Initialize event multicaster for this context. initApplicationEventMulticaster();// Initialize other special beans in specific context subclasses. onRefresh();// Check for listener beans and register them. registerListeners();// Instantiate all remaining (non-lazy-init) singletons.初始化非懒加载的bean实例 finishBeanFactoryInitialization(beanFactory);// Last step: publish corresponding event. finishRefresh();}catch (BeansException ex) {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;}}}
实例化bean对象,主要的是在
finishBeanFactoryInitialization(beanFactory)
方法。
大致的流程图(下部分):
(点击查看大图)
下面分析实例化bean对象的源码分析
加载bean对象:
在AbstractBeanFactory类中,根据不同scope进行实例化,例如Singleton,Prototype等
根据不同情况采用不同的代理方式:
到这里就是bean实例的初始化,可以看到spring采用的代理方式,来实现bean的初始化。