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中读取属性和常量的方式是什么?
提前致谢。
getProperty
功能放入getInstance
中,并将其重命名为新的getProperty
,以避免调用getInstance().getProperty
,但我在帖子中保留了这种方式,因为这样更容易理解。 - Esteban S