4.1.1 概述

在日常程序开发中,处理外部资源是很繁琐的事情,我们可能需要处理URL资源、File资源资源、ClassPath相关资源、服务器相关资源(JBoss AS 5.x上的VFS资源)等等很多资源。因此处理这些资源需要使用不同的接口,这就增加了我们系统的复杂性;而且处理这些资源步骤都是类似的(打开资源、读取资源、关闭资源),因此如果能抽象出一个统一的接口来对这些底层资源进行统一访问,是不是很方便,而且使我们系统更加简洁,都是对不同的底层资源使用同一个接口进行访问。
Spring 提供一个Resource接口来统一这些底层资源一致的访问,而且提供了一些便利的接口,从而能提供我们的生产力。
4.1.2 Resource接口
Spring的Resource接口代表底层外部资源,提供了对底层外部资源的一致性访问接口。


Java代码 收藏代码
public interface InputStreamSource {
InputStream getInputStream() throws IOException;
}


Java代码 收藏代码
public interface Resource extends InputStreamSource {
boolean exists();
boolean isReadable();
boolean isOpen();
URL getURL() throws IOException;
URI getURI() throws IOException;
File getFile() throws IOException;
long contentLength() throws IOException;
long lastModified() throws IOException;
Resource createRelative(String relativePath) throws IOException;
String getFilename();
String getDescription();
}


1)InputStreamSource接口解析:
getInputStream:每次调用都将返回一个新鲜的资源对应的java.io. InputStream字节流,调用者在使用完毕后必须关闭该资源。
2)Resource接口继承InputStreamSource接口,并提供一些便利方法:
exists:返回当前Resource代表的底层资源是否存在,true表示存在。
isReadable:返回当前Resource代表的底层资源是否可读,true表示可读。
isOpen:返回当前Resource代表的底层资源是否已经打开,如果返回true,则只能被读取一次然后关闭以避免资源泄露;常见的Resource实现一般返回false。
getURL:如果当前Resource代表的底层资源能由java.util.URL代表,则返回该URL,否则抛出IOException。
getURI:如果当前Resource代表的底层资源能由java.util.URI代表,则返回该URI,否则抛出IOException。
getFile:如果当前Resource代表的底层资源能由java.io.File代表,则返回该File,否则抛出IOException。
contentLength:返回当前Resource代表的底层文件资源的长度,一般是值代表的文件资源的长度。
lastModified:返回当前Resource代表的底层资源的最后修改时间。
createRelative:用于创建相对于当前Resource代表的底层资源的资源,比如当前Resource代表文件资源“d:/test/”则createRelative(“test.txt”)将返回表文件资源“d:/test/test.txt”Resource资源。
getFilename:返回当前Resource代表的底层文件资源的文件路径,比如File资源“file://d:/test.txt”将返回“d:/test.txt”,而URL资源http://www.javass.cn将返回“”,因为只返回文件路径。
getDescription:返回当前Resource代表的底层资源的描述符,通常就是资源的全路径(实际文件名或实际URL地址)。

Resource接口提供了足够的抽象,足够满足我们日常使用。而且提供了很多内置Resource实现:ByteArrayResource、InputStreamResource 、FileSystemResource 、UrlResource 、ClassPathResource、ServletContextResource、VfsResource等。
4.2 内置Resource实现

4.2.1 ByteArrayResource
ByteArrayResource代表byte[]数组资源,对于“getInputStream”操作将返回一个ByteArrayInputStream。
首先让我们看下使用ByteArrayResource如何处理byte数组资源:


Java代码 收藏代码

package cn.javass.spring.chapter4;
import java.io.IOException;
import java.io.InputStream;
import org.junit.Test;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
public class ResourceTest {
@Test
public void testByteArrayResource() {
Resource resource = new ByteArrayResource("Hello World!".getBytes());
if(resource.exists()) {
dumpStream(resource);
}
}
}

是不是很简单,让我们看下“dumpStream”实现:


Java代码 收藏代码
private void dumpStream(Resource resource) {
InputStream is = null;
try {
//1.获取文件资源
is = resource.getInputStream();
//2.读取资源
byte[] descBytes = new byte[is.available()];
is.read(descBytes);
System.out.println(new String(descBytes));
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
//3.关闭资源
is.close();
} catch (IOException e) {
}
}
}

让我们来仔细看一下代码,dumpStream方法很抽象定义了访问流的三部曲:打开资源、读取资源、关闭资源,所以dunpStrean可以再进行抽象从而能在自己项目中使用;byteArrayResourceTest测试方法,也定义了基本步骤:定义资源、验证资源存在、访问资源。

ByteArrayResource可多次读取数组资源,即isOpen ()永远返回false。

