Spring ResourceLoaderAware – Read file in Spring

Learn different ways to load resources or files (e.g. text files, XML files, properties file, or image files) into the Spring application context. Spring ResourceLoader provides a unified getResource() method for us to retrieve an external resource by a resource path.

1. Resource interface represents a resource

Resource is a general interface in Spring for representing an external resource.

Spring provides following 6 implementations for the Resource interface.

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

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

PrefixExampleExplanation
classpath:classpath:com/myapp/config.xmlLoaded from the classpath.
file:file:///data/config.xmlLoaded as a URL from the filesystem.
http:https://myserver/logo.pngLoaded as a URL.
(none)/data/config.xmlDepends on the underlying ApplicationContext.

2. ResourceLoader

It is used for loading resources (e.g. class path or file system resources). It has two methods:

//Expose the ClassLoader used by this ResourceLoader.
ClassLoader getClassLoader()

//Return a Resource handle for the specified resource location.
Resource getResource(String location)

The getResource() method will decide which Resource implementation to instantiate according to the resource path.

To get the reference of ResourceLoader, implement the ResourceLoaderAware interface.

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

3. Loading resource with ApplicationContext

In Spring, all application contexts implement the ResourceLoader interface. Therefore, all application contexts may be used to obtain Resource instances.

To get the reference of ApplicationContext, implement the ApplicationContextAware interface.

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

4. Loading resource with ResourceLoaderAware

To demonstrate the various examples below, I have placed a file with matching name in different locations and I will show to load each one of them.

CustomResourceLoader.java is written as below which print the content of loaded resource file into 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() 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();
	}
}

And applicationContext.xml file entry for this file is as below:

<bean id="customResourceLoader" class="com.howtodoinjava.demo.CustomResourceLoader"></bean>

To test the CustomResourceLoader bean and call the showResourceData() method, below code has been 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();
}

spring-load-external-resource-example

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

5. Load external resources

5.1. Load resource from application root folder

To load file from application folder, use below template:

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

5.2. Load resource from class path

To load file from classpath, use below template:

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

5.3. Load resource from filesystem

To load file from filesystem outside the application folder, use below template:

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

5.4. Load resource from URL

To load file from any URL, use below template:

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

All above examples will load the resource file from their location and you can use them the way you want.

6. How to inject external files

In above example, we have hard coded the resource name in CustomResourceLoader which many of you may not like and want to make it configurable through context file. Use below code template to make external resource name configurable.

<bean id="customResourceLoader" class="com.howtodoinjava.demo.CustomResourceLoader">

	<property name="resource">
		<value>classpath:classpathdata.txt</value>
		<!-- or -->
		<value>file:data.txt</value> 
	</property>

</bean>

And CustomResourceLoader will be like below:

public class CustomResourceLoader {

	private Resource resource;

	public Resource getResource() {
		return resource;
	}

	public void setResource(Resource resource) {
		this.resource = resource;
	}
}

Upon context initialization, resource will be injected into ‘resource‘ property of CustomResourceLoader. The same code can be used in spring boot resourceloader example.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

1 thought on “Spring ResourceLoaderAware – Read file in Spring”

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.