Spring --- Resource

本文深入探讨了Spring框架中资源文件访问的功能,包括如何使用`getResource`方法访问不同类型的资源文件,如本地文件、类路径、URL等。同时,介绍了Spring内部是如何实现这一功能的,以及如何通过`ResourceLoaderAware`接口进行资源加载器的注入。此外,还提供了资源文件通配符的使用方法,便于批量获取资源。

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

一)如何使用spring中的resource
Spring的资源文件访问功能使用起来十分简单,调用ApplicationContext.getResource的方法即可:
Resource template = ctx.getResource("some/resource/path/myTemplate.txt");
Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");
Resource template = ctx.getResource("file:/some/resource/path/myTemplate.txt");
Resource template = ctx.getResource("http://myhost.com/resource/path/myTemplate.txt");


二)resource的深入了解
其实知道了以上的gerResource方法,就已经能够满足我们日常的资源文件访问的需要了。但本着精益求精的精神,我们不妨看下spring的源码,看看spring到底是如何实现这个功能模块的。首先是接口Resource:
public interface Resource extends InputStreamSource {
boolean exists();
boolean isOpen();
URL getURL() throws IOException;
File getFile() throws IOException;
Resource createRelative(String relativePath) throws IOException;
String getFilename();
String getDescription();
}
public interface InputStreamSource {
InputStream getInputStream() throws IOException;
}

基于这个底层接口,spring运用多态继承了一系列的子类以满足不同形式的资源文件访问:
UrlResource: file: http: ftp: 的资源访问形式都是它处理啦
ClassPathResource: 看名字也猜的出来classpath:的资源访问形式就是它处理的
FileSystemResource: 从文件系统路径获取资源文件,C:\XXXXX
ServletContextResource: web应用中从context下获取资源文件,相对路径绝对路径均可
InputStreamResource: 缺省的Resource类,如果根据输入的url形式找不到对应的Resource,那么就调用它了...当然我们也可以显示的调用它:
@Test  
public void testInputStreamResource() {
ByteArrayInputStream bis = new ByteArrayInputStream("Hello World!".getBytes());
Resource resource = new InputStreamResource(bis);
if(resource.exists()) { ...... }
}


ByteArrayResource: 看代码便知...

@Test
public void testByteArrayResource() {
Resource resource = new ByteArrayResource("Hello World!".getBytes());
if(resource.exists()) { ...... }
}


三)ResourceLoaderAware
和其它Aware一样,继承此接口后,当此bean实例化时会自动调用setResourceLoader(ResourceLoader resourceLoader)方法。
public interface ResourceLoaderAware {
void setResourceLoader(ResourceLoader resourceLoader);
}


四) Resource的注入
那么,如果是一个resouce类,Spring在配置文件中改如何处理以使它自动注入呢?样例如下:
<bean id="myBean" class="...">
<property name="template" value="some/resource/path/myTemplate.txt"/>
</bean>

<property name="template" value="classpath:some/resource/path/myTemplate.txt">
<property name="template" value="file:/some/resource/path/myTemplate.txt"/>

十分方便吧~~

五)资源文件的通配样式
当你需要一次获取多个资源文件时,你可以考虑采用以下一些通配的手段:
/WEB-INF/*-context.xml
com/mycompany/**/applicationContext.xml
file:C:/some/path/*-context.xml
classpath:com/mycompany/**/applicationContext.xml
classpath*:conf/appContext.xml //获取classpath内所有的conf/appContext.xml,不加*的话只会加载搜索时遇到的第一个匹配文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值