Spring in Resource (resource) is acquired

1. Obtain resources through the Resource interface

Resource interface implementation class are:

 Resource interface extends InputStreamSource the interface, InputStreamSource the interface has a method: getInputStream()so Taken together, Resource interface there are the following methods:

public  class ResourceTest { 

    / ** ClassPathResource to acquire resources * * / 
    @Test 
    public  void TestClassPath () throws IOException { 
        the Resource Resource = new new ClassPathResource ( "test.txt" ); 

        // determine whether the file exists: 
        IF (resource.exists ( )) { 
            System.out.println ( "file exists" ); 
        } 

        // determines whether the resource file is readable 
        iF (resource.isReadable ()) {   
            System.out.println ( "read file" ); 
        } 

        // Analyzing current resource underlying resources representative has been started 
        if(resource.isOpen ()) { 
            System.out.println ( "resource file is already open" ); 
        } 

        System.out.println (resource.getURL ()); // access to resources where the URL of 
        System.out.println (Resource .getURI ()); // access to resources where the URI of the 
        resource.getFile (); // returns the current resource corresponding File. 
        System.out.println (resource.contentLength ()); // output content length 
        System.out.println (resource.lastModified ()); // last modified Resource returns the current representative of the underlying resource. 
        resource.createRelative ( "MyFile"); // create a new resource based on the relative path to the resource. [Default does not support the creation of a relative path resources] 
        System.out.println (resource.getFilename ()); // get the resource file name
        System.out.println (resource.getDescription ()); 


        // get the current resource represents an input stream 
        IF (resource.isReadable ()) { 
            the InputStream IS = resource.getInputStream ();   
            System.out.println (IS); 
            IS .close (); 
        } 

    } 

    / ** using FileSystemResource access to resources * * / 
    @Test 
    public  void TestFileSystem () throws IOException { 
        the resource resource = new new FileSystemResource ( "D: \\ test.txt" ); 
        System.out.println ( resource.getFilename ()); 
    } 

    / ** using UrlResource access to resources **/
    @Test
    public void TestUrl() throws MalformedURLException{
        Resource resource = new UrlResource("http://docs.spring.io/spring/docs/4.0.0.M1/spring-framework-reference/pdf/spring-framework-reference.pdf");
        System.out.println(resource.getFilename());
    }

    /**使用ByteArrayResource获取字节数组封装的资源**/
    @Test
    public void testByteArray() throws IOException {
        ByteArrayResource resource = new ByteArrayResource("Hello".getBytes()); 
        System.out.println (resource.getInputStream ());

    } 


    / ** using InputStreamResource input stream encapsulation access to resources. Resource for the input stream, which getInputStream () method can only be called once. * * /   
       @Test   
       public  void testInputStream () throws Exception {   
          the InputStream IS = new new the FileInputStream ( "D \\ test.txt" );   
          InputStreamResource Resource = new new InputStreamResource (IS);  
           // for InputStreamResource, its the getInputStream () method can only be called once, we continue to call throws an exception.  
          IS2 = resource.getInputStream InputStream ();    // return InputStream is that when a member 
          System.out.println (IS2); 
          is.close ();
       } 
}

2. Obtain resources through the interface ResourceLoader

Spring framework in order to more easily access resources to try to weaken the perception of each Resource programmer interface implementation class, defines another ResourceLoaderinterface. The interface getResource(String location)method can be used to access resources. It DefaultResourceLoader implementation class can be applied to all environments, you can return ClassPathResource, UrlResource and so on.

ResourceLoader making a prefix is ​​required to specify when loading resources need to be loaded: "classpath: path" represents a return to ClasspathResource, "http: // path" and "file: path" represents a return UrlResource resources, if not the prefix is ​​required based on the current context to decide, DefaultResourceLoader default implementation is to load the classpath resources. 

       @Test  
       public void testResourceLoader() { 

              ResourceLoader loader = new DefaultResourceLoader();  
              Resource resource = loader.getResource("http://www.baidu.com");  
              System.out.println(resource instanceof UrlResource); //true  
              resource = loader.getResource("classpath:test.txt");  
              System.out.println(resource instanceof ClassPathResource); //true  
              resource = loader.getResource("test.txt");  
              System.out.println(resource instanceof ClassPathResource); //true  

       } 

3. access to resources through ApplicationContext

All ApplicationContext instances have achieved ResourceLoader interface, so we use the Spring container, you can not be too care about the underlying implementation of Resource, do not need to create Resource implementation classes, but direct use applicationContext.getResource (), get into the bean container resource itself, and then take to the relevant resource information.

public class MyResource implements ApplicationContextAware {
        private ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public void resource() throws IOException {
        Resource resource = applicationContext.getResource("file:D:\\test.txt");
        System.out.println(resource.getFilename());
        System.out.println(resource.contentLength());

    }

}

Xml configuration file:

<bean id="myResource" class="com.spring.test.MyResource"></bean>

Test categories:

public class App {
    public static void main(String[] args) {
        @SuppressWarnings("resource")
        ApplicationContext context = new ClassPathXmlApplicationContext("classpath:spring-resource.xml");  
        MyResource myResource = (MyResource) context.getBean("myResource");
        try {
            myResource.resource();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Guess you like

Origin www.cnblogs.com/deityjian/p/11487644.html