我需要一些数据资源组织方面的帮助。我有一些resource.properties文件(LabelResources.properties,ParagraphResources.properties)。我可以通过以下标准方式从他们那里获取数据:
private static ResourceBundle myBundle = ResourceBundle.getBundle("com.helmes.rentalstore.res.Resource");
myBundle.getString("welcome")
我不喜欢这一刻我需要在所有需要从recource获取字符串的所有类中进行初始化。如果可以,我可以在没有显式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原则和设计正常实现的吗?
答案 0 :(得分:0)
您可以编写一个包装器单例类,它只进行一次实际的包初始化,并在进一步的请求中使用这些包:
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);
}
}
答案 1 :(得分:0)
一种模式是为所有资源包提供集中式Resources
类:
public class Resources {
public static final ResourceBundle Labels = ResourceBundle.getBundle("...");
public static final ResourceBundle Paragraphs = ResourceBundle.getBundle("...");
// ... more ...
}
用法:
label.setText(Resources.Labels.getString("welcome"));
但通常您会将UI代码分组到java包中,因此您可能拥有每个(UI)包的资源包。在这种情况下,您应该为每个java包(包含资源包)编写一个Messages
类:
public class Messages {
private static final ResourceBundle bundle = ResourceBundle.getBundle("...");
public static String getString(String key) {
return bundle.getString(key);
}
}
用法:
label.setText(Messages.getString("welcome));
例如,Eclipse IDE可以为您和helps you to externalize your strings自动创建此类Messages
类。