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

本文深入探讨了Spring框架如何通过ResourceLoader接口统一处理资源的加载,包括从文件系统、classpath、URL等不同位置加载不同类型的资源,并展示了如何将Resource作为依赖进行注入,以及在配置文件中设定Resource路径的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

《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>

  

 

转载于:https://my.oschina.net/pkpk1234/blog/58000

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值