2.4. ResourceLoader接口
ResourceLoader接口旨在由可以返回(即加载)Resource实例的对象实现。以下清单显示了ResourceLoader 接口定义:
public interface ResourceLoader {
    Resource getResource(String location);
    ClassLoader getClassLoader();
}所有应用程序上下文都实现了该ResourceLoader接口。因此,所有应用程序上下文都可以用于获取Resource实例。
当您调用getResource()特定的应用程序上下文,并且指定的位置路径没有特定的前缀时,您将返回Resource适合该特定应用程序上下文的类型。例如,假设下面的代码片段是针对一个ClassPathXmlApplicationContext实例运行的:
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");针对 ClassPathXmlApplicationContext,该代码返回 ClassPathResource。如果对FileSystemXmlApplicationContext实例运行相同的方法,它将返回一个FileSystemResource. 对于 WebApplicationContext,它将返回 ServletContextResource。它同样会为每个上下文返回适当的对象。
因此,您可以以适合特定应用程序上下文的方式加载资源。
另一方面,您也可以通过指定classpath:特殊前缀来强制使用ClassPathResource,无论应用程序上下文类型如何,如以下示例所示:
Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");同样,您可以通过指定任何标准 java.net.URL前缀来强制使用 UrlResource。以下示例使用file和https前缀:
Resource template = ctx.getResource("file:///some/resource/path/myTemplate.txt");Resource template = ctx.getResource("https://myhost.com/resource/path/myTemplate.txt");下表总结了将String对象转换为Resource 对象的策略:
classpath:
classpath:com/myapp/config.xml
从类路径加载。
https:
https://myserver/logo.png
加载为URL.
无
/data/config.xml
取决于底层ApplicationContext。
最后更新于
这有帮助吗?