spring容器初始化

 

public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
			throws BeansException {
		super(parent);
		setConfigLocations(configLocations);
		if (refresh) {
			/**spring容器初始化就是调用该方法实现的
			*该方法位于AbstractApplicationContext.java类里
			*/
			refresh();
		}
	}
 

 

 

[size=x-large][/size]spring容器的初始化是通过AbstractApplicationContext类里的refresh()方法实现的。AbstractApplicationContext 是容器的最基础的一个抽象父类。也就是说在该里面定义了一个容器初始化的基本流程,流程里的各个方法有些有提供了具体实现,有些是抽象的 ( 因为不同的容器实例不一样 ) ,由继承它的每一个具体容器完成定制。看看 refresh 的基本流程:

 

public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// 容器启动的预先准备,记录容器启动的时间和标记
			prepareRefresh();

			// 创建BeanFactory,如果已有就销毁,没有就创建。此类实现了对BeanDefinition的装载
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// 配置BeanFactory标准上下文特性,如类装载器,PostProcesser等
			prepareBeanFactory(beanFactory);

			try {
				// 在bean被装载后,提供一个修改BeanFactory的入口
				postProcessBeanFactory(beanFactory);

				// 调用postProcessBeanFactory
				invokeBeanFactoryPostProcessors(beanFactory);

				// 注册用于拦截bean创建过程中的BeanPostProcessors
				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();

				// 注册监听器
				registerListeners();

				// 完成容器的初始化,里面的preInstantiateSingletons()完成对单例对象的创建
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				finishRefresh();
			}

			catch (BeansException ex) {
				// Destroy already created singletons to avoid dangling resources.
				beanFactory.destroySingletons();

				// Reset 'active' flag.
				cancelRefresh(ex);

				// Propagate exception to caller.
				throw ex;
			}
		}
	}

 

 

     /**

	 * Prepare this context for refreshing, setting its startup date and
	 * active flag.
	 *容器启动的预先准备,记录容器启动的时间和标记
	 */
	protected void prepareRefresh() {
		this.startupDate = System.currentTimeMillis();

		synchronized (this.activeMonitor) {
			this.active = true;
		}

		if (logger.isInfoEnabled()) {
			logger.info("Refreshing " + this);
		}
	}

 

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
		/*创建BeanFactory,如果已有就销毁,没有就创建。此类实现了对BeanDefinition的装载*/
		refreshBeanFactory();
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();

		if (logger.isInfoEnabled()) {
			logger.info("Bean factory for application context [" + getId() + "]: " +
					ObjectUtils.identityToString(beanFactory));
		}
		if (logger.isDebugEnabled()) {
			logger.debug(beanFactory.getBeanDefinitionCount() + " beans defined in " + this);
		}

		return beanFactory;
	}

 

/**
	 * This implementation performs an actual refresh of this context's underlying
	 * bean factory, shutting down the previous bean factory (if any) and
	 * initializing a fresh bean factory for the next phase of the context's lifecycle.
	 *这个实现执行实际的刷新和这个context相关的BeanFactory.关闭前一个BeanFactory,如果存在;
	 *为下一阶段的context的生命周期初始化一个新的BeanFactory
	 */
	protected final void refreshBeanFactory() throws BeansException {
		//如果存在就销毁这个BeanFactory
		if (hasBeanFactory()) {
			destroyBeans();
			closeBeanFactory();
		}
		try {   //不存在就创建一个BeanFactory
			DefaultListableBeanFactory beanFactory = createBeanFactory();
                        //定制BeanFactory,包括allowBeanDefinitionOverriding允许覆盖BeanDefinition 和 allowCircularReferences 允许循环引用
			customizeBeanFactory(beanFactory);
			//通过XmlBeanDefinitionReader装载BeanDefinitions
			loadBeanDefinitions(beanFactory);
			synchronized (this.beanFactoryMonitor) {
				this.beanFactory = beanFactory;
			}
		}
		catch (IOException ex) {
			throw new ApplicationContextException(
					"I/O error parsing XML document for application context [" + getDisplayName() + "]", ex);
		}
	}

 

/**
	 * Loads the bean definitions via an XmlBeanDefinitionReader.
	 *通过XmlBeanDefinitionReader装载BeanDefinitions
	 * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
	 * @see #initBeanDefinitionReader
	 * @see #loadBeanDefinitions
	 */
	protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws IOException {
		// Create a new XmlBeanDefinitionReader for the given BeanFactory.
		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

		// Configure the bean definition reader with this context's
		// resource loading environment.
		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.
		initBeanDefinitionReader(beanDefinitionReader);
		loadBeanDefinitions(beanDefinitionReader);
	}

 /**

	 * Configure the factory's standard context characteristics,
	 * such as the context's ClassLoader and post-processors.
	 *配置BeanFactory标准上下文特性,如类装载器,PostProcesser等
	 * @param beanFactory the BeanFactory to configure
	 */
	protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		// Tell the internal bean factory to use the context's class loader.
		beanFactory.setBeanClassLoader(getClassLoader());

		// Populate the bean factory with context-specific resource editors.
		beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this));

		// Configure the bean factory with context callbacks.
		beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
		beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
		beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
		beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
		beanFactory.ignoreDependencyInterface(ApplicationContextAware.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);

		// Detect a LoadTimeWeaver and prepare for weaving, if found.
		if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME) && JdkVersion.isAtLeastJava15()) {
			// Register the (JDK 1.5 specific) LoadTimeWeaverAwareProcessor.
			try {
				Class ltwapClass = ClassUtils.forName(
						"org.springframework.context.weaving.LoadTimeWeaverAwareProcessor",
						AbstractApplicationContext.class.getClassLoader());
				BeanPostProcessor ltwap = (BeanPostProcessor) BeanUtils.instantiateClass(ltwapClass);
				((BeanFactoryAware) ltwap).setBeanFactory(beanFactory);
				beanFactory.addBeanPostProcessor(ltwap);
			}
			catch (ClassNotFoundException ex) {
				throw new IllegalStateException("Spring's LoadTimeWeaverAwareProcessor class is not available");
			}
			// Set a temporary ClassLoader for type matching.
			beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
		}
	}
 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值