Spring 备忘(五) - 资源访问

Spring 资源访问 

 

1. Resource 接口方法

   getInputStream(),exists(),isOpen(),getDescription(),getFile(),getURL()

 

2. 实现类

   UrlResource,ClassPathResource,FileSystemResource,

   ServletContextResource,InputStreamResource,

   ByteArrayResource.

   

3. ResourceLoader接口

   该接口实现类,可获得一个Resource实例

   ResourceLoaderAware接口实现类可获得一个ResourceLoader引用

   

   ResourceLoader接口方法,Resource getResource(String location),返回一个Resource实例.

   

4. ApplicationContext的实现类都实现了ResourceLoader接口.

   

   Resource res = ctx.getResource("some/location/file.txt");//ctx是ApplicationContext的某个实现类的实例

   默认采用和ApplicationContext相同的资源访问策略,

   比如ApplicationContext是由FileSystemXmlApplicationContext,

   则上面的res就是FileSystemResource;

   ClassPathXmlApplicationContext 对应 ClassPathResource

   XmlWebApplicationContext 对应 ServletContextResource

   

5. 使用ApplicationContext,强制指定ClassPathResource,FileSystemResource, 

   Resource res = ctx.getResource("some/location/file.txt");

   上面的调用中使用前缀:

   classpath: -- 使用 ClassPathResource 访问

   file:  -- 使用 FileSystemResource

   http:  -- 使用UrlResource

   无前缀: -- 使用ApplicationContext默认的实现类来实现Resource

   

6. ResourceLoaderAware接口

   该接口的实现类必须持有一个ResourceLoader实例.

   该接口方法 setResourceLoader(),该方法由Spring调用

   当把实现了ResourceLoaderAware接口的实例部署到Spring容器后,

   Spring容器将自身作为参数,调用setResourceLoader()方法.

   

   

7. Resource作为bean的属性注入到bean中

   配置片段:

   <bean id="test" class="xxx.xxx.TestBean">

    <property name="resource" value="classpath:book.xml" />

   </bean> 

   

   上面的TestBean类,有个setResource(Resource res)方法,setter与name对应

   value="classpath:book.xml"表示,Spring容器将一个ClassPathResource作为

   参数,传递给配置的setter.如果不采用前缀,则将采用与该ApplicationContext

   相同的资源访问策略的Resource实现类实例作为参数传递给setter.

   

8. 在ApplicationContext中访问资源(P639)

   classpath*:bean.xml,这种通配符方式访问资源,系统将搜索类加载路径,

   找出所有的匹配的文件. 这种方式 仅仅对ApplicationContext有效.

   纯Resource的实现类,不能这样配置.

   另外,还可使用ClassPathXmlApplicationContext("bean*.xml");

   中bean*.xml这种通配符方式.

   

   file:前缀使用,

   new FileSystemXmlApplicationContext("bean.xml" )和

   new FileSystemXmlApplicationContext("/bean.xml" )

   效果一样,因为FileSystemXmlApplicationContext让FileSystemResource将绝对路径当相对路径使用,

   所以在最前面加/ 无效.

   

   强制使用绝对路径,则 建议加file:前缀,

   new FileSystemXmlApplicationContext("file:bean.xml" )和

   new FileSystemXmlApplicationContext("file:/bean.xml" )

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值