DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Spring Beans With Auto-Generated Implementations: How-To
  • The ABCs of Unity's Coroutines: From Basics to Implementation
  • React, Angular, and Vue.js: What’s the Technical Difference?
  • In-Depth Guide to Using useMemo() Hook in React

Trending

  • S3 Vectors: How to Build a RAG Without a Vector Database
  • Key Takeaways From Integrating a RAG Application With LangSmith
  • Evaluating SOC Effectiveness Using Detection Coverage and Response Metrics
  • Retesting Best Practices for Agile Teams: A Quick Guide to Bug Fix Verification
  1. DZone
  2. Coding
  3. Frameworks
  4. Working With Resources in Spring

Working With Resources in Spring

Learn how to use the ResourceLoader in your Spring apps.

By 
John Thompson user avatar
John Thompson
·
Aug. 29, 19 · Tutorial
Likes (14)
Comment
Save
Tweet
Share
122.7K Views

Join the DZone community and get the full member experience.

Join For Free

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.

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.

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 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;
@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 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.

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.

Spring Framework Application directory Web application Interface (computing) Implementation

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

Opinions expressed by DZone contributors are their own.

Related

  • Spring Beans With Auto-Generated Implementations: How-To
  • The ABCs of Unity's Coroutines: From Basics to Implementation
  • React, Angular, and Vue.js: What’s the Technical Difference?
  • In-Depth Guide to Using useMemo() Hook in React

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook