Overlaps the tear mark jin word, life only love difficult to die.

An overview of the

This article looks at different implementations of resources or files (such as text files, XML files, properties files, or image files) loaded into the context of a Spring application. Spring ResourceLoader provides a unified getResource() method to retrieve external resources through the resource path.

Resources (Resource) interface

Resource is a generic interface in Spring for representing external resources.

Spring provides the following six implementations for the Resource interface.

  1. UrlResource
  2. ClassPathResource
  3. FileSystemResource
  4. ServletContextResource
  5. InputStreamResource
  6. ByteArrayResource

We can specify different prefixes to create paths to load resources from different locations

The prefix The sample instructions
classpath: classpath:com/myapp/config.xml Load from the classpath
file: file:///data/config.xml As from the file systemURLLoad.
http: https://myserver/logo.png fromURLloading
(none) /data/config.xml Depends on the underlyingApplicationContext

ResourceLoader

It is used to load resources (such as classpath or file system resources). It works in two ways:

//Expose the ClassLoader used by this ResourceLoader.
ClassLoader getClassLoader(a)
 
//Return a Resource handle for the specified resource location.
Resource getResource(String location)
Copy the code

The getResource () method determines the Resource implementation to be instantiated based on the Resource path. To get a reference to ResourceLoader, implement the ResourceLoaderAware interface.

Resource banner = resourceLoader.getResource("file:c:/temp/filesystemdata.txt");
Copy the code

useApplicationContextLoad resources

In Spring, all application contexts implement the ResourceLoader interface. Therefore, all application contexts are available to obtain resource instances.

To get a reference to ApplicationContext, implement the ApplicationContextAware interface.

Resource banner = ctx.getResource("file:c:/temp/filesystemdata.txt");
Copy the code

useResourceLoaderAwareLoad resources

To illustrate the various examples below, I’ve placed a file with the same name in a different location, and I’ll show you how to load each file.

CustomResourceLoader. Java write as follows, it will print the contents of the loaded resource file to the console.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
 
public class CustomResourceLoader implements ResourceLoaderAware
{
    private ResourceLoader resourceLoader;
 
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
 
    public void showResourceData(a) throws IOException
    {
        //This line will be changed for all versions of other examples
        Resource banner = resourceLoader.getResource("file:c:/temp/filesystemdata.txt");
 
        InputStream in = banner.getInputStream();
 
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
 
        while (true) {
            String line = reader.readLine();
            if (line == null)
                break; System.out.println(line); } reader.close(); }}Copy the code

The applicationContext.xml file entry for this file is as follows:

<bean id="customResourceLoader" class="cn.howtodoinjava.demo.CustomResourceLoader"></bean>
Copy the code

To test the CustomResourceLoader bean and call the showResourceData () method, the following code is used:

@SuppressWarnings("resource")
public static void main(String[] args) throws Exception
{
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
 
    CustomResourceLoader customResourceLoader = (CustomResourceLoader) context.getBean("customResourceLoader");
 
    customResourceLoader.showResourceData();
}
Copy the code

https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2019/10/25/16e007f0502c5381~tplv-t2oaga2asx-image.image

Since we are accessing resources through Spring’s resource loader, the custom resource loader must implement either the ApplicationContextAware interface or the ResourceLoaderAware interface.

Loading external resources

Load resources from the application root folder

To load files from the application folder, use the following template:

Resource banner = resourceLoader.getResource("file:data.txt");
Copy the code

Loads resources from the classpath

To load a file from the classpath, use the following template:

Resource banner = resourceLoader.getResource("classpath:classpathdata.txt");
Copy the code

Loads resources from the file system

To load files from a file system outside the application folder, use the following template:

Resource banner = resourceLoader.getResource("file:c:/temp/filesystemdata.txt");
Copy the code

fromURLLoad resources

To load a file from any URL, use the following template:

Resource banner = resourceLoader.getResource("//howtodoinjava.com/readme.txt");
Copy the code

All of the examples above will load resource files from their locations, and you can use them as needed.

How do I inject external files

In the example above, we hard-coded the resource name in CustomResourceLoader, which many people may not like and want to configure through a context file. External resource names can be configured using the following code template.

<bean id="customResourceLoader" class="com.howtodoinjava.demo.CustomResourceLoader">
 
    <property name="resource">
        <value>classpath:classpathdata.txt</value>
        <! -- or -->
        <value>file:data.txt</value>
    </property>
 
</bean>
Copy the code

CustomResourceLoader is as follows:

public class CustomResourceLoader {
 
    private Resource resource;
 
    public Resource getResource(a) {
        return resource;
    }
 
    public void setResource(Resource resource) {
        this.resource = resource; }}Copy the code

After the context is initialized, the resource is injected into the Resource property of the CustomResourceLoader. The same code can be used in the Spring Boot Resourceloader example.

Spring ResourceLoaderAware — Read file in Spring