Spring – ResourceLoaderAware with Example

Last Updated : 31 Oct, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Prerequisite: Introduction to Spring Framework

In this article, we will discuss the various ways through which we can load resources or files (e.g. text files, XML files, properties files, etc.) into the Spring application context. These resources or files may be present at different locations like in the file system, classpath, or URL. Spring provides the Resource and ResourceLoader interfaces. The Resource interface represents external resources and the ResourceLoader interface provides a unified method i.e. getResource() to retrieve an external resource represented by a resource object.

Java




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();
}
  
public interface InputStreamSource {
    InputStream getInputStream() throws IOException;
}


Java




public interface ResourceLoader {
    Resource getResource(String location);
}


As we discussed earlier, the Resource interface represents an external resource. As we know, we can’t create an object of the interface. Spring provides the following 6 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.
  • InputStreamResource: Represents an input stream resource.
  • ByteArrayResource: Represents a byte array resource.

There are a few ways through which we can read/load external files via. creation of Resource object.

1. Through the ApplicationContext Interface

Java




public interface ResourceLoader {
    Resource getResource(String location);
}


The ResourceLoader interface is meant to be implemented by objects that can return (i.e. load) Resource instances. In Spring, all application contexts implement the ResourceLoader interface. Therefore, all application contexts may be used to obtain Resource instances. Let’s see how we can load/read external resources/files by using application context :

Java




package com.gfg.technicalscripter;
  
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
  
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
  
public class App {
    public static void main(String[] args)
    {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext();
  
        // Through File system
        Resource fileResource = applicationContext.getResource("file:c:\\gfg-testing.txt");
  
        // Through URL path
        Resource urlResource = applicationContext.getResource("url:http:// www.gfg.com/gfg-testing.txt");
  
        // Through Classpath
        Resource classpathResource = applicationContext
                                         .getResource("classpath:com/gfg/technicalscripter/gfg-testing.txt");
  
        readFileThroughResource(classpathResource);
        // We can call readFileThroughResource for
        // any resource object representing a file
    }
  
