Spring Resource之ResourceLoader

ResourceLoader接口意味着任何实现的对象都能够返回Resource实例.

public interface ResourceLoader {
 Resource getResource(String location);
}

所有的应用上下文实现了ResourceLoader接口,而且因此所有的应用上下文可以用于获取Resource实例。

当你在一个指定的应用上下文中调用getResource()的时候,指定的位置路径没有指定的前缀的话,你将会返回一个适合特定上下文中的Resource类型。例如,下面的代码ClassPathXmlApplicationContext实例中运行:

Resource template = ctx.getResource("some/resource/path/myTemplate.txt");

它将会返回的是一个ClassPathResource;如果相同的方法在FileSystemXmlApplicationContext实例总运行,它将会返回一个FileSystemResource.对于一个WebApplicationContext,你将会反馈一个ServletContextResource,等等。

同样的,你可以以一种合适的方法加载资源到特殊的应用上下文中。

另一方面,你可以通过执行特殊的ClassPath 前缀来强制使用ClassPathResource,而不管应用上下的类型。

Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");

相似的,也可以通过制定任何的标准的java.net.URL的前缀来强制使用URLResource:

Resource template = ctx.getResource("file:/some/resource/path/myTemplate.txt");
Resource template = ctx.getResource("http://myhost.com/resource/path/myTemplate.txt");

下面的表格总结了将String转成Resource的策略:

前缀 例子 解释
classpath: classpath:com/myapp/config.xml 从classpath中加载
file: file:/data/config.xml 从文件系统中,以一个URL的形式来加载
http: http://myserver/logo.png 以一个URL的方式来加载
(none) /data/config.xml 决定于依赖的ApplicationContext
posted on 2015-03-29 21:50  叼烟斗的纤夫  阅读(1207)  评论(0编辑  收藏  举报