Spring Core 之 Resources


Java’s standard java.net.URL class and standard handlers for various URL prefixes, unfortunately, are not quite adequate enough for all access to low-level resources. For example, there is no standardized URL implementation that may be used to access a resource that needs to be obtained from the classpath or relative to a ServletContext. While it is possible to register new handlers for specialized URL prefixes (similar to existing handlers for prefixes such as http:), this is generally quite complicated, and the URL interface still lacks some desirable functionality, such as a method to check for the existence of the resource being pointed to.

java中有标准的java.net.URL类和对各种URL的标准处理器,但是它们并不十分适合访问低级资源。例如,没有一个标准的URL实现类可以用来访问类路径下的资源。注册一个新的特殊场景的URL处理器是非常复杂的,并且URL 接口仍然缺乏一些理想的功能,例如检查所指向资源是否存在的方法。

一、The Resource Interface

Spring’s Resource interface located in the org.springframework.core.io. package is meant to be a more capable interface for abstracting access to low-level resources. The following listing provides an overview of the Resource interface.

Spring 的 Resource 接口位于 org.springframework.core.io 包中。旨在成为一个更强大的接口,用于抽象对低级资源的访问。以下清单提供了 Resource 接口的概述。

public interface Resource extends InputStreamSource{
boolean exists();

    boolean isReadable();

    boolean isOpen();

    boolean isFile();

    URL getURL() throws IOException;

    URI getURI() throws IOException;

    File getFile() throws IOException;

    ReadableByteChannel readableChannel() throws IOException;

    long contentLength() throws IOException;

    long lastModified() throws IOException;

    Resource createRelative(String relativePath) throws IOException;

    String getFilename();

    String getDescription();
}

Some implementations of the Resource interface also implement the extended WritableResource interface for a resource that supports writing to it.Spring itself uses the Resource abstraction extensively, as an argument type in many method signatures when a resource is needed. Other methods in some Spring APIs (such as the constructors to various ApplicationContext implementations) take a String which in unadorned or simple form is used to create a Resource appropriate to that context implementation or, via special prefixes on the String path, let the caller specify that a specific Resource implementation must be created and used.

Resource 接口的一些实现还为支持写入资源扩展实现了 WritableResource 接口。Spring 本身广泛使用 Resource 抽象,作为需要资源时许多方法签名中的参数类型。某些 Spring API 中的其他方法(例如各种 ApplicationContext 实现的构造函数)采用一个字符串,该字符串以未修饰或简单的形式用于创建适合该上下文实现的资源,或者,通过字符串路径上的特殊前缀,让调用者指定必须创建和使用特定的资源实现。

二、Built-in Resource Implementations(内置的Resource实现)

1、UrlResource
UrlResource wraps a java.net.URL and can be used to access any object that is normally accessible with a URL, such as files, an HTTPS target, an FTP target, and others. All URLs have a standardized String representation, such that appropriate standardized prefixes are used to indicate one URL type from another. This includes file: for accessing filesystem paths, https: for accessing resources through the HTTPS protocol, ftp: for accessing resources through FTP, and others.

UrlResource 包装了一个 java.net.URL,可用于访问能通过 URL 访问的任何对象,例如文件、HTTPS 目标、FTP 目标等。所有 URL 都具有标准化的字符串表示形式,以便使用适当的标准化前缀来指示一种 URL 类型和另一种 URL 类型。这包括 file:用于访问文件系统路径、https:用于通过 HTTPS 协议访问资源、ftp:用于通过 FTP 访问资源等。

2、ClassPathResource
This class represents a resource that should be obtained from the classpath. It uses either the thread context class loader, a given class loader, or a given class for loading resources.

此类表示应从类路径中获取的资源。它使用线程上下文类加载器、给定的类加载器或给定的类来加载资源。

3、FileSystemResource
This is a Resource implementation for java.io.File handles. It also supports java.nio.file.Path handles, applying Spring’s standard String-based path transformations but performing all operations via the java.nio.file.Files API. For pure java.nio.path.Path based support use a PathResource instead. FileSystemResource supports resolution as a File and as a URL.

FileSystemResource是 java.io.File 的 Resource 实现。它还支持 java.nio.file.Path ,应用 Spring 的标准基于字符串的路径转换,但通过 java.nio.file.Files API 执行所有操作。对于纯基于 java.nio.path.Path 的支持,请改用 PathResource。 FileSystemResource 支持解析文件和 URL。

4、PathResource
This is a Resource implementation for java.nio.file.Path handles, performing all operations and transformations via the Path API. It supports resolution as a File and as a URL and also implements the extended WritableResource interface. PathResource is effectively a pure java.nio.path.Path based alternative to FileSystemResource with different createRelative behavior.

PathResource是 java.nio.file.Path 的 Resource 实现,通过 Path API 执行所有操作和转换。它支持解析为文件和 URL,还扩展实现了 WritableResource 接口。PathResource 实际上是一个基于纯 java.nio.path.Path 的 FileSystemResource 替代品,具有不同的 createRelative 行为。

5、ServletContextResource
This is a Resource implementation for ServletContext resources that interprets relative paths within the relevant web application’s root directory.

这是 ServletContext 资源的 Resource 实现,用于解释相关 Web 应用程序根目录中的相对路径。

6、InputStreamResource
An InputStreamResource is a Resource implementation for a given InputStream. It should be used only if no specific Resource implementation is applicable.

