《Spring Recipes》第二章笔记:Loading External Resources
问题
程序需要从不同的位置(文件系统,classpath,URL)读取不同类型的资源(如文本文件,XML文件,properties文件或者图片)。程序员需要使用不同的API来实现以上操作。
解决方案
Spring的ResourceLoader接口提供了getResource()方法统一处理资源的加载。使用带有不同前缀的资源路径,可以从不同位置加载资源。
- 使用file前缀从文件系统加载资源。
- 使用classpath前缀从classpath加载资源。
- 使用http前缀从URL加载资源。
- 如果不指定前缀,资源将根据Context的类型进行加载,FileSystemXmlApplicationContext从文件系统加载,ClassPathXmlApplicationContext从classpath加载。
一个类如果需要让容器注入ResourceLoader,需要实现ApplicationContextAware接口,或者ResourceLoaderAware接口。
例:
public class MyResourceLoader implements ResourceLoaderAware {
private ResourceLoader rs;
@Override
public void setResourceLoader(ResourceLoader rs) {
this.rs = rs;
}
public void getFile() throws FileNotFoundException, IOException {
Resource f = rs.getResource("file:D:/Windowssrsi2.ini");
printFileContent(f);
}
public void getClasspathFile() throws FileNotFoundException, IOException {
Resource f = rs
.getResource("classpath:com/ljm/springrecipses/getresource/bean.xml");
printFileContent(f);
}
}
注入资源
Spring支持将Resource作为依赖进行注入。
bean:
public class BannerLoader {
private Resource banner;
public void setBanner(Resource banner) {
this.banner = banner;
}
... ...
}
配置文件:直接在value中设定Resource的路径。
<bean id="bannerLoader"
class="com.apress.springrecipes.shop.BannerLoader"
init-method="showBanner">
<property name="banner">
<value>classpath:com/apress/springrecipes/shop/banner.txt</value>
</property>
</bean>