spring 资源访问

spring在java基础上封装了资源访问,简单易用。

Resource接口 根据资源路径的不同提供了不同的实现类:

ByteArrayResource :通过二进制数组构造

ClassPathResource:类路径下的资源访问

FileSystemResource:文件系统资源访问

InputStreamResource:对应InputStream资源

ServletContextResource:web容器上下文资源

UrlResource:http,ftp资源....

 

EncodedResource 可以对资源进行编码 满足不同的资源类型读取操作

例子:

首先在classpath下放load.properties gbk编码

 

//FileSystemResource:文件系统资源访问

Resource fileSystem = new FileSystemResource("F:\\salmon\\WebRoot\\WEB-INF\\classes\\load.properties");

System.out.println(fileSystem.getFilename());

 

//ClassPathResource:类路径下的资源访问

 

Resource classPath = new ClassPathResource("load.properties");

System.out.println(classPath.getFilename());

 

Properties p = new Properties();

EncodedResource encRes = new EncodedResource(classPath,"gbk");

p.load(encRes.getReader());

System.out.println(p.get("salmon"));

 

以上都是通过指定具体的实现类来达到加载不同的资源目的

但是spring实现了一套资源加载接口能够通过在路径前加上区分 后统一读取资源。

 

注意:

classpath:classpath*:         ClassPathResource     

file:                                          FileSystemResource

http://                                      UrlResource

ftp:                                          UrlResource

 

classpath:classpath*:区别:像maven这样的分模块打包时候 如果出现在不同包里面出现同样前缀的资源文件  classpath:spring-*.xml  classpath*:spring-*.xml  

如果是classpath只会加载第一个包下面的   而 classpath*:spring-*.xml  会加载所有的包下面的。

 

例如:PathMatchingResourcePatternResolver支持ant类型风格匹配。

ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();

Resource res = resolver.getResource("classpath:load.properties");

encRes = new EncodedResource(res,"gbk");

p.load(encRes.getReader());

System.out.println(p.get("salmon"));

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值