InputStreamResource 是对给定 InputStream 的 Resource 实现。它应该仅在没有合适的特定Resource实现时使用。

7、ByteArrayResource
This is a Resource implementation for a given byte array. It creates a ByteArrayInputStream for the given byte array.

这是对给定字节数组的资源实现。它为给定的字节数组创建一个 ByteArrayInputStream。

三、The ResourceLoader Interface

The ResourceLoader interface is meant to be implemented by objects that can return (that is, load) Resource instances. The following listing shows the ResourceLoader interface definition:

ResourceLoader 接口旨在由可以返回(即加载)实现Resource的 实例对象。以下代码显示了 ResourceLoader 接口定义:

public interface ResourceLoader{

    Resource getResource(String location);
    
    ClassLoader getClassLoader();
}

All application contexts implement the ResourceLoader interface. Therefore, all application contexts may be used to obtain Resource instances.When you call getResource() on a specific application context, and the location path specified doesn’t have a specific prefix, you get back a Resource type that is appropriate to that particular application context. For example, assume the following snippet of code was run against a ClassPathXmlApplicationContext instance:

所有的应用上下文都实现了ResourceLoader接口,因此,所有的应用上下文都可以用来获取Resource实例。当你调用一个特定应用上下文的getResource()方法,并且使用没有特定前缀的位置路径时,你将会得到特定应用上下文相关的一个Resource。例如,假设以下代码片段中基于ClassPathXmlApplicationContext 实例获取Resource:

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

Against a ClassPathXmlApplicationContext, that code returns a ClassPathResource. If the same method were run against a FileSystemXmlApplicationContext instance, it would return a FileSystemResource. As a result, you can load resources in a fashion appropriate to the particular application context.On the other hand, you may also force ClassPathResource to be used, regardless of the application context type, by specifying the special classpath: prefix, as the following example shows:

对于 ClassPathXmlApplicationContext,该代码返回一个 ClassPathResource。如果对 FileSystemXmlApplicationContext 实例运行相同的方法,它将返回一个 FileSystemResource。因此,你可以以适合特定应用程序上下文的方式加载资源。另一方面,你也可以通过指定特殊的 classpath: 前缀来强制使用 ClassPathResource,而不管应用程序上下文类型如何,如下例所示:

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

四、The ResourcePatternResolver Interface

The ResourcePatternResolver interface is an extension to the ResourceLoader interface which defines a strategy for resolving a location pattern (for example, an Ant-style path pattern) into Resource objects.

ResourcePatternResolver接口是ResourceLoader接口的一个扩展,其定义了一个解析路径模式(例如,一个Ant风格路径模式)为Resource对象的策略。

public interface ResourcePatternResolver extends ResourceLoader{
    String CLASSPATH_ALL_URL_PREFIX = "classpath*:";
    Resource[] getResources(String locationPattern) throws IOException;
}

As can be seen above, this interface also defines a special classpath*: resource prefix for all matching resources from the class path. Note that the resource location is expected to be a path without placeholders in this case — for example, classpath*:/config/beans.xml. JAR files or different directories in the class path can contain multiple files with the same path and the same name.

正如以上所见,ResourcePatternResolver接口定义了一个特殊的classpath*: 资源前缀来匹配类路径下所有匹配的资源。注意在此处,资源路径中不能存在占位符,例如,classpath*:/config/beans.xml。 JAR 文件或类路径中的不同目录可以包含多个具有相同路径和相同名称的文件。

五、Application Contexts and Resource Paths(应用上下文和资源路径)

1、Constructing Application Contexts(构建应用上下文)

An application context constructor (for a specific application context type) generally takes a string or array of strings as the location paths of the resources, such as XML files that make up the definition of the context.When such a location path does not have a prefix, the specific Resource type built from that path and used to load the bean definitions depends on and is appropriate to the specific application context. For example, consider the following example, which creates a ClassPathXmlApplicationContext:

一个应用上下文构造器通常接收一个描述资源位置路径的字符串或字符串数组,例如构成应用上下文定义的XML文件。当这样的位置路径没有前缀时,从该路径构建并用于加载 bean 定义的特定资源类型取决于特定应用程序上下文。例如,参考以下示例,它创建了一个 ClassPathXmlApplicationContext:

ApplicationContext ctx = new ClassPathXmlApplicationContext("conf/appContext.xml");

The bean definitions are loaded from the classpath, because a ClassPathResource is used. However, consider the following example, which creates a FileSystemXmlApplicationContext:

bean 定义是从类路径加载的,因为使用了 ClassPathResource。但是,请考虑以下创建 FileSystemXmlApplicationContext 的示例:

ApplicationContext ctx =
    new FileSystemXmlApplicationContext("conf/appContext.xml");

Now the bean definitions are loaded from a filesystem location (in this case, relative to the current working directory).Note that the use of the special classpath prefix or a standard URL prefix on the location path overrides the default type of Resource created to load the bean definitions. Consider the following example:

现在 bean 定义从文件系统位置加载(在这种情况下,相对于当前工作目录)。需要注意的是,在位置路径上使用特殊的类路径前缀或标准 URL 前缀会覆盖为加载 bean 定义而创建的默认资源类型。考虑以下示例:

ApplicationContext ctx =
    new FileSystemXmlApplicationContext("classpath:conf/appContext.xml");
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值