这可能是一个古老的问题,我相信每个人都有自己的方式。 假设我有一些属性定义,如java属性 - 暴露还是不暴露?
secret.user.id=user
secret.password=password
website.url=http://stackoverflow.com
假设我有100个不同的阶级和我需要使用这些属性的地方。 哪一个很好 (1)我创建了一个Util类,它将加载所有属性并使用键常量来提供它们。 Util是一个加载所有属性并保持getInstance
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)
所以无论我需要这些属性,我都可以执行上述步骤。
(2)我创建了一个有意义的类来表示这些属性;例如, ApplicationConfig并提供getter来获取特定的属性。 所以,上面的代码可能看起来像:
ApplicationConfig config = ApplicationConfig.getInstance();
doSomething(config.getSecretUserId(), config.getPassword());
//ApplicationConfig would have instance variables that are initialized during
// getInstance() after loading from properties file.
注:属性文件因此将在未来只有轻微的变化。
我个人的选择是(2) - 让我听听一些评论?
无论如何您不会缓存属性,所以如果您在几个不同的地方加载它,性能会受到影响吗? – willcodejavaforfood 2010-03-04 17:09:10
为什么使用锅炉板?我不这是一个很好的建议。 另请注意,我用程序设计标记了这一点。我喜欢代码运行良好,并且能够很好地阅读。 – 2010-03-04 17:12:24