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


当前回答

假设你正在使用Java,你可以:

Create a .properties file in (most commonly) your src/main/resources directory (but in step 4 you could tell it to look elsewhere). Set the value of some property in your .properties file using the standard Maven property for project version: foo.bar=${project.version} In your Java code, load the value from the properties file as a resource from the classpath (google for copious examples of how to do this, but here's an example for starters). 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.name, project.description,甚至是你放在pom <properties>中的任意属性,等等。资源过滤与Maven概要文件相结合,可以在构建时为您提供可变的构建行为。当您在运行时使用-PmyProfile指定配置文件时,可以启用属性,然后可以在构建中显示这些属性。

其他回答

如果你使用mvn包装,如jar或war,使用:

getClass().getPackage().getImplementationVersion()

它读取生成的META-INF/MANIFEST的“Implementation-Version”属性。MF(它被设置为pom.xml的版本)。

公认的答案可能是将版本号静态地放入应用程序的最佳和最稳定的方法,但实际上并没有回答最初的问题:如何从pom.xml检索工件的版本号?因此,我想提供一个替代方案,展示如何在运行时动态地做这件事:

您可以使用Maven本身。更确切地说,您可以使用Maven库。

<dependency>
  <groupId>org.apache.maven</groupId>
  <artifactId>maven-model</artifactId>
  <version>3.3.9</version>
</dependency>

然后在Java中这样做:

package de.scrum_master.app;

import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;

import java.io.FileReader;
import java.io.IOException;

public class Application {
    public static void main(String[] args) throws IOException, XmlPullParserException {
        MavenXpp3Reader reader = new MavenXpp3Reader();
        Model model = reader.read(new FileReader("pom.xml"));
        System.out.println(model.getId());
        System.out.println(model.getGroupId());
        System.out.println(model.getArtifactId());
        System.out.println(model.getVersion());
    }
}

控制台日志如下:

de.scrum-master.stackoverflow:my-artifact:jar:1.0-SNAPSHOT
de.scrum-master.stackoverflow
my-artifact
1.0-SNAPSHOT

更新2017-10-31:为了回答Simon Sobisch的后续问题,我修改了这个例子:

package de.scrum_master.app;

import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.codehaus.plexus.util.xml.pull.XmlPullParserException;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Application {
  public static void main(String[] args) throws IOException, XmlPullParserException {
    MavenXpp3Reader reader = new MavenXpp3Reader();
    Model model;
    if ((new File("pom.xml")).exists())
      model = reader.read(new FileReader("pom.xml"));
    else
      model = reader.read(
        new InputStreamReader(
          Application.class.getResourceAsStream(
            "/META-INF/maven/de.scrum-master.stackoverflow/aspectj-introduce-method/pom.xml"
          )
        )
      );
    System.out.println(model.getId());
    System.out.println(model.getGroupId());
    System.out.println(model.getArtifactId());
    System.out.println(model.getVersion());
  }
}

接受的答案在步骤#2中为我工作过一次,我改变了${项目。版本}到${pom.version}

关于ketankk的回答:

不幸的是,添加这个打乱了我的应用程序处理资源的方式:

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

但是在maven-assemble-plugin的< manifest >标签中使用这个可以达到目的:

<addDefaultImplementationEntries>true</addDefaultImplementationEntries>
<addDefaultSpecificationEntries>true</addDefaultSpecificationEntries>

所以我能得到版本使用

String version = getClass().getPackage().getImplementationVersion();

第一步:如果你使用Spring Boot,你的pom.xml应该已经包含了Spring - Boot -maven-plugin。您只需要添加以下配置。

<plugin>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-maven-plugin</artifactId>
    <executions>
        <execution>
            <id>build-info</id>
            <goals>
                <goal>build-info</goal>
            </goals>
        </execution>
    </executions>
</plugin>

它指示插件执行build-info目标,默认情况下不会运行。这会生成关于应用程序的构建元数据,包括工件版本、构建时间等。

步骤2:使用buildProperties bean访问构建属性。在我们的例子中,我们创建了一个restResource来访问我们的webapp中的构建信息

@RestController
@RequestMapping("/api")
public class BuildInfoResource {
    @Autowired
    private BuildProperties buildProperties;

    
    @GetMapping("/build-info")
    public ResponseEntity<Map<String, Object>> getBuildInfo() {
        Map<String, String> buildInfo = new HashMap();
        buildInfo.put("appName", buildProperties.getName());
        buildInfo.put("appArtifactId", buildProperties.getArtifact());
        buildInfo.put("appVersion", buildProperties.getVersion());
        buildInfo.put("appBuildDateTime", buildProperties.getTime());
        return ResponseEntity.ok().body(buldInfo);
    }
}

我希望这能有所帮助