java java中的常量和属性

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29896927/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 16:06:07  来源:igfitidea点击:

Constants and properties in java

javaconfigurationconstantsconfigproperties-file

提问by Esteban S

Java best practices recommends read properties as constants. So, what do you think is the best approach to reach it? My approach is: A Configuration class to read the properties file only one time (singleton pattern) and use this class to read properties when needed as constants. And a Constants class to store:

Java 最佳实践建议将读取属性作为常量。那么,您认为达到它的最佳方法是什么?我的方法是:一个配置类只读取一次属性文件(单例模式),并在需要时使用这个类作为常量读取属性。还有一个用于存储的 Constants 类:

  • The properties name to find them in the properties file (eg app.database.url).
  • Static constants (those that I don't want the user to config eg CONSTANT_URL="myurl.com").
  • 在属性文件中找到它们的属性名称(例如 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();
}}

The Constant class contains the references to the properties and the Constants.

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;
}

And the properties files would be:

属性文件将是:

db.url=www.myurl.com
db.driver=mysql

To read the properties and constants would be:

读取属性和常量将是:

// Constants
int i = Constants.MYCONSTANT_ONE;
// Properties
String url = Configurations.getInstance().getProperty(Constants.DB_URL);

Do you think this is a good approach? What is your way to read properties and constants in Java?

你认为这是一个好方法吗?在 Java 中读取属性和常量的方法是什么?

Thanks in advance.

提前致谢。

采纳答案by Esteban S

I found a better solution to homogenize the code and has everything as constants. With the same Configurations class and .properties file: Since getInstance() method is static it is possible to init the constants in the class Constants.

我找到了一个更好的解决方案来统一代码并将所有内容都作为常量。使用相同的 Configurations 类和 .properties 文件:由于 getInstance() 方法是静态的,因此可以在类 Constants 中初始化常量。

A class to store the name to the property in .properties file:

将名称存储到 .properties 文件中的属性的类:

public class Properties {
// Properties (user configurable)
public static final String DB_URL = "db.url";
public static final String DB_DRIVER = "db.driver";
}

And then the Constant class will be:

然后 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;
}

And finally to use them:

最后使用它们:

// Constants
int i = Constants.MYCONSTANT_ONE;
// Properties
String url = Constants.DB_URL;

I think it is a clean and elegant solution that fix constants and properties problems in tests.

我认为这是一个干净优雅的解决方案,可以解决测试中的常量和属性问题。

回答by Fabien

I think you should have a look to Apache Commons Configuration, you could find it useful. You can do a lot of things like having a hierarchy for your config files, specify multiple sources.

我认为你应该看看Apache Commons Configuration,你会发现它很有用。你可以做很多事情,比如为你的配置文件设置层次结构,指定多个源。

For the Constants it seems good :)

对于常量,它似乎不错:)