05.Spring Resource Loading-resource_srping

Source: Internet
Author: User
Tags assert define stream readable throw exception ftp protocol
Basic concepts

Spring calls all vectors that can record information, such as various types of files, binary streams, and so on, as resources.

The most common resource for spring developers is the spring configuration file (usually an XML-formatted file).

Spring provides a Resource interface for resource access, which is used to represent different types of resources. And the Spring framework itself uses the Resource interface heavily to access the underlying resources.

The Resource interface is an abstraction of a specific resource access policy and an interface implemented by all resource access classes. Internal construction

The Resource interface inherits the Inputstreamsource interface, through which any form of resources can be converted into a stream to operate.

Here's what it's Source: Inputstreamsource

Public interface Inputstreamsource {
    //means any form of resource can be converted into an input stream
    InputStream getInputStream () throws IOException;
}
Resoure
 public Interface Resource extends Inputstreamsource {//resource exists, true means Boolean exists ();

    Whether the resource is readable, true indicates the existence of a Boolean isreadable ();

    Whether the resource is turned on, true indicates that the resource can only be read once and then closed to avoid resource leaks Boolean isOpen ();

    If the current resource can be represented by Java.util.URL, the URL is returned or the exception URL GetURL () throws IOException;

    If the current resource can be represented by Java.util.URI, the URI is returned or the exception Uri GetURI () throws IOException;

    If the current resource can be represented by Java.io.File, the file is returned, otherwise the exception file GetFile () throws IOException is thrown;

    The length of the resource is generally the length of the file resource represented by the value long ContentLength () throws IOException;

    The last modification time of the resource was long lastmodified () throws IOException; Create a resource that is represented by the current resource//such as the current resource represents the file resource [d:/test/] then [Createrelative ("Test.txt")] will return the file resource [D:/test/test.txt] Resource C

    Reaterelative (String relativepath) throws IOException;

    The file path of the resource, such as the file resource, returns its path, and the URL resource returns an empty String GetFileName ();
    A resource's descriptor, which is usually the full path of the resource (the actual file name or the actual URL address).
String getdescription (); }

The Resource interface is an abstraction of the Spring resource access policy, which does not itself provide any resource access implementation, and the specific resource access is accomplished by the implementation class of the interface--each implementation class represents a resource access policy.

There is a large number of Resource implementation classes in Spring that represent different forms of resources. As shown in the following figure: Inheritance relationships

Common Types of resources

Resource type

The Resource implementation class provides the appropriate resource access logic for different underlying resources and provides convenient packaging to facilitate resource access by client programs. This is actually a typical policy pattern. Here are a few common resource types and the corresponding access methods. 1.ByteArrayResource

The implementation class that accesses the byte array resource. It maintains a byte array inside it, and the resource, once created, indicates that it must exist, so the Exists method returns true by default. We can access it by converting the byte array into Bytearrayinputstream. The specific source code is as follows:

public class Bytearrayresource extends Abstractresource {
    //byte array
    private final byte[] ByteArray;

    Description, can be customized by the developer, the default value is
    private final String description when empty;

    Constructor public
    Bytearrayresource (byte[] bytearray) {This
        (ByteArray, "Resource loaded from byte array");
    }

    //Constructor public
    Bytearrayresource (byte[] bytearray, String description) {
        if (ByteArray = null) {
            //Throw Out of Exception
        }
        This.bytearray = ByteArray;
        this.description = (description!= null? Description: "");
    }

    Key-> convert the array to bytearrayinputstream public 
    InputStream getInputStream () throws IOException {return
        new byt Earrayinputstream (This.bytearray);
    }

    The key-> returns true by default, indicating that public
    Boolean exists () {Returns True if the resource is created as a default
        ;

    Omit part of the source code ...
}

Then see how to use Bytearrayresource to access byte arrays:

Define stream Read method public
static void Readresource (Resource Resource) throws ioexception{
    InputStream is  = Resource.getinputstream ();
    byte[] buf = new byte[1024];
    int Len =0;
    while ((Len=is.read (BUF))!=-1) {
        System.out.println (new String (Buf,0,len));
    }


public static void Main (String [] args) throws IOException {
    Resource resouce = new Bytearrayresource ("Hello". Getbyt ES ());
    Readresource (resouce);
}
2.InputStreamResource

The implementation class that accesses the input stream resource. maintains an input stream within it, so we can get the input stream directly and access it. It is noteworthy that the input stream allows only one read (corresponding to its IsOpen method), and throws an exception if read again.

public class Inputstreamresource extends Abstractresource {//character input stream private final InputStream InputStream;

    Description private final String description;

    Indicates whether the private Boolean read = False is readable;
    Public Inputstreamresource (InputStream inputstream) {This (InputStream, "Resource Loaded through InputStream");
            Public Inputstreamresource (InputStream inputstream, String description) {if (InputStream = null) {
        Throw exception ...}
        This.inputstream = InputStream;
    this.description = (description!= null? Description: ""); }//Key--> direct access to the input stream (itself is the stream, no more conversion) public InputStream getInputStream () throws IOException, IllegalStateException

        {//means read only once, corresponding IsOpen if (this.read) {//Throw exception ...}
        This.read = true;
    return this.inputstream;
    }//is ture to read only once public boolean IsOpen () {return true; }//Key-> default return ture PubLic Boolean exists () {return true; }

}

Then see how to access the character input stream using Inputstreamresource:

The BIS represents the input stream
Bytearrayinputstream bis = new Bytearrayinputstream ("Hello". GetBytes ());
Inputstreamresource resource = new Inputstreamresource (bis);
Readbytearrayresource (Resource);

Key-> again reads the resource, throws an exception
Readresource (Resource);
3.FileSystemResource

Access to the implementation classes of resources in the file system. This class accesses a resource that is Java.io.File, a file object. It finds the specified file through the path of file. And it can be turned into FileInputStream to operate.

The IsOpen method inherits from the parent class Abstractresource and returns False, indicating that the resource can be read multiple times.

public class Filesystemresource extends Abstractresource implements Writableresource {//File private final file fi

    Le

    File path private final String path;
        Public filesystemresource (file file) {assert.notnull (file, ' file must not being null ');
        This.file = file;
    This.path = Stringutils.cleanpath (File.getpath ());
        Public Filesystemresource (String path) {assert.notnull (path, ' path must not to null ');
        This.file = new file (path);
    This.path = Stringutils.cleanpath (path);
    }//Key-> According to file, if the specified path does not save the file, returns false public Boolean exists () {return this.file.exists (); }//Is readable public boolean isreadable () {return (This.file.canRead () &&!this.file.isdirectory ())
    ; }//Key-> get FileInputStream public InputStream getInputStream () throws IOException {return new File
    InputStream (This.file);
    }//Key-> Create a resource that is relative to the current resource path. Suppose the current FThe Ile path is D:/demo/hello. TXT, and relativepath = good. TXT//The resource path created by this method is D:/demo/good. TXT Public Resource createrelative (string relativepath) {string pathtouse = stringutils.applyrelativepath (th
        Is.path, RelativePath);
    return new Filesystemresource (Pathtouse);
 }
}

