这一节总结一下Spring关于资源的访问。
1.基础知识--3个重要接口
1)Resource 接口

是对底层资源的封装,为资源的访问提供更加方便的接口。
Resource不仅被Spring自身大量地使用,它也非常适合在你自己的代码中独立作为辅助类使用。 用户代码甚至可以在不用关心Spring其它部分的情况下访问资源。这样的确会造成代码与Spring之间的耦合,但也仅仅是与很少量的辅助类耦合。这些类可以作为比 URL 更有效的替代,而且与为这个目的而使用其它类库基本相似。
主要的实现类:
UrlResource
ClassPathResource
FileSystemResource
ServletContextResource
InputStreamResource
ByteArrayResource

2)ResourceLoader 接口


实现这个接口的类能够得到Resource实例。
主要的实现类:所有的application context。

3)ResourceLoaderAware 接口


实现这个接口的类,表示希望拥有一个ResourceLoader的引用。
当实现了 ResourceLoaderAware接口的类部署到application context(比如受Spring管理的bean)中时,它会被application context识别为 ResourceLoaderAware。接着,application context会调用setResourceLoader(ResourceLoader)方法,并把自身作为参数传入该方法(记住,所有Spring里的application context都实现了ResourceLoader接口)。




2.实际运用

1)Bean中使用资源:


通常只需让bean暴露所需的

Resource 属性,通过依赖注入Resource实例。

强制使用ClassPathResource-->
< property name ="template" value ="classpath:some/resource/path/myTemplate.txt" >



强制使用UrlResource访问本地文件资源-->
< property name ="template" value ="file:/some/resource/path/myTemplate.txt" />



Resource的类型取决于ApplicationContext的类型-->
< property name ="template" value ="some/resource/path/myTemplate.txt" />



2)ApplicationContext中使用资源


(1)手动构建ApplicationContext时,传入资源路径标识符(标识资源路径的字符串)


// Resource的类型取决于ApplicationContext的类型
ApplicationContext ctx = new ClassPathXmlApplicationContext( "conf/appContext.xml");
ApplicationContext ctx = new FileSystemClassPathXmlApplicationContext("conf/appContext.xml");



// 强制使用ClassPathResource
ApplicationContext ctx = new FileSystemXmlApplicationContext( "classpath:conf/appContext.xml");

(2)调用application context的 getResource() 方法


这里我们是将ApplicationContext作为ResourceLoader来使用,别忘了getResource()方法来自于ResourceLoader接口。


// 强制使用ClassPathResource
Resource template = ctx.getResource( "classpath:some/resource/path/myTemplate.txt");
// 强制使用UrlResource访问本地文件资源
Resource template = ctx.getResource("file:/some/resource/path/myTemplate.txt");
// 强制使用UrlResource访问web资源
Resource template = ctx.getResource("http://myhost.com/resource/path/myTemplate.txt");
// Resource的类型取决于ApplicationContext的类型
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");




3.资源路径标识符(Resource Path Identifier)

资源路径标识符(RPI),自己发明的一个词,就是标识资源路径的字符串。


从RPI到 Resource 的转换规则(资源的访问策略)


前缀

例子

说明

 classpath:

classpath:com/myapp/config.xml

强制使用ClassPathResource

 file:

file:/data/config.xml

强制使用UrlResource访问本地文件资源

 http:

[url]http://myserver/logo.png[/url]

强制使用UrlResource访问web资源

 (none)

/data/config.xml

Resource的类型取决于ApplicationContext的类型

 classpath*:

 classpath*:conf/appContext.xml

只在application context构造器的资源路径中有效,表示所有与给定名称匹配的classpath资源都应该被获取。