在属性文件中引用来自 pom.xml 的标记,以便在 Java 中使用它

Reference tag from pom.xml in properties file to use it in Java

Java:

    ...
    Properties properties = new Properties();
    FileInputStream in;
    try {
        in = new FileInputStream("src/main/resources/profile.properties");
        properties.load(in);
        in.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    System.out.println(properties.getProperty("url") + "<---");
    driver.get(properties.getProperty("url"));
    ...

profile.properties 文件:

url = ${webdriver.base.url}

行家:

...
<properties>
    ...
    <webdriver.base.url></webdriver.base.url>
    ...
</properties>
...
<resources>
    <resource>
        <directory>src/main/resources</directory>
        <filtering>true</filtering>
        <includes>
            <include>profile.properties</include>
        </includes>
    </resource>
    <resource>
        <directory>src/main/resources</directory>
        <filtering>false</filtering>
        <excludes>
            <exclude>profile.properties</exclude>
        </excludes>
    </resource>
</resources>
...
<profiles>
    <profile>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <id>staging</id>
        <properties>
            <webdriver.base.url>google.de</webdriver.base.url>
        </properties>
    </profile>
</profiles>
...

我想在不同的系统(staging、prod 等)中执行宁静测试。为此,我尝试使用 pom.xml 中的配置文件,将 <webdriver.base.url> 标记引用到 profile.properties 中的值 url,然后通过 driver.get(properties.getProperty("url")); 调用此值. System.out.println(properties.getProperty("url") + "<---"); 在控制台中给出 ${webdriver.base.url}<---(扩展为 google.de)。所以,这意味着参考不起作用。我已经阅读了很多关于这个主题的主题,但没有找到解决我的问题的方法。如何将 xml 中的标记引用到属性文件中的变量,然后在 Java 中使用它?可能吗?

PS 当我将鼠标悬停在属性文件中的 ${webdriver.base.url} 上并按下 Ctrl 并单击它时,我将被重定向到 xml 文件到 <webdriver.base.url>google.de</webdriver.base.url>.

您正在使用来自 src/main/resources 的文件,Maven 将带有替换的属性文件放入 ${project.build.directory}。因此,您需要更改 java 代码以使用

in = ClassLoader.getSystemResourceAsStream("profile.properties");