I was exploring ways to do simple, plain-old file-based configuration in Java. I looked into Java's built-in Properties
and the Apache Common Configuration library. For the latter, the distilled code is as follows:
Configurations configs = new Configurations();
Configuration config = null;
try
{
config = configs.properties(new File("config.properties"));
}
catch (ConfigurationException cex)
{
}
long loadQPS = config.getInt("loadQPS");
The issue I have with this is that I find myself inserting this in every single class, which is suboptimal for at least two reasons: 1) I'm reading the file once for every class, when I should only read it once. 2) code duplication.
One obvious solution would be to create a Singleton configuration class that I then access from every other class. But surely this is a desired feature in almost every use case, so shouldn't it be included with the configuration library itself (am I missing something)? I also thought of using Spring configuration, which can create a Singleton configuration class for me, but isn't there too much overhead just for file-based configuration? (Spring's strength is in DI, as I understand.)
What's a good solution, or best practice (if there is one)?
EDIT: A simple static solution suggested in the answer:
public class ConfigClass {
static Configuration config;
static {
Configurations configs = new Configurations();
Logger sysLogger = LoggerFactory.getLogger("sysLogger");
try
{
config = configs.properties(new File("config.properties"));
}
catch (ConfigurationException cex)
{
sysLogger.error("Config file read error");
}
}
}
Access in the package by ConfigClass.config
.