Spring Read Properties File using ResourceUtils

In this Java Spring Framework tutorial, we learn how to use the ResourceUtils class of Spring Core module to read a properties file and convert it to Properties object in Spring application.

For example, we have the properties file located in \src\main\resources\application.properties

In the following PropertiesService class, we implement a method to read properties from classpath and convert it to Properties object.

PropertiesService.java

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

public class PropertiesService {
	
	private Logger logger = LoggerFactory.getLogger(PropertiesService.class);
	
	public Properties readApplicationProperties() {
		Properties properties = new Properties();
		
		try {
			File file = ResourceUtils.getFile("classpath:application.properties");
			InputStream inputStream = new FileInputStream(file);
			
			properties.load(inputStream);
		} catch (IOException e) {
			logger.error(e.getMessage(), e);
		}
		return properties;
	}

}

How to use the PropertiesService class.

PropertiesService propertiesService = new PropertiesService();
Properties properties = propertiesService.readApplicationProperties();

Happy Coding 😊