1

I need to ask for the best way how to read the configuration file for my application. Currently what I'm doing is put the above code in my Java program, get all configuration item that I want, and then pass the value to the function that requires the variable.

What is the best way for me to let the configuration file to load only once and can be used in the other process (other users)?

File configFile = new File("D:\\config.properties");

try {
    FileReader reader = new FileReader(configFile);
    Properties prop = new Properties();
    prop.load(reader);

    String dbName = prop.getProperty("dbName");
    String dBase = prop.getProperty("database");

    String strMethod1 = prop.getProperty("method1"); 
    int method1 = Integer.parseInt(strMethod1);

    String strMethod2 = prop.getProperty("method2"); 
    int method2 = Integer.parseInt(strMethod2);

} catch (IOException e) {
    returnValue = IO_EXCEPTION;
    logger.error("IOException:::" + e + "  returnValue:::" + returnValue);
}
Malt
  • 28,965
  • 9
  • 65
  • 105
inayzi
  • 459
  • 2
  • 6
  • 13

1 Answers1

1

I suggest creating your own class that wraps the Properties and is responsible for giving out individual configuration values. That class should also be responsible for reading the property file just once (or whenever it needs to be read).

Once you have such a class, you have two options. Either initiate once and have the other classes access it statically (perhaps as a singleton). Or don't use a static instance and pass it as a dependency to classes that need configuration.

Using a static reference is the simpler approach, but it can complicate testing since now all of your classes depend on that one class statically. Passing it as a dependency improves testability, but requires actually passing that class around or using some sort of Dependency Injection framework/library.

Finally, I suggest not working with Properties directly. There are some nice configuration libraries out there that can simplify many of the mundane aspects of handling configuration in a complex project. In other words, that wheel has already been invented, and re-invented a whole bunch of times.

I personally like using owner but there's also apache commons configuration, as well as other libraries.

Malt
  • 28,965
  • 9
  • 65
  • 105