1.2.2 InputStreamResource
InputStreamResource代表java.io.InputStream字节流,对于“getInputStream ”操作将直接返回该字节流,因此只能读取一次该字节流,即“isOpen”永远返回true。
让我们看下测试代码吧:


Java代码 收藏代码
@Test
public void testInputStreamResource() {
ByteArrayInputStream bis = new ByteArrayInputStream("Hello World!".getBytes());
Resource resource = new InputStreamResource(bis);
if(resource.exists()) {
dumpStream(resource);
}
Assert.assertEquals(true, resource.isOpen());
}


测试代码几乎和ByteArrayResource测试完全一样,注意“isOpen”此处用于返回true。

4.2.3 FileSystemResource
FileSystemResource代表java.io.File资源,对于“getInputStream ”操作将返回底层文件的字节流,“isOpen”将永远返回false,从而表示可多次读取底层文件的字节流。
让我们看下测试代码吧:


Java代码 收藏代码
@Test
public void testFileResource() {
File file = new File("d:/test.txt");
Resource resource = new FileSystemResource(file);
if(resource.exists()) {
dumpStream(resource);
}
Assert.assertEquals(false, resource.isOpen());
}


注意由于“isOpen”将永远返回false,所以可以多次调用dumpStream(resource)。

4.2.4 ClassPathResource
ClassPathResource代表classpath路径的资源,将使用ClassLoader进行加载资源。classpath 资源存在于类路径中的文件系统中或jar包里,且“isOpen”永远返回false,表示可多次读取资源。
ClassPathResource加载资源替代了Class类和ClassLoader类的“getResource(String name)”和“getResourceAsStream(String name)”两个加载类路径资源方法,提供一致的访问方式。
ClassPathResource提供了三个构造器:
public ClassPathResource(String path):使用默认的ClassLoader加载“path”类路径资源;
public ClassPathResource(String path, ClassLoader classLoader):使用指定的ClassLoader加载“path”类路径资源;
比如当前类路径是“cn.javass.spring.chapter4.ResourceTest”,而需要加载的资源路径是“cn/javass/spring/chapter4/test1.properties”,则将加载的资源在“cn/javass/spring/chapter4/test1.properties”;
public ClassPathResource(String path, Class<?> clazz):使用指定的类加载“path”类路径资源,将加载相对于当前类的路径的资源;
比如当前类路径是“cn.javass.spring.chapter4.ResourceTest”,而需要加载的资源路径是“cn/javass/spring/chapter4/test1.properties”,则将加载的资源在“cn/javass/spring/chapter4/cn/javass/spring/chapter4/test1.properties”;
而如果需要 加载的资源路径为“test1.properties”,将加载的资源为“cn/javass/spring/chapter4/test1.properties”。

让我们直接看测试代码吧:
1)使用默认的加载器加载资源,将加载当前ClassLoader类路径上相对于根路径的资源:


Java代码 收藏代码
@Test
public void testClasspathResourceByDefaultClassLoader() throws IOException {
Resource resource = new ClassPathResource("cn/javass/spring/chapter4/test1.properties");
if(resource.exists()) {
dumpStream(resource);
}
System.out.println("path:" + resource.getFile().getAbsolutePath());
Assert.assertEquals(false, resource.isOpen());
}


2)使用指定的ClassLoader进行加载资源,将加载指定的ClassLoader类路径上相对于根路径的资源:


Java代码 收藏代码
@Test
public void testClasspathResourceByClassLoader() throws IOException {
ClassLoader cl = this.getClass().getClassLoader();
Resource resource = new ClassPathResource("cn/javass/spring/chapter4/test1.properties" , cl);
if(resource.exists()) {
dumpStream(resource);
}
System.out.println("path:" + resource.getFile().getAbsolutePath());
Assert.assertEquals(false, resource.isOpen());
}

3)使用指定的类进行加载资源,将尝试加载相对于当前类的路径的资源:


Java代码 收藏代码
@Test
public void testClasspathResourceByClass() throws IOException {
Class clazz = this.getClass();
Resource resource1 = new ClassPathResource("cn/javass/spring/chapter4/test1.properties" , clazz);
if(resource1.exists()) {
dumpStream(resource1);
}
System.out.println("path:" + resource1.getFile().getAbsolutePath());
Assert.assertEquals(false, resource1.isOpen());

Resource resource2 = new ClassPathResource("test1.properties" , this.getClass());
if(resource2.exists()) {
dumpStream(resource2);
}
System.out.println("path:" + resource2.getFile().getAbsolutePath());
Assert.assertEquals(false, resource2.isOpen());
}
“resource1”将加载cn/javass/spring/chapter4/cn/javass/spring/chapter4/test1.properties资源;“resource2”将加载“cn/javass/spring/chapter4/test1.properties”;

4)加载jar包里的资源,首先在当前类路径下找不到,最后才到Jar包里找,而且在第一个Jar包里找到的将被返回:


