Reputation: 8724
I have a properties file called xyz.properties
. Right now, I am able to load individual property of this file in my class annotated with @Component
which is working perfectly fine.
However, I am thinking of making my project more modular, for which I need to read the whole xyz.properties
file as one properties
object so that i can pass it along. How can I do so ?
Update
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
@Component
public class XyzConfiguration {
@Value("${client.id}")
private String clientId;
@Value("${client.secret}")
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 spring
framework specific. I might someday put this module on github for others as well and they may or may not use spring
framework. For them it would be easier to create an object of this module by passing required parameters (ideally in case of a Properties
object) so that my module will fetch the properties by itself.
Upvotes: 0
Views: 539
Reputation: 26
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.
Upvotes: 1