《Spring Recipes》第二章笔记:Loading External Resources

《Spring Recipes》第二章笔记:Loading External Resources

 

问题

程序须要从不一样的位置(文件系统,classpath,URL)读取不一样类型的资源(如文本文件,XML文件,properties文件或者图片)。程序员须要使用不一样的API来实现以上操做。java

解决方案

Spring的ResourceLoader接口提供了getResource()方法统一处理资源的加载。使用带有不一样前缀的资源路径,能够从不一样位置加载资源。程序员

  • 使用file前缀从文件系统加载资源。
  • 使用classpath前缀从classpath加载资源。
  • 使用http前缀从URL加载资源。
  • 若是不指定前缀,资源将根据Context的类型进行加载,FileSystemXmlApplicationContext从文件系统加载,ClassPathXmlApplicationContext从classpath加载。

一个类若是须要让容器注入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>
相关文章
相关标签/搜索