Spring Read Classpath Resource using @Value

Tags: Spring Framework Resource Value Annotation Classpath

In this Java Spring Framework tutorial, we learn how to use @Value annotation to read classpath resource files located in the resources folder in your Spring application project.

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 a method to read the data.json file and return it as a String object. In this service class we use @Value annotation to load the data.json file to the Resource object.

ResourceService.java

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

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

@Service
public class ResourceService {
	
	@Value("classpath:data.json")
	private Resource dataResource;
	
	public String readDataResourceAsString() throws IOException {
		InputStream inputStream = dataResource.getInputStream();
		byte[] fileData = FileCopyUtils.copyToByteArray(inputStream);
		String outputString = new String(fileData);
		return outputString;
	}

}

How to use ResourceService class

Firstly, declare the resourceService object.

@Autowired
private ResourceService resourceService;

And return data.json file from classpath as a String object.

String data = resourceService.readDataResourceAsString();

Happy Coding 😊