Then see how to use Filesystemresource to access file objects:

Resource Resource = new  Filesystemresource ("D:/demo/hello.txt");

The critical-> represents the reading of files under the D:/demo/hello/good.txt path
Resource resource2 =  resource.createrelative ("Hello/good.txt") ;
Readresource (Resource);
Readresource (RESOURCE2);
4.ClassPathResource

The main advantage of accessing the resources under the class loading path is to facilitate access to the resources in the class loading path, especially for WEB applications, where the Classpathresource can automatically search for resource files located under Web-inf/classes, as opposed to other Resource implementation classes. There is no need to use absolute path access.

public class Classpathresource extends Abstractfileresolvingresource {//path private final String path;

    Class loader private ClassLoader ClassLoader;

    Class object Private class<?> clazz; Critical-> Use the default ClassLoader to load the path classpath resource public Classpathresource (path, (ClassLoader) nu
    ll);
        }//Critical-> Load path classpath resource public classpathresource using specified ClassLoader (String path, ClassLoader ClassLoader) {
        Assert.notnull (Path, "path must not being null");
        String pathtouse = stringutils.cleanpath (path);
        if (Pathtouse.startswith ("/")) {pathtouse = pathtouse.substring (1);
        } This.path = Pathtouse;
    This.classloader = (ClassLoader!= null? ClassLoader:ClassUtils.getDefaultClassLoader ()); }//Key-> the specified class loads the resource and loads the resource public classpathresource (String path, class<?> clazz) that is relative to the path of the current class {ass
        Ert.notnull (Path, "path must not being null"); This.path = StrIngutils.cleanpath (path);
    This.clazz = Clazz; } protected Classpathresource (String path, ClassLoader ClassLoader, class<?> clazz) {This.path = Strin
        Gutils.cleanpath (path);
        This.classloader = ClassLoader;
    This.clazz = Clazz; }//Get class Loader public final ClassLoader getClassLoader () {return (This.clazz!= null? this.clazz.getClass
    Loader (): This.classloader);
    }//Resource presence public Boolean exists () {return (ResolveUrl ()!= null); Protected URL ResolveUrl () {if (This.clazz!= null) {return This.clazz.getResource (This.path)
        ;
        else if (This.classloader!= null) {return this.classLoader.getResource (This.path);
        else {return Classloader.getsystemresource (This.path);
        } public InputStream getInputStream () throws IOException {InputStream is; if (This.clazz!= null) {is = This.clazz.geTresourceasstream (This.path);
        else if (This.classloader!= null) {is = This.classLoader.getResourceAsStream (This.path);
        else {is = Classloader.getsystemresourceasstream (This.path); } if (is = = null) {throw new FileNotFoundException (getdescription () + "cannot be opened because it D
        OES not exist ");
    return is; Resource createrelative (String relativepath) {string pathtouse = Stringutils.applyrelativepath (This
        . path, RelativePath);
    return new Classpathresource (Pathtouse, This.classloader, This.clazz); }
}

Then see how to use Classpathresource to access resources under the class load path:

public static void Main (String [] args) throws IOException {
    test test = new test;
    Test.readresource ();
}

Public  void Readresource () throws ioexception{
    //Assuming the path of the class is com\demo\, the path to the resource is Com\demo\com\demo\hello.txt
    Resource Resource = new Classpathresource ("Com\\demo\\hello.txt", This.getclass ());

    InputStream is  = Resource.getinputstream ();
    byte[] buf = new byte[1024];
    int Len =0;
    while ((Len=is.read (BUF))!=-1) {
        System.out.println (new String (Buf,0,len));
    Is.close ();
}
5.UrlResource

This resource represents a URL resource that simplifies URL resource access and can be read multiple times.

The following resource accesses are generally supported:

http: Access to Web resources via the standard HTTP protocol, such as New Urlresource ("http://address");

FTP: Access to resources via the FTP protocol, such as New Urlresource ("ftp://address");

File: Access to local file system resources via the file protocol, such as New Urlresource ("File:d:/test.txt"); 6.ServletContextResource

This resource represents a Web application resource that simplifies the getresource and getresourceasstream operations of the ServletContext interface of the Servlet container. Reference

Http://www.blogjava.net/DLevin/archive/2012/12/01/392325.html

http://jinnianshilongnian.iteye.com/blog/1416320

https://www.ibm.com/developerworks/cn/java/j-lo-spring-resource/

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.