Spring Framework源码(二):spring beans之ApplicationContext

 

         接着上一章的内容这章讲spring最重要的IOC容器中的另一个容器ApplicationContext。

         首先来看看spring资源文件绑定的相关接口。第一个便是ResourceLoader接口:

public interface ResourceLoader {
	String CLASSPATH_URL_PREFIX = ResourceUtils.CLASSPATH_URL_PREFIX;
	Resource getResource(String location);
	ClassLoader getClassLoader();
}

         此接口的第一个成员变量便是常量类路径前缀“classpath:”,

         第二个成员函数是getResource(String location),它能返回一个特定资源文件例如某*-context.xml的句柄,并能反复使用和多次使用。

         第三个成员函数是getClassLoader(),它能暴露它所使用的类装载器。

        

         然后是一个它的子接口ResourcePatternResolver:

public interface ResourcePatternResolver extends ResourceLoader {
	String CLASSPATH_ALL_URL_PREFIX = "classpath*:";
	Resource[] getResources(String locationPattern) throws IOException;
}

        它扩展了父接口使其能用表达式匹配收集某些路径下的资源文件。

         在开讲ApplicationContext这个接口之前,我们先看看它所实现的其它几个接口,首先是MessageSource:

public interface MessageSource {
	String getMessage(String code, Object[] args, String defaultMessage, Locale locale);
	String getMessage(String code, Object[] args, Locale locale) throws NoSuchMessageException;
	String getMessage(MessageSourceResolvable resolvable, Locale locale) throws NoSuchMessageException;
}

        此接口定义了一些根据不同Locale获取文本资源(即国际化中的*.properties)的几个方法。

         第二个便是EnvironmentCapable接口:

public interface EnvironmentCapable {
	Environment getEnvironment();
}

        这个接口建立了ApplicationContext和Environment的联系。通过它用户能获取Environment,Environment接口:        

public interface Environment extends PropertyResolver {
	String[] getActiveProfiles();
	String[] getDefaultProfiles();
	boolean acceptsProfiles(String... profiles);
}

      这个接口能获取项目的配置属性和不同的运行环境properties和profiles。

      最后是ApplicationContext接口: 

public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,
		MessageSource, ApplicationEventPublisher, ResourcePatternResolver {
	String getId();
	String getApplicationName();
	String getDisplayName();
	long getStartupDate();
	ApplicationContext getParent();
	AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException;
}

    这是第二个重要的IOC容器。getId能获取当前ApplicationContext的唯一ID,getApplicationName能获取当前应用的名字,getDisplayName能获取应用的显示名字即web.xml中配置displayName,getStartupDate能获取应用的启动日期,getParent能获取当前容器的父容器,ioc容器都能相互嵌套的。getAutowireCapableBeanFactory可以获取支持能自动注入bean的BeanFactory。这个类总体说来提供了一个获取上层IOC容器和应用的相关属性的通道。

    ApplicationContext的直接子类是ConfigurableApplicationContext,这个子类同时实现了一个Lifecycle接口来控制生命周期。它提供了一个启动函数start,同时提供了一个终止函数stop,还有一个判断应用的运行状态的函数isRunning。ConfigurableApplicationContext提供了一些接口来配置ApplicationContext并封装了Lifecycle的一些方法是这些方法仅仅暴露给应用的启动和关闭代码。

public interface ConfigurableApplicationContext extends ApplicationContext, Lifecycle, Closeable {
	String CONFIG_LOCATION_DELIMITERS = ",; \t\n";
	String CONVERSION_SERVICE_BEAN_NAME = "conversionService";
	String LOAD_TIME_WEAVER_BEAN_NAME = "loadTimeWeaver";
	String ENVIRONMENT_BEAN_NAME = "environment";
	String SYSTEM_PROPERTIES_BEAN_NAME = "systemProperties";
	String SYSTEM_ENVIRONMENT_BEAN_NAME = "systemEnvironment";
	void setId(String id);
	void setParent(ApplicationContext parent);
	@Override
	ConfigurableEnvironment getEnvironment();
	void setEnvironment(ConfigurableEnvironment environment);
	void addBeanFactoryPostProcessor(BeanFactoryPostProcessor beanFactoryPostProcessor);
	void addApplicationListener(ApplicationListener<?> listener);
	void refresh() throws BeansException, IllegalStateException;
	void registerShutdownHook();
	@Override
	void close();
	boolean isActive();
	ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;
}

    这个接口既是通向BeanFactory的桥梁又是获取应用配置参数和运行环境的通道,它的一个重要作用就是使ApplicationContext变成可配置的。

    此类的直接子抽象类是AbstractApplicationContext,这个类为大多数父接口中方法提供了默认实现。这里着重讲下refresh()方法:

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

			// Tell the subclass to refresh the internal bean factory.
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			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.
				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;
			}
		}
	}

     首先为startupShutdownMonitor(启动和关闭监听器)对象加锁保持线程同步,接着调用prepareRefresh方法为初始化做准备:

	protected void prepareRefresh() {
		this.startupDate = System.currentTimeMillis();
		this.active.set(true);

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

    由上图所见, 这个方法初始化启动时间,设置激活状态,然后初始化配置文件(留给子类实现),最后验证资源文件的可用性。

    为初始化准备好后,初始化局部ConfigurableListableBeanFactory对象并初始化BeanFactory。初始化的步奏包括1、设置此BeanFactory的类装载器,2、设置bean表达式处理器,3、加载PropertyEditor注册器,4、加载bean初始化后置处理器(BeanPostProccessor),5、注册一系列自动注入时所需要忽略的相关接口类,6、注册一系列自动注入时需要依赖的相关接口类,7、探测加载时间织入器,8、注册运行环境相关的单例对象。当这一步准备好后,调用一个接口方法提供给子类自定义BeanFactory初始化后的后置处理。然后使用后置处理器注册代理。然后初始化资源对象MessageSource,初始化应用事件广播器,调用onrefresh提供给子类实现特殊逻辑,初始化监听器,初始化所有非延迟加载类,最后注册生命周期管理器和发起refresh事件。

    接着是AbstractRefreshableApplicationContext类,这里只做简略介绍,这个类较之于父类,通过并发访问父类的refresh方法使多次调用refresh函数的同时不会重复创建BeanFactory实例(每次调用refresh都会创建一个BeanFactory实例)。此子类提供一个抽象方法loadBeanDefinitions留给子类实现加载bean定义的具体逻辑。

    再下面是AbstractRefreshableConfigApplicationContext类,这个类很简单,仅仅作为基于xml定义的ApplicationContext的基类,提供了一些获取和设置配置文件的路径的方法。

    再接下来是AbstractXmlApplicationContext类,这个类为loadDefinitions(DefaultListableBeanFactory beanFactory)提供了实现逻辑,包括创建XmlBeanDefinitionReader实例并初始化,利用这个实例加载配置文件分别转化为一个Resource数组和一个ConfigLocation字符串数组。

    最后是FileSystemXmlApplicationContext类,它是一个实实在在的实现类,它提供一系列的构造函数创建ApplicationContext容器。

总结

    ApplicationContext作为最重要的IOC容器之一(这里仅介绍基于xml创建IOC容器的方式),它提供了一个将存在于文件系统中的xml应用上下文配置文件转化成一系列程序可用的Resource(资源)。

   

   

       

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值