【问题标题】:Loading different integrations from properties file从属性文件加载不同的集成
【发布时间】:2019-06-12 09:14:28
【问题描述】:

我正在我的大学做一个期末考试项目,我遇到了一个特殊的问题。我正在使用 TestNG 和 Selenium 测试某些网站在 localhost 中的工作方式。现在,我有不同的集成,这意味着它使用属性文件中配置的不同数据库。我希望我可以在 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 类中配置的

ConfigurationService.java

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

【问题讨论】:

    标签: java selenium jvm testng properties-file


    【解决方案1】:

    您可以如下修改您的 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 调用的顺序很重要。当您再次放置相同的键值时,较早的值将被覆盖。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-15
      • 2013-07-28
      • 1970-01-01
      • 2011-06-20
      • 2010-09-24
      相关资源
      最近更新 更多