Spring Read Classpath Resource using ApplicationContext

Tags: Spring Framework Resource ApplicationContext ApplicationContextAware Classpath

In this Java Spring Framework tutorial, we learn how to read classpath resources in a Spring application using ApplicationContext class.

For example, we have a text file located at /src/main/resources/data.json in the Spring application project.

Next step, we implement a new class named ResourceService and implement two methods to read the data.json file as a Resource object and as a String object. In order to get the ApplicationContext object we implement the ApplicationContextAware interface and override setApplicationContext() method.

ResourceService.java

import java.io.IOException;
import java.io.InputStream;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

@Service
public class ResourceService implements ApplicationContextAware {

	private ApplicationContext applicationContext;
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		this.applicationContext = applicationContext; 
	}

	public Resource readDataResource() {
		Resource resource = applicationContext.getResource("classpath:data.json");
		return resource;
	}
	
	public String readDataResourceAsString() throws IOException {
		Resource resource = applicationContext.getResource("classpath:data.json");
		InputStream inputStream = resource.getInputStream();
		byte[] fileData = FileCopyUtils.copyToByteArray(inputStream);
		String outputString = new String(fileData);
		return outputString;
	}
}

How to use the ResourceService class

Firstly, declare the resourceService object.

@Autowired
private ResourceService resourceService;

How to read file in resources folder and return Resource object.

Resource resource = resourceService.readDataResource();

How to read the text file in classpath and return as a String object.

String data = resourceService.readDataResourceAsString();

Happy Coding 😊