程序须要从不一样的位置(文件系统,classpath,URL)读取不一样类型的资源(如文本文件,XML文件,properties文件或者图片)。程序员须要使用不一样的API来实现以上操做。java
Spring的ResourceLoader接口提供了getResource()方法统一处理资源的加载。使用带有不一样前缀的资源路径,能够从不一样位置加载资源。程序员
一个类若是须要让容器注入ResourceLoader,须要实现ApplicationContextAware接口,或者ResourceLoaderAware接口。web
例:spring
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做为依赖进行注入。ide
bean:this
public class BannerLoader { private Resource banner; public void setBanner(Resource banner) { this.banner = banner; } ... ... }
配置文件:直接在value中设定Resource的路径。spa
<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>