【发布时间】:2015-07-05 23:25:36
【问题描述】:
Java 最佳实践建议将属性读取为常量。那么,您认为实现它的最佳方法是什么?我的方法是:一个配置类,只读取一次属性文件(单例模式),并在需要时使用该类作为常量读取属性。还有一个要存储的常量类:
- 要在属性文件中找到它们的属性名称(例如 app.database.url)。
- 静态常量(我不希望用户配置的常量,例如 CONSTANT_URL="myurl.com")。
public final class Configurations {
private Properties properties = null;
private static Configurations instance = null;
/** Private constructor */
private Configurations (){
this.properties = new Properties();
try{
properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(Constants.PATH_CONFFILE));
}catch(Exception ex){
ex.printStackTrace();
}
}
/** Creates the instance is synchronized to avoid multithreads problems */
private synchronized static void createInstance () {
if (instance == null) {
instance = new Configurations ();
}
}
/** Get the properties instance. Uses singleton pattern */
public static Configurations getInstance(){
// Uses singleton pattern to guarantee the creation of only one instance
if(instance == null) {
createInstance();
}
return instance;
}
/** Get a property of the property file */
public String getProperty(String key){
String result = null;
if(key !=null && !key.trim().isEmpty()){
result = this.properties.getProperty(key);
}
return result;
}
/** Override the clone method to ensure the "unique instance" requeriment of this class */
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}}
Constant 类包含对属性和常量的引用。
public class Constants {
// Properties (user configurable)
public static final String DB_URL = "db.url";
public static final String DB_DRIVER = "db.driver";
// Constants (not user configurable)
public static final String PATH_CONFFILE = "config/config.properties";
public static final int MYCONSTANT_ONE = 1;
}
属性文件将是:
db.url=www.myurl.com
db.driver=mysql
读取属性和常量是:
// Constants
int i = Constants.MYCONSTANT_ONE;
// Properties
String url = Configurations.getInstance().getProperty(Constants.DB_URL);
您认为这是一个好方法吗?在 Java 中读取属性和常量的方法是什么?
提前致谢。
【问题讨论】:
标签: java configuration constants config properties-file