Em Ae Em Ae - 4 months ago 19x
Java Question

Getting properties object in spring

I have a properties file called

. Right now, I am able to load individual property of this file in my class annotated with
which is working perfectly fine.

However, I am thinking of making my project more modular, for which I need to read the whole
file as one
object so that i can pass it along. How can I do so ?


Right now, I am loading individual property from the file like this

my applicationContext.xml has following entry

<context:property-placeholder location="classpath:xyz.properties" order="2" ignore-unresolvable="true"/>

and then i have the respective class as

public class XyzConfiguration {
private String clientId;

private String clientSecret;


What I mean by pass it along

Right now, for each individual property I have to create a respective field in a class and then annotate it with respective property name. By doing so, I am making my nested module very
framework specific. I might someday put this module on github for others as well and they may or may not use
framework. For them it would be easier to create an object of this module by passing required parameters (ideally in case of a
object) so that my module will fetch the properties by itself.


You can try below code.

import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.core.io.ResourceLoader;
import java.util.Properties;

private String fileLocator;
private Properties prop;
private ResourceLoader resourceLoader;

 public void init() throws IOException {
        //"fileLocator" must be set as a path of file.
        final Resource resource = resourceLoader.getResource(fileLocator);

        prop = PropertiesLoaderUtils.loadProperties(resource);

prop will have all values from your property file and then you can get any value by calling prop.getProperty() method.