Reputation: 4636
What's the correct way to access the Properties()
object after loading it with a .properties
file?
One way I've used in the past is to just store each Properties
object in a static variable in a utility class and access it through there. However I've been thinking that it might be better to actually create a wrapper class with some utility functions? Not sure if that would be helpful. Most examples I've found just concern themselves with how one loads a properties file but not what should happen after that.
Is there a generally approved way to do it and what are its pros and cons?
Upvotes: 0
Views: 123
Reputation: 2851
Just like Rob Conklin said, it's probably good to keep a level of abstraction in order to (in the future) be able to switch out the properties-file based storage.
However, you can set merge your properties with System.getProperty()
to get easy access from wherever in your program
FileInputStream propFile = new FileInputStream("myProperties.properties");
Properties p = new Properties(System.getProperties());
p.load(propFile);
// set the system properties
System.setProperties(p);
Whichever properties you set latest will override the others (if the names collides)
You can then later access the property simply with
System.getProperty("propName");
Upvotes: 1
Reputation: 9456
Do yourself a huge favor, and create a DAO around your properties file access. In most systems I've worked on, we always wished we had this abstraction, it allows properties files to become database driven at some future point.
You can cache it inside the DAO as a static variable, but that becomes hidden from the client.
Upvotes: 0