Working With Resources in Spring

DZone 's Guide to

Working With Resources in Spring

Learn how to use the ResourceLoader in your Spring apps.

· Java Zone ·
Free Resource

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.
Interested in learning more about Resources in Spring? Check out this post on REST and defining Resources.

Picture of Resource Spring

ResourceLoader is a vital component in pulling external resources for Spring applications.

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 thegetResource() method to load a text file from the path provided.

Here is the content of the ResourceLoaderService.java file.


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;
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 the Spring application context, we get the ResourceLoaderService object and call the showResourceDataUsingFilePath() using this object.

Below is an example the 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;
public class ResourceloaderdemoApplication {
  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 {
    } catch (Exception e) {

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 the 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.


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.

Further Reading

Binding Properties From External Souces in Spring Boot Applications

REST: Defining a Resource

external, java, load, resourceloader, resources, spring, spring tutorial, tutorial

Published at DZone with permission of John Thompson , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}