ClassPathXmlApplicationContext支持从classpath中查找资源。假如我以下面的方式启动Spring:
ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
那么系统将会从classpath中查找myFile.xml文件。相当于:
URL resource = getClassLoader().getResource("myFile.xml");
FileSystemXmlApplicationContext支持从文件系统中查找资源。假如我以下面的方式启动Spring:
ApplicationContext context = new FileSystemXmlApplicationContext("beans.xml");
那么系统将会在文件系统中查找myFile.xml文件。相当于:
File resource = new File("myFile.xml");
XmlWebApplicationContext支持从webapp上下文中(也就是ServletContext对象中)查找资源。假如我以下面的方式启动Spring:
ApplicationContext context = new XmlWebApplicationContext();
或者在/WEB-INF/web.xml中添加如下配置:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/beans.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
那么系统将会在Web应用的根目录中查找myFile.xml。相当于:
URL resource = servletContext.getResource("myFile.xml");
除了用ClassPathXmlApplicationContext来装载classpath下的资源,所有的Spring ApplicationContext实现都支持从classpath中装载资源:
l 使用classpath前缀:“classpath:myFile.xml” —— 在classpath中查找资源myFile.xml。
l 使用classpath*前缀:“classpath*:/META-INF/my*.xml” —— 在classpath中查找所有符合pattern的资源。
l 鱼和熊掌不可得兼
Spring ResourceLoader是由ApplicationContext来实现的。而你一次只能选择一种ApplicationContext的实现 —— 如果你选择了XmlWebApplicationContext,你就放弃了FileSystemXmlApplicationContext;反之亦然。
在WEB应用中,由于Spring使用了XmlWebApplicationContext,因此你就无法装载文件系统下的资源。
l 不透明性
你必须用“绝对路径”来引用Spring中的资源。
假如你使用FileSystemXmlApplicationContext来访问资源,你必须使用绝对路径来访问文件或目录资源。这妨碍了应用程序在不同系统中布署的自由。因为在不同的系统中,例如Windows和Linux,文件的绝对路径是不同的。为了系统管理的需要,有时也需要将文件或目录放在不同于开发环境的地方。
即便是访问WEB应用下的资源,或者是classpath下的资源,你也必须明确指出它们的位置,例如:WEB-INF/myFile.xml、classpath:myFile.xml等。如果我希望把classpath:myFile.xml挪到另一个物理位置,就必须修改所有的引用。
l 无扩展性
我无法在Spring ResourceLoader机制中增加一种新的装载资源的方法。例如,我希望把资源文件保存在数据库中,并用ResourceLoader来取得它。