Java最佳实践建议将属性作为常量读取。那么,您认为达到目标的最佳方法是什么?我的方法是:一个Configuration类只读取一次属性文件(单例模式),并使用此类在需要时读取属性作为常量。还有一个存储的Constants类:
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中读取属性和常量的方法是什么?
提前致谢。
答案 0 :(得分:4)
我找到了一个更好的解决方案来均匀化代码并将所有内容都作为常量。使用相同的Configurations类和.properties文件:由于getInstance()方法是静态的,因此可以在类Constants中初始化常量。
将名称存储在.properties文件中的属性的类:
public class Properties {
// Properties (user configurable)
public static final String DB_URL = "db.url";
public static final String DB_DRIVER = "db.driver";
}
然后Constant类将是:
public class Constants {
// Properties (user configurable)
public static final String DB_URL = Configurations.getInstance().getProperty(Properties.DB_URL);
public static final String DB_DRIVER = Configurations.getInstance().getProperty(Properties.DB_DRIVER );
// Constants (not user configurable)
public static final String PATH_CONFFILE = "config/config.properties";
public static final int MYCONSTANT_ONE = 1;
}
最后使用它们:
// Constants
int i = Constants.MYCONSTANT_ONE;
// Properties
String url = Constants.DB_URL;
我认为这是一个干净而优雅的解决方案,可以修复测试中的常量和属性问题。
答案 1 :(得分:2)
我认为你应该看看Apache Commons Configuration,你会发现它很有用。您可以执行很多操作,例如为配置文件建立层次结构,指定多个源。
对于常数来说似乎很好:)