Java代码 收藏代码
@Test
public void classpathResourceTestFromJar() throws IOException {
Resource resource = new ClassPathResource("overview.html");
if(resource.exists()) {
dumpStream(resource);
}
System.out.println("path:" + resource.getURL().getPath());
Assert.assertEquals(false, resource.isOpen());
}

如果当前类路径包含“overview.html”,在项目的“resources”目录下,将加载该资源,否则将加载Jar包里的“overview.html”,而且不能使用“resource.getFile()”,应该使用“resource.getURL()”,因为资源不存在于文件系统而是存在于jar包里,URL类似于“file:/C:/.../***.jar!/overview.html”。
类路径一般都是相对路径,即相对于类路径或相对于当前类的路径,因此如果使用“/test1.properties”带前缀“/”的路径,将自动删除“/”得到“test1.properties”。

4.2.5 UrlResource
UrlResource代表URL资源,用于简化URL资源访问。“isOpen”永远返回false,表示可多次读取资源。
UrlResource一般支持如下资源访问:
http:通过标准的http协议访问web资源,如new UrlResource(“http://地址”);
ftp:通过ftp协议访问资源,如new UrlResource(“ftp://地址”);
file:通过file协议访问本地文件系统资源,如new UrlResource(“file:d:/test.txt”);
具体使用方法在此就不演示了,可以参考cn.javass.spring.chapter4.ResourceTest中urlResourceTest测试方法。

4.2.6 ServletContextResource
ServletContextResource代表web应用资源,用于简化servlet容器的ServletContext接口的getResource操作和getResourceAsStream操作;在此就不具体演示了。

4.2.7 VfsResource
VfsResource代表Jboss 虚拟文件系统资源。

Jboss VFS(Virtual File System)框架是一个文件系统资源访问的抽象层,它能一致的访问物理文件系统、jar资源、zip资源、war资源等,VFS能把这些资源一致的映射到一个目录上,访问它们就像访问物理文件资源一样,而其实这些资源不存在于物理文件系统。
在示例之前需要准备一些jar包,在此我们使用的是Jboss VFS3版本,可以下载最新的Jboss AS 6x,拷贝lib目录下的“jboss-logging.jar”和“jboss-vfs.jar”两个jar包拷贝到我们项目的lib目录中并添加到“Java Build Path”中的“Libaries”中。
让我们看下示例(cn.javass.spring.chapter4.ResourceTest):


Java代码 收藏代码
@Test
public void testVfsResourceForRealFileSystem() throws IOException {
//1.创建一个虚拟的文件目录
VirtualFile home = VFS.getChild("/home");
//2.将虚拟目录映射到物理的目录
VFS.mount(home, new RealFileSystem(new File("d:")));
//3.通过虚拟目录获取文件资源
VirtualFile testFile = home.getChild("test.txt");
//4.通过一致的接口访问
Resource resource = new VfsResource(testFile);
if(resource.exists()) {
dumpStream(resource);
}
System.out.println("path:" + resource.getFile().getAbsolutePath());
Assert.assertEquals(false, resource.isOpen());
}
@Test
public void testVfsResourceForJar() throws IOException {
//1.首先获取jar包路径
File realFile = new File("lib/org.springframework.beans-3.0.5.RELEASE.jar");
//2.创建一个虚拟的文件目录
VirtualFile home = VFS.getChild("/home2");
//3.将虚拟目录映射到物理的目录
VFS.mountZipExpanded(realFile, home,
TempFileProvider.create("tmp", Executors.newScheduledThreadPool(1)));
//4.通过虚拟目录获取文件资源
VirtualFile testFile = home.getChild("META-INF/spring.handlers");
Resource resource = new VfsResource(testFile);
if(resource.exists()) {
dumpStream(resource);
}
System.out.println("path:" + resource.getFile().getAbsolutePath());
Assert.assertEquals(false, resource.isOpen());
}


通过VFS,对于jar里的资源和物理文件系统访问都具有一致性,此处只是简单示例,如果需要请到Jboss官网深入学习。
4.3.1 ResourceLoader接口
ResourceLoader接口用于返回Resource对象;其实现可以看作是一个生产Resource的工厂类。


Java代码 收藏代码
public interface ResourceLoader {
Resource getResource(String location);
ClassLoader getClassLoader();
}

getResource接口用于根据提供的location参数返回相应的Resource对象;而getClassLoader则返回加载这些Resource的ClassLoader。

Spring提供了一个适用于所有环境的DefaultResourceLoader实现,可以返回ClassPathResource、UrlResource;还提供一个用于web环境的ServletContextResourceLoader,它继承了DefaultResourceLoader的所有功能,又额外提供了获取ServletContextResource的支持。

ResourceLoader在进行加载资源时需要使用前缀来指定需要加载:“classpath:path”表示返回ClasspathResource,“http://path”和“file:path”表示返回UrlResource资源,如果不加前缀则需要根据当前上下文来决定,DefaultResourceLoader默认实现可以加载classpath资源,如代码所示(cn.javass.spring.chapter4.ResourceLoaderTest):


Java代码 收藏代码
@Test
public void testResourceLoad() {
ResourceLoader loader = new DefaultResourceLoader();
Resource resource = loader.getResource("classpath:cn/javass/spring/chapter4/test1.txt");
//验证返回的是ClassPathResource
Assert.assertEquals(ClassPathResource.class, resource.getClass());
Resource resource2 = loader.getResource("file:cn/javass/spring/chapter4/test1.txt");
//验证返回的是ClassPathResource
Assert.assertEquals(UrlResource.class, resource2.getClass());
Resource resource3 = loader.getResource("cn/javass/spring/chapter4/test1.txt");
//验证返默认可以加载ClasspathResource
Assert.assertTrue(resource3 instanceof ClassPathResource);
}

对于目前所有ApplicationContext都实现了ResourceLoader,因此可以使用其来加载资源。
ClassPathXmlApplicationContext:不指定前缀将返回默认的ClassPathResource资源,否则将根据前缀来加载资源;
FileSystemXmlApplicationContext:不指定前缀将返回FileSystemResource,否则将根据前缀来加载资源;
WebApplicationContext:不指定前缀将返回ServletContextResource,否则将根据前缀来加载资源;
其他:不指定前缀根据当前上下文返回Resource实现,否则将根据前缀来加载资源。

4.3.2 ResourceLoaderAware接口
ResourceLoaderAware是一个标记接口,用于通过ApplicationContext上下文注入ResourceLoader。


Java代码 收藏代码
public interface ResourceLoaderAware {
void setResourceLoader(ResourceLoader resourceLoader);
}

让我们看下测试代码吧:

1) 首先准备测试Bean,我们的测试Bean还简单只需实现ResourceLoaderAware接口,然后通过回调将ResourceLoader保存下来就可以了:


Java代码 收藏代码
package cn.javass.spring.chapter4.bean;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.ResourceLoader;
public class ResourceBean implements ResourceLoaderAware {
private ResourceLoader resourceLoader;
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
public ResourceLoader getResourceLoader() {
return resourceLoader;
}
}


2) 配置Bean定义(chapter4/resourceLoaderAware.xml):


Java代码 收藏代码

<bean class="cn.javass.spring.chapter4.bean.ResourceBean"/>

3)测试(cn.javass.spring.chapter4.ResoureLoaderAwareTest):


Java代码 收藏代码
@Test
public void test() {
ApplicationContext ctx = new ClassPathXmlApplicationContext("chapter4/resourceLoaderAware.xml");
ResourceBean resourceBean = ctx.getBean(ResourceBean.class);
ResourceLoader loader = resourceBean.getResourceLoader();
Assert.assertTrue(loader instanceof ApplicationContext);
}

注意此处“loader instanceof ApplicationContext”,说明了ApplicationContext就是个ResoureLoader。
由于上述实现回调接口注入ResourceLoader的方式属于侵入式,所以不推荐上述方法,可以采用更好的自动注入方式,如“byType”和“constructor”,此处就不演示了。

4.3.3 注入Resource
通过回调或注入方式注入“ResourceLoader”,然后再通过“ResourceLoader”再来加载需要的资源对于只需要加载某个固定的资源是不是很麻烦,有没有更好的方法类似于前边实例中注入“java.io.File”类似方式呢?

Spring提供了一个PropertyEditor “ResourceEditor”用于在注入的字符串和Resource之间进行转换。因此可以使用注入方式注入Resource。

ResourceEditor完全使用ApplicationContext根据注入的路径字符串获取相应的Resource,说白了还是自己做还是容器帮你做的问题。

接下让我们看下示例:
1)准备Bean:


Java代码 收藏代码
package cn.javass.spring.chapter4.bean;
import org.springframework.core.io.Resource;
public class ResourceBean3 {
private Resource resource;
public Resource getResource() {
return resource;
}
public void setResource(Resource resource) {
this.resource = resource;
}
}


2)准备配置文件(chapter4/ resourceInject.xml):


Java代码 收藏代码
<bean );”

相关文章:

  • 2021-08-20
  • 2021-12-22
  • 2021-12-21
  • 2022-12-23
  • 2021-09-24
  • 2021-07-06
  • 2022-02-20
猜你喜欢
  • 2021-05-15
  • 2021-02-19
  • 2022-12-23
  • 2021-08-01
  • 2021-08-22
  • 2021-12-26
  • 2021-12-24
相关资源
相似解决方案