小编典典

从Maven POM文件读取属性文件

tomcat

我有一些配置的Maven POM文件,在“插件”部分,我有一些配置的maven tomcat插件,如下所示:

<configuration>
   <url>http://localhost:8080/manager/html</url>
   <server>tomcat</server>
</configuration>

我想使用该键将url设置导出到某些属性文件,例如tomcat.properties:

url=http://localhost:8080/manager/html

以及如何在我的POM文件中读回此密钥?


阅读 722

收藏
2020-06-16

共1个答案

小编典典

Maven允许您在项目的POM中定义属性。您可以使用类似于以下内容的POM文件来执行此操作:

<project>
    ...
    <properties>
        <server.url>http://localhost:8080/manager/html</server.url>
    </properties>
    ...
    <build>
        <plugins>
            <plugin>
            ...
                <configuration>
                    <url>${server.url}</url>
                    <server>tomcat</server>
                </configuration>
            ...
            </plugin>
        </plugins>
    </build>
</project>

您可以避免在properties标记中指定属性,而将命令行中的值传递为:

mvn -Dserver.url=http://localhost:8080/manager/html some_maven_goal

现在,如果您不想从命令行指定它们,并且需要将这些属性与项目POM进一步隔离到一个属性文件中,则需要使用Properties
Maven插件
并运行它的read-project- properties目标在Maven生命周期初始化阶段。此处复制了插​​件页面的示例:

<project>
  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>properties-maven-plugin</artifactId>
        <version>1.0-alpha-2</version>
        <executions>
           <!-- Associate the read-project-properties goal with the initialize phase, to read the properties file. -->
          <execution>
            <phase>initialize</phase>
            <goals>
              <goal>read-project-properties</goal>
            </goals>
            <configuration>
              <files>
                <file>etc/config/dev.properties</file>
              </files>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>
2020-06-16