I have several classes that need to load some properties files, and I was wondering what are the best practices to accomplish this. I thought of two basic approaches:
Hardcode the properties file name in each class, and then use the
Properties
class to load from aFileInputStream
, which can be problematic if someone decides to change the name of the properties file, as it is hardcoded in the code.public class A { public A() { Properties p = new Properties().load( new FileInputStream("properties/Aconfig.properties")); String value = p.getProperty("key", ""); } }
Create a method that, given a class name, loads a properties file that has the same name as the class. Though this approach doesn't require to hardcode the properties file name, it does require that we follow some convention in naming the files, which can cause confusion.
public class A { public A() { Properties p = PropertiesHelper.loadFromClassName(A.class.getName()); // here, we **assume** that there is a A.properties file in the classpath. } }
However, there may be many other more elegant approaches, and that's why I posed these questions: i) What are the best practices for loading properties files in Java?; ii) Do you use any helper class that takes care of the job?; iii) Where (in the code) do you typically load the properties file?
Also, is it OK for a class to "auto-load" its properties? Or should I pass the arguments that I need to the constructor ? The problem of passing the arguments, is that there are way too many for some classes (~20, which represent parameters in a statistical model).