Java en iyi uygulamaları, sabit okuma özelliklerini önerir. Peki, sizce ona ulaşmak için en iyi yaklaşım nedir? Benim yaklaşımım: Özellikler dosyasını sadece bir kez okuyabilmek için bir konfigürasyon sınıfı (singleton pattern) ve sabit olarak gerektiğinde özellikleri okumak için bu sınıfı kullanır. Ve saklamak için bir Sabitler sınıfı:Java sabitleri ve özellikleri
- Özellikler dosyasında bunları bulmak için özellik adı (örneğin, app.database.url).
- Statik sabitler (kullanıcının yapılandırma yapmasını istemediğim gibi, örneğin 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();
}}
sabit Sınıf özellikleri ve sabitleri referanslar içerir.
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;
}
Ve dosyaları özellikleri şöyle olacaktır:
db.url=www.myurl.com
db.driver=mysql
özelliklerini okumak için ve sabitler olacaktır:
// Constants
int i = Constants.MYCONSTANT_ONE;
// Properties
String url = Configurations.getInstance().getProperty(Constants.DB_URL);
Bu iyi bir yaklaşım olduğunu düşünüyor musunuz? Java'daki özellikleri ve sabitleri okuma yolunuz nedir?
Şimdiden teşekkürler.
Fabien'in de mümkün olan “getProperty” işlevini “getInstance” içine koyması ve bunu “getInstance(). GetProperty' adlı çağrıdan kaçınmak için yeni getProperty” olarak yeniden adlandırması gibi yorumladı. anlama. –