Jonny5
Jonny5

Reputation: 1499

Java properties: best practices?

Scenario: application has an algorithm where some optimizations can be enabled. By default some are on, some are off. Is there a convenient way of implementing some kind of global property system in Java?

Requirements:

Alternatives:

Which of these (or other) seems the best solution for this scenario?

Upvotes: 2

Views: 8740

Answers (1)

Pranalee
Pranalee

Reputation: 3409

  1. Keep properties in .prop files. I think this is better than command line arguments because
  1. it makes easy to look what all properties are being used.
  2. what is their current value,
  3. each deployment environment can have their own properties values(ex. qa, prod)
  4. you can logically group properties in different files.
  1. Create a class PropertyFactory. Have a private static final member propertiesMap. In this class in static block initalize propertiesMap with values from all properties file. You can use propertiesMap now from anywhere in code.
  2. To make it easy for end user, you can give one more option to user to specify property values in command line arguments. And in your static block, handle it. Override in map if user has provided value for some property.
  3. You can access it as

    PropertiesFactory.getPropertiesMap().get("key");

Update

  1. You want values to be changed runtime. But thats not possible with vm arguments/command line arguments/ system enviornments. These values are fixed once program execution starts. So this is not possible in stand alone java application.

If you want values to be update able , then propertiesMap needs to be mutable. You will need to run this program on server, where instance of propertiesMap is maintained and you can put method on this map when you want to override value of one of its key.

Upvotes: 3

Related Questions