从属性文件加载不同的集成

Loading different integrations from properties file

我正在我的大学做一个期末项目,我遇到了一个特别的问题。我正在使用 TestNG 和 Selenium 测试某些网站在本地主机中的工作方式。现在,我有不同的集成,这意味着它使用在属性文件中配置的不同数据库。我希望我可以在 JVM 或命令行中传递参数,例如 "integration1" 并且它会从 属性 文件中捕获该字段。我在网上找到的唯一东西是关于 Spring 配置文件,但这没有帮助,因为它是一个普通的 java 项目。这是一个代码:

default.properties

db_driver = com.mysql.jdbc.Driver
db_path = jdbc:mysql://localhost:3306/dana?useUnicode=true&characterEncoding=UTF-8

user.properties(它检查 user.properties 文件中是否存在某个字段,如果存在则使用该字段而不是默认字段,这对团队中的其他成员很有用,因为每个配置都不同)

db_driver = com.mysql.jdbc.Driver
db_path_elixir = jdbc:mysql://localhost:3306/elixir?useUnicode=true&characterEncoding=UTF-8
db_path_dana = jdbc:mysql://localhost:3306/dana?useUnicode=true&characterEncoding=UTF-8
#db_path - actual path which will be used if user passes "dana" or "elixir" as arguments
#my logic would be something like db_path = jdbc:mysql://localhost:3306/ + ${integration} + ?useUnicode=true&characterEncoding=UTF-8

那些 属性 文件是在 ConfigurationService class

中配置的

ConfigurationService.java

...
private String getProperty(String key) {
    if (userProperties.containsKey(key)) {
        return userProperties.getProperty(key);
    }
    return defaultProperties.getProperty(key);
}

您可以按如下方式修改 ConfigurationService 并从命令行将 属性 作为 java -Dkey=value 传递。

private String getProperty(String key){
    String value = null;
    if (System.getProperties().contains(key))
        value = System.getProperty(key);
    else if (userProperties.containsKey(key))
        value = userProperties.getProperty(key);
    else
        value = defaultProperties.getProperty(key);
}

您还可以按如下方式初始化 ConfigurationService 实例

Properties properties;
public void init(){
 properties.putAll(defaultProperties);
 properties.putAll(userProperties);
 properties.putAll(System.getProperties());
}

然后修改您的 getProperty 方法如下

private String getProperty(String key){
        return properties.getProperty(key);
}

此处 putAll 调用的顺序很重要。当您再次输入相同的 key-value 时,先前的值将被覆盖。