Spring's resource interface and its implementation class

Source: Internet
Author: User

The classes provided by the JDK to access the resources (such as Java.net.URL, File, etc.) do not satisfy the access requirements of various underlying resources, such as the absence of an operational class that obtains resources from the CLASSPATH or the context of the Web container. In view of this, Spring has designed a resource interface, which provides the application with the ability to access the underlying resources more strongly. The interface has an implementation class that corresponds to a different resource type. Let's take a look at the main methods of the resource interface:

    • Boolean exists (): whether the resource exists;
    • Boolean IsOpen (): Whether the resource is open;
    • URL GetURL () throws IOException: If the underlying resource can be represented as a URL, the method returns the corresponding URL object;
    • File GetFile () throws IOException: if the underlying resource corresponds to a file, the method returns the corresponding files object;
    • InputStream getInputStream () throws IOException: returns the input stream corresponding to the resource.

Resource plays an integral role in the spring framework, and the spring framework uses Resource to load a variety of resources, including configuration file resources, internationalized attribute file resources, and so on. Let's take a look at the specific implementation class for resource, shown in 3-5:

    • Bytearrayresource: Binary array represents the resource, binary array resources can be constructed in memory through the program;
    • Classpathresource: A resource under a classpath that is represented as a path relative to a classpath, as shown in code listing 3-14;
    • Filesystemresource: File system resources, resources are represented by file system path, such as d:/conf/bean.xml, etc.;
    • Inputstreamresource: Returns the indicated resource as an input stream;
    • Servletcontextresource: A class designed to access resources in the context of a web container, responsible for loading resources in a path relative to the Web application's root directory, which supports streaming and URL access, and can be accessed in the case of a war unpacking, The class can also access resources directly from the jar package;
    • Urlresource:url encapsulates the Java.net.URL, which enables users to access any resource that can be represented by a Url, such as file system resources, HTTP resources, FTP resources, and so on. With this abstract resource class, we can place the spring configuration information anywhere (such as database, LDAP), as long as the configuration information can eventually be returned via the resource interface.

 Tip: Spring's resource interface and its implementation classes can be used without the spring framework, which is better and more powerful than the APIs that access resources through the JDK.

Suppose a file is located under the classpath of the Web app, and the user can access the file resource in the following ways:

    • Access via Filesystemresource in the absolute path of the file system;
    • Access by Classpathresource in a classpath manner;
    • Access is done through Servletcontextresource in a way that is relative to the Web application's root directory.

Spring's Resource implementation class provides a much more flexible way to operate than accessing file resources through the JDK files class, and users can choose the appropriate resource implementation class to access resources, depending on the situation. Below, we access the same file resource through Filesystemresource and Classpathresource, respectively:

Code Listing 3-14 Filesourceexample

 PackageCom.baobaotao.resource; Importjava.io.IOException; ImportJava.io.InputStream; ImportOrg.springframework.core.io.ClassPathResource; ImportOrg.springframework.core.io.FileSystemResource; ImportOrg.springframework.core.io.Resource;  Public classFilesourceexample { Public Static voidMain (string[] args) {Try{String FilePath= "D:/masterspring/chapter3/webroot/web-inf/classes/conf/file1.txt"; //① loading files using the System file path methodResource res1 =NewFilesystemresource (FilePath); //② loading files with classpath modeResource Res2 =NewClasspathresource ("Conf/file1.txt"); InputStream ins1=Res1.getinputstream (); InputStream Ins2=Res2.getinputstream (); System.out.println ("Res1:" +res1.getfilename ()); System.out.println ("Res2:" +res2.getfilename ()); } Catch(IOException e) {e.printstacktrace (); }}}

Once the resource is fetched, the user can access the file's data and other information through multiple methods defined by the resource interface: such as GetFileName () to get the file name, and GetFile () to obtain the resource corresponding file object, through the getInputStream () gets the input stream of the file directly. In addition, you can create a new file on a resource relative address by createrelative (Stringrelativepath).
In a web app, users can also access file resources through Servletcontextresource in a way that is relative to the Web app root, as follows:

Code Listing 3-15 resource.jsp

 <%@ page language= "java" contenttype= "text/html; charset=utf-8" pageencoding  = "Utf-8"%><jsp:directive.page import  = " Org.springframework.web.context.support.ServletContextResource "/><jsp:directive.page import  = "Org.springframework.core.io.Resource"/><jsp:directive.page Span style= "color: #0000ff;" >import  = "Org.springframework.web.util.WebUtils"/><%// ① Note that the file resource address represents the  Resource res3 =  + "<br/>"  %> 

For file resources located on remote servers (WEB servers or FTP servers), users can easily access them through Urlresource.
When the resource is loaded, the resource content is read by the system code, and if the resource file is in a special encoding format, the resource can be encoded by Encodedresource to ensure the correctness of the resource content operation:

 PackageCom.baobaotao.resource;ImportOrg.springframework.core.io.ClassPathResource;ImportOrg.springframework.core.io.Resource;ImportOrg.springframework.core.io.support.EncodedResource;Importorg.springframework.util.FileCopyUtils; Public classEncodedresourceexample { Public Static voidMain (string[] args)throwsThrowable {Resource res=NewClasspathresource ("Conf/file1.txt"); Encodedresource Encres=NewEncodedresource (res, "UTF-8"); String content=filecopyutils.copytostring (Encres.getreader ());    SYSTEM.OUT.PRINTLN (content); }}

Spring's resource interface and its implementation class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.