开发者

java Properties - to expose or not to expose?

This might be an age old problem and I am sure everyone has their own ways. Suppose I have some properties defined such as

secret.user.id=user
secret.password=password
website.url=http://stackoverflow.com

Suppose I have 100 different classes and places where I need to use these properties. Which one is good (1) I create a Util class that will load all properties and serve them using a key constant Such as : Util is a singleton that loads all properties and keeps up on getInstance() call.

Util myUtil = Util.getInstance();
String user = myUtil.getConfigByKey(Constants.SECRET_USER_ID);
String password = myUtil.getConfigByKey(Constants.SECRET_PASSWORD);
..
//getConfigByKey() - inturns invokes properties.get(..)
doSomething(user, password)

So wherever I need these properties, I can do steps above.

(2) I create a meaningful Class to r开发者_JAVA百科epresent these properties; say, ApplicationConfig and provide getters to get specific properties. So above code may look like:

ApplicationConfig config = ApplicationConfig.getInstance();
doSomething(config.getSecretUserId(), config.getPassword());
//ApplicationConfig would have instance variables that are initialized during
// getInstance() after loading from properties file.

Note: The properties file as such will have only minor changes in the future.

My personal choice is (2) - let me hear some comments?


Do it the most straightforward way (a class with static values):

package com.domain.packagename

public class Properties {
    private static String hostName;
    public static getHostName() { return hostName; }
    private static int port;
    public static int getPort() { return port; }

    public static void load() {
        //do IO stuff, probably
        hostName = ??;
        port = ??;
        //etc
    }
}


I find the first approach to be more verbose than necessary. (Especially if the properties are not expected to change very much.) Also, by using the second approach you can handle casting/type issues when the properties are loaded instead of when they are used.


Your option (2) to keep application specific getters sounds better and clean. public static final keys from an interface had been a bad design in Java for ages.


I guess my first question is why you want to create an instance of something you're saying is a singleton (you mentioned using code like Util.getInstance()). A singleton only has 1 instance so you shouldn't try to instantiate multiple copies in your code.

If the data is static (like this appears to be) I'd create a singleton and retrieve the values from it.


I don't think there is any significant advantage of one method over the other and I don't think the solution (1) is more secure, just because it provides a property key instead of a java getter for getting passwords.

If I had to chose one though I would take option (2).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