本文介绍了在代码中从 maven pom.xml 中检索版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在代码中从 maven 的 pom.xml 中检索版本号的最简单方法是什么,即以编程方式?

What is the simplest way to retrieve version number from maven's pom.xml in code, i.e., programatically?

推荐答案

假设您使用的是 Java,您可以:

Assuming you're using Java, you can:

  1. 在(最常见的)您的 src/main/resources 目录中创建一个 .properties 文件(但在第 4 步中,您可以告诉它在其他地方查找).

  1. Create a .properties file in (most commonly) your src/main/resources directory (but in step 4 you could tell it to look elsewhere).

使用项目版本的标准 Maven 属性设置 .properties 文件中某些属性的值:

Set the value of some property in your .properties file using the standard Maven property for project version:

foo.bar=${project.version}

  • 在您的 Java 代码中,将属性文件中的值作为类路径中的资源加载(谷歌有关如何执行此操作的大量示例,但 这是初学者的示例).

    在 Maven 中,启用资源过滤.这将导致 Maven 将该文件复制到您的输出类中,并在该复制期间翻译资源,解释属性.你可以在这里找到一些信息,但你大多只是在你的pom:

    In Maven, enable resource filtering. This will cause Maven to copy that file into your output classes and translate the resource during that copy, interpreting the property. You can find some info here but you mostly just do this in your pom:

    <build>
      <resources>
        <resource>
          <directory>src/main/resources</directory>
          <filtering>true</filtering>
        </resource>
      </resources>
    </build>
    

  • 您还可以访问其他标准属性,例如 project.nameproject.description,甚至是您放入 pom 中的任意属性 等.资源过滤,结合 Maven 配置文件,可以在构建时为您提供可变的构建行为.当您在运行时使用 -PmyProfile 指定配置文件时,它可以启用随后可以显示在您的构建中的属性.

    You can also get to other standard properties like project.name, project.description, or even arbitrary properties you put in your pom <properties>, etc. Resource filtering, combined with Maven profiles, can give you variable build behavior at build time. When you specify a profile at runtime with -PmyProfile, that can enable properties that then can show up in your build.

    这篇关于在代码中从 maven pom.xml 中检索版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

    08-07 07:55