Spring-资源

6 篇文章 0 订阅

Spring’s Resource interface is meant to be a more capable interface for abstracting access to low-level resources。

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();

}

spring build-in resources

  1. UrlResource
  2. ClassPathResource
  3. FileSystemResource
  4. ServletContextResource
  5. InputStreamResource
  6. ByteArrayResource

spring怎样加载这些资源

public interface ResourceLoader {

    Resource getResource(String location);

}

所有的spring context都实现了这个接口,所以可以使用spring的context加载这些资源。

例如:

Resource template = ctx.getResource("some/resource/path/myTemplate.txt");

那么,ctx获取的是哪一种类型的资源呢,是UrlResources,还是ClassPathResource。。。

这取决于ctx的类型,如果ctx是ClassPathXmlApplicationContext,则获取的是classPathResource.如果ctx是FileSystemXmlApplicationContext则获取的是FileSystemResouces.。。。

另一方面,你也可以强制spring以某种资源开式来获取:

Resource template = ctx.getResource("classpath:some/resource/path/myTemplate.txt");
则,不管ctx是什么类型,都会以ClassPathResource的形式来获取。

其它形式还有:

Prefix Example Explanation

classpath:

classpath:com/myapp/config.xml

Loaded from the classpath.

file:

file:///data/config.xml

Loaded as a URL, from the filesystem. [1]

http:

http://myserver/logo.png

Loaded as a URL.

(none)

/data/config.xml

Depends on the underlying ApplicationContext.


那么怎样在代码中获取Resource呢


实现接口的方式:

public interface ResourceLoaderAware {

    void setResourceLoader(ResourceLoader resourceLoader);
}
在spring管理的bean中实现该接口,即可获取Resources;

以注解的方式

要spring2.5以后,以

@autowired

Resouces resouces;

的方式即可注入。

方式三

又由于所有的context都实现了ResourceLoader接口,所以实现ApplicationContextAware接口也可以获取Resources。


获取Resource后,怎样注入该Resouces


class MyBean{
<span style="white-space:pre">	</span> Resouces template;
}

<bean id="myBean" class="...">
    <property name="template" value="some/resource/path/myTemplate.txt"/>
</bean>

以value=“资源路径” 的方式即可注入。spring中有个特殊的bean PropertyEditor会将相应的路径转换成Resouces。

资源路径还可以加入资源前缀。如:

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

那么怎样加载jar中的资源呢。

ApplicationContext ctx =
    new ClassPathXmlApplicationContext("classpath*:conf/appContext.xml");
以classpath*为前缀,则会加载所有jar中的conf/appContext.xml文件。在以Componet形式开的的工程中将非常有效。








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值