且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么不使用ResourceBundle而不是Properties?

更新时间:2023-12-04 11:00:46


那么,为什么我不应该使用ResourceBundle而不是属性,当第二个是更详细?

So, why shouldn’t I use the ResourceBundle instead of Properties when the second one is more verbose?

因为那不是 ResourceBundle 所针对的。 课程描述以:

Because that's not what ResourceBundle is for. The description of the class starts with:


资源包包含特定于语言环境的对象。当您的程序需要特定于语言环境的资源(例如String)时,您的程序可以从适合当前用户的语言环境的资源包中加载它。通过这种方式,您可以编写程序代码,该程序代码在很大程度上独立于用户的语言环境,隔离资源包中大多数(如果不是全部)特定于语言环境的信息。

Resource bundles contain locale-specific objects. When your program needs a locale-specific resource, a String for example, your program can load it from the resource bundle that is appropriate for the current user's locale. In this way, you can write program code that is largely independent of the user's locale isolating most, if not all, of the locale-specific information in resource bundles.

这听起来像你的用例吗?我不这么认为。

Does any of this sound like your use case? I don't think so.

听起来问题是纯粹加载属性文件的详细程度:所以写一个实用工具方法去做。然后您的代码可以简单:

It sounds like the problem is purely the verbosity of loading a properties file: so write a utility method to do that. Then your code can be simply:

private static final Properties CONFIGURATION = PropertyUtil.load("scheduler.properties");
private static final String DRIVER = CONFIGURATION.getString("bd.driver");
private static final String CONNECTIONURL = CONFIGURATION.getString("bd.url");

不可否认,我并不热衷于以依赖于顺序的方式使用静态字段初始化程序。我很想把所有的配置封装在一个单独的类中,所以你可以这样写:

Admittedly I'm not keen on having static field initializers in an order-dependent way like that... I'd be tempted to encapsulate all of the configuration in a separate class, so you could write:

private static final SchedulerConfiguration CONFIG = 
    SchedulerConfiguration.load("scheduler.properties");

然后使用 CONFIG.getDriver()等可以每次从属性中获取,或使用字段,或其他任何内容。

then use CONFIG.getDriver() etc which could fetch from the properties each time, or use a field, or whatever.