ApplicationContext对于Spring框架起着举重轻重的重用,自己在学习时作了一些笔记,其中有很多部分从夏昕的《springGuild》
ApplicationContext覆盖了BeanFactory的所有功能,并提供了更多的特性,但相对于BeanFactory,ApplicationContext提供了以下的扩展功能:
1. 国际化支持
我们可以在Beans.xml文件中,对程序中的语言信息(如提示信息)进行定义,将程序中的提示信息抽取到配置文件中加以定义,为我们进行应用的各语言版本转换提供了极大的灵活性。
<beans>
<description>Spring Quick Start</description>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>messages</value>
</list>
</property>
</bean>
</beans>
这里声明了一个名为messageSource的Bean(注意对于Message定义,Bean ID必须为messageSource,这是目前Spring的编码规约),对应类为ResourceBundleMessageSource,目前Spring中提供了两MessageSource接口的实现,即ResourceBundleMessageSource和ReloadableResourceBundleMessageSource,后者提供了无需重启即可重新加载配置信息的特性。
在配置节点中,我们指定了一个配置名“messages”。Spring会自动在CLASSPATH根路
SpringFrameWork Developer’s Guide Version 0.6
October 8, 2004 So many open source projects. Why not Open your Documents?
径中按照如下顺序搜寻配置文件并进行加载(以Locale为zh_CN为例):
messages_zh_CN.properties
messages_zh.properties
messages.properties
messages_zh_CN.class
messages_zh.class
messages.class
(Spring实际上调用了JDK的ResourceBundle读取配置文件,相关内容请参见JDK文档)
2. 资源访问
支持对文件和URL的访问。
ApplicationContext.getResource方法提供了对资源文件访问支持,如:
Resource rs = ctx.getResource("classpath:config.properties");
File file = rs.getFile();
上例从CLASSPATH根路径中查找config.properties文件并获取其文件句柄。
getResource方法的参数为一个资源访问地址,如:
file:C:/config.properties
/config.properties
classpath:config.properties
注意getResource返回的Resource并不一定实际存在,可以通过Resource.exists()方法对
其进行判断。
3. 事件传播
事件传播特性为系统中状态改变时的检测提供了良好支持。
ApplicationContext基于Observer模式(java.util包中有对应实现),提供了针对Bean的事件传
播功能。通过Application. publishEvent方法,我们可以将事件通知系统内所有的
ApplicationListener。
4. 多实例加载
可以在同一个应用中加载多个Context实例。