这里的Resource并不是指我们所用的@Resource注解,这里的Resource值对各种资源的抽象在应用中我们通常使用URL来定位一些资源,我们经常使用URL前缀来区分定位不同类型的资源,比如使用http:来定位http资源,使用ftp:获得ftp资源等,Spring提供了一个Resource接口来抽象各种资源,比如从文件系统、系统类路径classpath、网络、输入流、或者谁ServletContext中获得资源。
1、几个Spring内置的Resource接口实现类
2、ResourceLoader接口
3、ResourceLoaderAware接口
4、使用通配符指定资源路径(为了应用的灵活性和简单等我们可以使用统配符来配置资源路径,Spring文档内描述的很清楚这里不过是简单的描述,当你有这方面的需求再去查文档就可以)
1、几个Spring内置的Resource接口实现类
ClassPathResource:从名字我们可以看出它代表从ClassPath下加载的资源
FileSystemResource:代表从文件系统中加载的资源
ServletContextResource:代表从ServletContext中获得的资源
InputStreamResource:代表从输入流中获得的资源
ByteArrayResource:它根据一个给的的array创建一个ByteArrayInputStream资源
这里所说的资源是一个抽象,可以代表数据、对象、文件等。
2、ResourceLoader接口
2.1ResourceLoader
ResourceLoader是一个资源加载器接口,通过getResource(String resName)返回资源:
Resource template = ctx.getResource("beans.txt");
ctx为ClassPathXmlApplicationContext的一个实例(并不一定是这个类我们会在后面说明),你可以通过getResource()得到资源,默认的这个beans.txt是从classpath下查找的。
你还可以这样使用:
Resource template = ctx.getResource("classpath:beans.txt"); //这同意是在classpath下寻找资源
Resource template = ctx.getResource("file:/beans.txt"); //从文件系统中寻找获得资源
Resource template = ctx.getResource("http://www.weicoop.com/beans.txt"); //从http中获得资源
说明:
1、你可以通过一个前缀行http、file等指定如何获取资源;
2、*ApplicationContext本身是实现了Resource接口的所以你可以使用ctx.getResource("beans.txt")获得beans.txt数据,这里的*ApplicationContext代表我吗在Spring Ioc中提到的各种ApplicationContext,例如ClassPathXmlApplicationContext、FileSystemApplicationContext、WebApplicationContext等;
3、如果你使用FileSystemApplicationContext 那么ctx.getResource("beans.txt")则默认是从文件系统中查找资源,你也可使用URL前缀来修改默认加载资源方式
3、ResourceLoaderAware接口
该接口提供了一个方法
public interface ResourceLoaderAware { void setResourceLoader(ResourceLoader resourceLoader); }
实现此接口的类表明此类希望通过ResourceLoader来提供资源,当此类配置成为Spring管理时(可以通过@Component注解声明)在Spring初始化后会调用此类的setResource()接口来设置资源;
例:
MResource.java
package org.fp.smark.spring3;
import org.springframework.context.ResourceLoaderAware;
@Component //声明通过Spring来管理
public class MResource implements ResourceLoaderAware{
public void setResourceLoader(ResourceLoader arg0) {
System.out.println("resource loader set ");
}
}
Test.java
package org.fp.smark.spring3;
import java.io.IOException;
public class IOCTest {
@Test
public void test1() throws IOException {
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
}
}
Console输出: