Spring -- 5.Resources

本文详细介绍了Spring中不同类型的Resource,包括UrlResource, ClassPathResource, FileSystemResource, ServletContextResource, InputStreamResource和ByteArrayResource的用法。重点讲解了ResourceLoader接口及其在加载资源时的不同定位方式,如URL、类路径、文件系统和ServletContext。同时展示了如何通过ApplicationContext获取Resource实例,并解释了在无前缀时默认的加载策略。" 50516985,1097439,Linux C编程指南,"['Linux', 'C编程', 'GCC', '库管理', '网络编程']

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

以下为学习笔记


UrlResource:URL对应的资源,根据一个URL地址去构建

ClassPathResource:对应类路径下的资源文件(相对路径)

FileSystemResource:获取文件系统里面的资源(绝对路径)

ServletContextResource:ServletContext封装的资源用于访问ServletContext环境下的资源(与web相关的入口)

InputStreamResource:针对于输入流封装的资源

ByteArrayResource:针对于字节数组封装的资源



ResourceLoader

对resource进行加载

public interface ResourceLoader{

Resource gerResource(String location);

}


Resource remplate = ctx.getResource("some/resource/path/my.txt");

Resource remplate = ctx.getResource("classpath:some/resource/path/my.txt");

Resource remplate = ctx.getResource("file:/some/resource/path/my.txt");

http: --http://myserver/logo.png

(none) -- /data/config.xml


---------------------------------


public class MyResource implements ApplicationContextAware {

private ApplicationContext applicationContext;


//获取到applicationContext并且赋值

@Override

public void setApplicationContext(ApplicationContext applicationContext) throws BeansException{

this.applicationContext = applicationContext;

}


public void resource(){

applicationContext.gerResource("classpath:config.txt");

applicationContext.gerResource("file:D:\\ddd\web_projects\\spring\\src\\main\\resources\\config.txt");

applicationContext.gerResource("url:http://docs.spring.io/spring/docs/4.0.5/RELEASE/spring-framework-reference/htmlsingle");

applicationContext.gerResource("config.txt");

//没有前缀的时候,依赖于applicationContext,默认classpath的方式加载,是取super("classpath:xxx")传入的那个classpath


}












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值