    private static void readFileThroughResource(Resource resource)
    {
        try {
            InputStream is = resource.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
  
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            br.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Spring project structure & gfg-testing.txt file content:

Project Structure

 

Content of gfg-testing.txt file

 

Screenshot of output console:

 

2. Through the ResourceLoaderAware interface

Since spring bean does not have access to the spring application context, So how can a bean load/access resources or files (e.g. text files, XML files, properties files, etc.)? To solve this issue, the workaround is to implement the ResourceLoaderAware interface and create a setter method for the ResourceLoader object. At last, spring will inject the resource loader into your bean.

Java




package com.gfg.technicalscripter;
  
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 Resource getResource(String location)
    {
        return resourceLoader.getResource(location);
    }
}


XML




    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
  
    <bean id="customResourceLoader" class="com.gfg.technicalscripter.CustomResourceLoader" />
  
</beans>


Java




package com.gfg.technicalscripter;
  
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
  
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
  
public class App {
    public static void main(String[] args)
    {
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:com/gfg/technicalscripter/config.xml");
        CustomResourceLoader customResourceLoader = applicationContext.getBean(CustomResourceLoader.class);
        Resource classpathResource = customResourceLoader
                                         .getResource("classpath:com/gfg/technicalscripter/gfg-testing.txt");
  
        readFileThroughResource(classpathResource);
    }
  
    private static void readFileThroughResource(Resource resource)
    {
        try {
            InputStream is = resource.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
  
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
            br.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Screenshot of output console:

Output

 

When a class implements ResourceLoaderAware and is deployed into an application context (as a Spring-managed bean), it is recognized as ResourceLoaderAware by the application context. The application context will then invoke the setResourceLoader(ResourceLoader), supplying itself as the argument (remember, all application contexts in Spring implement the ResourceLoader interface). This getResource() method is very helpful to deal with different resources with different solutions, like File object for file system resource, and URL object for URL resource and it really saves a lot of time.



Previous Article
Next Article

Similar Reads

Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code &lt;?xml version=&quot;1.0&quot; encoding=
4 min read
Difference Between Spring DAO vs Spring ORM vs Spring JDBC
The Spring Framework is an application framework and inversion of control container for the Java platform. The framework's core features can be used by any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring-DAO Spring-DAO is not a spring module. It does not provide interfaces or templates
5 min read
Spring vs Spring Boot vs Spring MVC
Are you ready to dive into the exciting world of Java development? Whether you're a seasoned pro or just starting out, this article is your gateway to mastering the top frameworks and technologies in Java development. We'll explore the Spring framework, known for its versatility and lightweight nature, making it perfect for enterprise-level softwar
8 min read
Java Spring Boot Microservices - Develop API Gateway Using Spring Cloud Gateway
The API Gateway Pattern in some cases stands for “Backend for frontend”. It is basically the entry gate for taking entry into any application by an external source. The pattern is going on in a programmer’s mind while they are making the client’s application. It acts as a medium between the client applications and microservices. For example-Netflix
4 min read
Spring Boot | How to access database using Spring Data JPA
Spring Data JPA is a method to implement JPA repositories to add the data access layer in applications easily. CRUD stands for create, retrieve, update, delete which are the possible operations which can be performed in a database. In this article, we will see an example of how to access data from a database(MySQL for this article) in a spring boot
4 min read
Difference between Spring MVC and Spring Boot
1. Spring MVC : Spring is widely used for creating scalable applications. For web applications Spring provides Spring MVC framework which is a widely used module of spring which is used to create scalable web applications. Spring MVC framework enables the separation of modules namely Model View, Controller, and seamlessly handles the application in
3 min read
How to Create a Spring Boot Project in Spring Initializr and Run it in IntelliJ IDEA?
Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using Java is that it tries to connect every concept in the language to the real world with the help
3 min read
Spring - Add User Name and Password in Spring Security
Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications. Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is fou
3 min read
How to Create and Setup Spring Boot Project in Spring Tool Suite?
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
How to Run Your First Spring Boot Application in Spring Tool Suite?
Spring Tool Suite (STS) is a java IDE tailored for developing Spring-based enterprise applications. It is easier, faster, and more convenient. And most importantly it is based on Eclipse IDE. STS is free, open-source, and powered by VMware. Spring Tools 4 is the next generation of Spring tooling for the favorite coding environment. Largely rebuilt
3 min read
Spring - Add Roles in Spring Security
Spring Security is a powerful and highly customizable authentication and access-control framework. It is the de-facto standard for securing Spring-based applications. Spring Security is a framework that focuses on providing both authentication and authorization to Java applications. Like all Spring projects, the real power of Spring Security is fou
4 min read
Difference Between Spring Boot Starter Web and Spring Boot Starter Tomcat
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
Create and Run Your First Spring MVC Controller in Eclipse/Spring Tool Suite
Spring MVC framework enables separation of modules namely Model, View, and Controller, and seamlessly handles the application integration. This enables the developer to create complex applications also using plain java classes. The model object can be passed between view and controller using maps. In this article, we will see how to set up a Spring
5 min read
Spring - Using SQL Scripts with Spring JDBC + JPA + HSQLDB
We will be running the SQL scripts with Spring JDBC +JPA + HSQLDB. These scripts are used to perform SQL commands at the time of application start. Java Database Connectivity (JDBC) is an application programming interface (API) for the programming language Java, which defines how a client may access a database. JPA is just a specification that faci
3 min read
How to Make a Project Using Spring Boot, MySQL, Spring Data JPA, and Maven?
For the sample project, below mentioned tools got used Java 8Eclipse IDE for developmentHibernate ORM, Spring framework with Spring Data JPAMySQL database, MySQL Connector Java as JDBC driver.Example Project Using Spring Boot, MySQL, Spring Data JPA, and Maven Project Structure: As this is getting prepared as a maven project, all dependencies are s
4 min read
How to Generate a New Spring Cloud Project in Spring Initializr?
Spring Initializr is a Web-based tool that generates the Spring Boot project structure. The spelling mistake in initializr is inspired by initializr. Modern IDEs have integrated Spring Initializr which provides the initial project structure. It is very easy for developers to select the necessary configuration for their projects. The Spring Initiali
2 min read
Spring - Integration of Spring 4, Struts 2, and Hibernate
In modern Java web application development, integrating different frameworks is a common requirement to leverage the strengths of each framework. Spring, Struts, and Hibernate are three popular frameworks that can work together seamlessly to build robust and scalable applications. In this article, we will explore how to integrate Spring 4, Struts 2
4 min read
Java Spring Boot Microservices – Integration of Eureka and Spring Cloud Gateway
Microservices are small, loosely coupled distributed services. Microservices architecture evolved as a solution to the scalability, independently deployable, and innovation challenges with Monolithic Architecture. It provides us to take a big application and break it into efficiently manageable small components with some specified responsibilities.
5 min read
What's New in Spring 6 and Spring Boot 3?
Spring and Spring Boot are two of the most popular Java frameworks used by developers worldwide. The Spring team is continuously working on improving and enhancing the frameworks with each new major release. Spring 6 and Spring Boot 3 are expected to bring in significant new features and changes that will further boost development with these techno
5 min read
How to Integrate Keycloak with Spring Boot and Spring Security?
Keycloak is Open Source Identity and Access Management (IAM) solution developed by Red Hat. By using this you can add authentication to applications and secure services with minimum effort. No need to deal with storing users or authenticating users. Keycloak provides user federation, strong authentication, user management, fine-grained authorizatio
2 min read
How to Download and Install Spring Tool Suite (Spring Tools 4 for Eclipse) IDE?
Spring Tool Suite (STS) is a Java IDE tailored for developing Spring-based enterprise applications. It is easier, faster, and more convenient. And most importantly it is based on Eclipse IDE. STS is free, open-source, and powered by VMware. Spring Tools 4 is the next generation of Spring tooling for your favorite coding environment. Largely rebuilt
2 min read
Java Spring Boot Microservices - Integration of Eureka, Feign & Spring Cloud Load Balancer
Microservices are small, loosely coupled distributed services. Microservices architecture evolved as a solution to the scalability, independently deployable, and innovation challenges with Monolithic Architecture. It provides us to take a big application and break it into efficiently manageable small components with some specified responsibilities.
13 min read
Java Spring Boot Microservices - Client Side Load Balancing with Spring Cloud LoadBalancer
Spring Cloud is a collection of projects like load balancing, service discovery, circuit breakers, routing, micro-proxy, etc will be given by Spring Cloud. So spring Cloud basically provides some of the common tools and techniques and projects to quickly develop some common patterns of the microservices. Basically, there are two ways to load balanc
12 min read
Difference between Spring and Spring Boot
Spring Spring is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier compared to classic Java frameworks and Appl
4 min read
Difference Between Spring MVC and Spring WebFlux
Spring MVCSpring MVC Framework takes on the Model-View-Controller design pattern, which moves around the Dispatcher Servlet, also called the Front Controller. With the help of annotations like @Controller and @RequestMapping, the by-default handler becomes a robust(strong) tool with a diverse set of handling ways. This kind of dynamic kind of featu
5 min read
Spring Data JPA vs Spring JDBC Template
In this article, we will learn about the difference between Spring Data JPA vs Spring JDBC Template. Spring Data JPATo implement JPA-based repositories, Spring Data JPA, a piece of the Spring Data family, takes out the complexity. With the help of spring data JPA the process of creating Spring-powered applications that support data access technolog
5 min read
Spring AOP vs Spring IOC
Spring AOPAspect Oriented Programming i.e. AOP, is another way to program a structure, similar to Object-oriented Programming (OOP). Object-oriented Programming (OOP) completely depends upon classes as the main modular unit, whereas Aspect Oriented Programming (AOP) moves the main idea to aspects. Aspects are the essential element that allows probl
4 min read
Spring MVC vs Spring Web Flux: Top Differences
For creating Java-based projects and applications, developers usually have to choose between Spring MVC and Spring WebFlux when using the Spring framework to create web apps. To pick the best framework for their project, developers need to know how each one is different and what features they have. Each framework has its own benefits compared to th
11 min read
Spring Cloud Vs Spring Boot Actuator
Spring CloudSpring Cloud's main purpose is to give tools and services for managing and making distributed systems, especially in a microservices architecture. The developer wants to speed up the process of building patterns in distributed systems, these tools can fulfill their requirement. They include almost all from the management of configuratio
5 min read
Configuring Multiple Spring Batch Jobs in a Spring Boot Application
Spring Batch serves as a robust framework within the Spring ecosystem, specifically tailored for managing batch processing tasks efficiently. It's designed to tackle big data jobs efficiently and comes with handy tools to make batch application development a breeze. In the context of a Spring Boot application, setting up multiple Spring Batch jobs
10 min read