开发者

Filtered properties in java

I have a java program that uses a handful of .properties files. It chooses what properties file to use based on a parameter (mode) passed at runtime. for example when the program is running in mode:a it uses a.prope开发者_如何学Pythonrties file and when mode:b it'll uses b.properties file, etc. I want to combine all these properties files into one common.properties and instead have different namespaces. For example in common.properties I'll have:

a.url = aaa
a.ip = aaa.aaa.aaa.aaa
b.url = bbb
b.ip = bbb.bbb.bbb.bbb

Right now, I instantiate the properties object in the main method and pass it to the other objects/methods that need to read something from the properties.But now that I've combined the properties I have to pass the mode: a or b as well so that they know what set of properties they should extract. Is there a better way of creating a filtered instance of the properties file in the main method and then passing that to other object in a way that these objects are not aware of the mode: a or b, and just query the properties object for url and ip (not a.url or a.ip)


Don't pass the Properties object to other methods/objects. It's too low-level, especially now that you have to deal with this namespace thing. Encapsulate the Properties inside a dedicated object (let's call it "Configuration"), and pass this Configuration object.

public class Configuration {
    private String mode;
    private Properties properties;

    public Configuration(String mode, Properties properties) {
        this.mode = mode;
        this.properties = properties;
    }

    public String get(String key) {
        return properties.getString(mode + "." + key);
    }
}

You could even extract the contract of this Configuration object into an interface, and make all objects depend on this interface rather than the concrete Configuration class, which would help in

  • changing the configuration strategy later if you want to (if you has done this from the start, you wouldn't have to change anything in all the objects now)
  • mocking the configuration in unit tests to make it return what you want.


You can extend the Properties class, add a getter and setter for the active namespace, and override the get() method to prepend the active namespace and call the super.get() method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