Working with Resources in Spring

Working with Resources in Spring

0 Comments

In this post, I’ll explain how to work with resources in Spring using ResourceLoader.

  • We’ll begin with a brief introduction about resources.
  • Next, we’ll look at the Resource interface and some of its important methods.
  • Finally, we’ll go through its implementations.

Introduction: Working With Resources In Spring via ResourceLoader

Frequently, we need to read external resources into our Spring application.

Examples of external resources are text files, XML files, properties files, and image files.

These resources may be present at different locations. For example, in the file system, classpath, or URL.

Usually, we have to use different APIs for loading resources from different locations.

To handle such tasks, Spring provides the Resource and ResourceLoader interfaces. The Resource interface represents external resources. The ResourceLoader interface provides methods to load resources.

Spring Resource Interface

Resource is an interface in Spring to represent an external resource. Spring provides several implementations for the Resource interface.

The getResource() method of ResourceLoader decides the Resource implementation to use. This is determined by the resource path.

The code of the Resource interface is this.

public interface Resource extends InputStreamSource {

    boolean exists();

    boolean isOpen();

    URL getURL() throws IOException;

    File getFile() throws IOException;

    Resource createRelative(String relativePath) throws IOException;

    String getFilename();

    String getDescription();
}

As you can see, the Resource interface extends the InputStreamSource interface. Some of the important methods of the Resource interface are:

  • getInputStream(): Locates and opens the resource. It returns an InputStream for reading from the resource.
  • exists(): Returns a boolean indicating whether this resource actually exists in physical form.
  • isOpen(): Returns a boolean indicating whether this resource represents a handle with an open stream. If true, the InputStream must be read once only and then closed to avoid resource leaks. It will typically be false for resource implementations, with the exception of InputStreamResource.
  • getDescription(): Returns a description for this resource. The description can be used for error output when working with the resource. The description is often the fully qualified file name or the actual URL of the resource.

Spring’s Implementations for Resource Interface

Spring provides several implementations for the Resource interface:

  • URLResource: Represents a resource loaded from a URL.
  • ClassPathResource: Represents a resource loaded from the classpath.
  • FileSystemResource: Represents a resource loaded from the filesystem.
  • ServletContextResource: This implementation is for ServletContext resources. This interprets relative paths within the relevant web application’s root directory.
  • InputStreamResource: Represents an input stream resource.
  • ByteArrayResource: Represents a byte array resource.

Let’s start coding for loading a resource using ResourceLoader.

Using Spring’s ResourceLoader To Get A Resource

First, let’s define the class ResourceLoaderService.

It has the showResourceDataUsingFilePath() method which contains getResource() method to load a text file from the path provided.

Here is the content of the ResourceLoaderService.java file.

ResourceLoaderService.java

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;
import org.springframework.stereotype.Component;

@Component("resourceLoaderService")
public class ResourceLoaderService implements ResourceLoaderAware{
  private ResourceLoader resourceLoader;
  public void setResourceLoader(ResourceLoader resourceLoader) {
    this.resourceLoader = resourceLoader; 
  }
  public void showResourceDataUsingFilePath() throws IOException {
    Resource resource = resourceLoader.getResource("file:d:/test.txt");
    InputStream in = resource.getInputStream();
    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
    while (true) {
      String line = reader.readLine();
      if (line == null)
        break; System.out.println(line);
    } reader.close();
  }
}

Next, let’s write the main method.

With the help of Spring application context, we get the ResourceLoaderService object and call the showResourceDataUsingFilePath() using this object.

Below is an example which prints the content of loaded resources on the console.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import guru.springframework.resourceloaderdemo.service.ResourceLoaderService;

@SpringBootApplication
public class ResourceloaderdemoApplication {

  @SuppressWarnings("resource")
  public static void main(String[] args) {
    SpringApplication.run(ResoruceloaderdemoApplication.class, args);

    ApplicationContext ctx = new AnnotationConfigApplicationContext("guru.springframework.resourceloaderdemo.service");
    ResourceLoaderService loader = (ResourceLoaderService) ctx.getBean("resourceLoaderService");
    System.out.println("** Resource loader using file path **");

    try {
      loader.showResourceDataUsingFilePath();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

How To Load External Resources

We can specify different prefixes for creating a path to load resources from different locations.

  • To load a resource from a file system, we use the file prefix.
  • Similarly, to load a resource from the classpath, we use the classpath prefix.
  • We may also specify a URL as a resource path.

Below are the ways to load external resources:
Load resource from the application root folder
To load a file from the application folder, use this.
Resource resource = resourceLoader.getResource("file:data.txt");

Load resource from classpath
To load a file from the classpath, use this.
Resource resource = resourceLoader.getResource("classpath:data.txt");

Load resource from the filesystem
To load a file from filesystem outside the application folder, use the below template:
Resource resource = resourceLoader.getResource("file:c:/temp/filesystemdata.txt");

Load resource from URL
Similarly, to load a file from any URL, use below template:
Resource resource = resourceLoader.getResource("https://testsite.com/data.txt");

In conclusion, all the above examples will load the resource file from their location. You can choose the implementation that fits your requirements.

Summary

In this post, we’ve seen a few ways to access and read a resource using Spring. We looked at example implementations for loading resources present at

  • The classpath
  • The filesystem
  • Directly from any URL
  • Main application directory

You can download the complete source code of this post from GitHub.

About SFG Contributor

Staff writer account for Spring Framework Guru

    You May Also Like

    Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.