gpt4 book ai didi

java - 一个ResourceBundle实例获取字符串资源

转载 作者:太空宇宙 更新时间:2023-11-04 14:49:16 24 4
gpt4 key购买 nike

我在数据资源组织方面需要一些帮助。我有一些resource.properties 文件(LabelResources.properties、ParagraphResources.properties)。我可以通过以下标准方式从他们那里获取数据:

private static ResourceBundle myBundle = ResourceBundle.getBundle("com.helmes.rentalstore.res.Resource");
myBundle.getString("welcome")

我不喜欢这里,我每次都需要在所有需要从资源中获取字符串的类中进行初始化。是否可以这样做,我可以在没有显式 ResourceBundle 初始化的情况下编写以下内容:

Resources.getBundle("com.helmes.rentalstore.res.Resource").getString("welcome")

更新

我用下面的方法做到了:

public enum ResourceBundleType {
LABELS(ResourceBundle.getBundle("Labels", Locale.ENGLISH)),
ERRORS(ResourceBundle.getBundle("Errors", Locale.ENGLISH));

private final ResourceBundle bundle;

private ResourceBundleType(ResourceBundle bundle) {
this.bundle = bundle;
}

public ResourceBundle getBundle() {
return bundle;
}
}


public class Resource {

private static Resource instance;
private ResourceBundle bundle;

private Resource(ResourceBundle bundle) {
this.bundle = bundle;
}

public static synchronized Resource getInstance(ResourceBundle bundle) {

if (instance == null) {
instance = new Resource(bundle);
} else if (!instance.bundle.getBaseBundleName().equals(bundle.getBaseBundleName())) {
instance = new Resource(bundle);
}

return instance;
}

public String getString(String key) {
if (bundle.containsKey(key))
return this.bundle.getString(key);

return null;
}

public String getString(String key, Object... params) {
if (bundle.containsKey(key))
return MessageFormat.format(this.bundle.getString(key), params);

return null;
}
}

调用它:

Resource.getInstance(ResourceBundleType.LABELS.getBundle()).getString("welcome", 1);

它现在正在我的项目中运行。你能评论一下吗?是否按照OOP原理和设计正常实现?

最佳答案

您可以编写一个包装器单例类来执行一次实际的 bundle 初始化,然后在进一步的请求中使用这些 bundle :

public class PropertiesHolder {

private static PropertiesHolder instance;

private PropertiesHolder() {
//initialize bundles here
}

public static synchronized PropertiesHolder getInstance() {
if (instance == null) {
instance = new PropertiesHolder();
}

return instance;
}

public String getProperty(String key) {
//something like return bundle.getstring(key);
}
}

关于java - 一个ResourceBundle实例获取字符串资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23994782/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com