溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

獲取Maven項目版本號的方式有哪些

發(fā)布時間:2022-02-23 15:10:56 來源:億速云 閱讀:194 作者:小新 欄目:開發(fā)技術

小編給大家分享一下獲取Maven項目版本號的方式有哪些,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!

Maven 是經(jīng)常用來創(chuàng)建項目的一個工具,主要是因為它方便項目構建、管理以及下載 jar 包。

目前大多數(shù)Spring Boot項目都會打成Jar包,所以什么War包、Ear包的就先不摸索了。

Jar包的秘密

我們先解壓一個Spring Boot應用Jar包看看里面能不能找到一些蛛絲馬跡。在META-INF文件夾中找到了兩個相關的東西,一個是MANIFEST.MF:

Manifest-Version: 1.0
Spring-Boot-Classpath-Index: BOOT-INF/classpath.idx
Implementation-Title: spring-boot-version
Implementation-Version: 1.0.23
Spring-Boot-Layers-Index: BOOT-INF/layers.idx
Start-Class: cn.felord.SpringBootVersionApplication
Spring-Boot-Classes: BOOT-INF/classes/
Spring-Boot-Lib: BOOT-INF/lib/
Build-Jdk-Spec: 1.8
Spring-Boot-Version: 2.4.5
Created-By: Maven Jar Plugin 3.2.0
Main-Class: org.springframework.boot.loader.JarLauncher

里面包含了我定義的版本號1.0.23,Implementation-Version這個值好像通過代碼能夠獲得:

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

但是用IDE啟動發(fā)現(xiàn)version=null,不過用java -jar運行時version = 1.0.23??赡芘cIDE運行并不是通過jar的方式有關。

另一個是pom.properties,Maven項目編譯會生成一個Properties配置文件:

artifactId=spring-boot-version
groupId=cn.felord
version=1.0.23

這豈不是讀取Properties文件就可以了?

  String path = "META-INF/maven/cn.felord/spring-boot-version/pom.properties";
  ClassPathResource resource = new ClassPathResource(path);

  InputStream inputStream = resource.getInputStream();
  try (InputStreamReader reader = new InputStreamReader(inputStream)) {
      try (BufferedReader bufferedReader = new BufferedReader(reader)) {
          bufferedReader.lines()
                                .forEach(System.out::println);
         }
     } catch (Exception ignored) {

  }

這豈不是讀取Properties文件就可以了?

  String path = "META-INF/maven/cn.felord/spring-boot-version/pom.properties";
  ClassPathResource resource = new ClassPathResource(path);

  InputStream inputStream = resource.getInputStream();
  try (InputStreamReader reader = new InputStreamReader(inputStream)) {
      try (BufferedReader bufferedReader = new BufferedReader(reader)) {
          bufferedReader.lines()
                                .forEach(System.out::println);
         }
     } catch (Exception ignored) {

  }

依然只能從jar讀取,而且比較麻煩。這兩種方式都要依賴jar包,有木有不單純依賴jar包的呢?

Maven資源插件過濾

Maven在構建項目時可以通過資源插件將構建屬性即pom.xml中的屬性注入到指定的資源文件中,具體操作為:

<build>
  ...
  <resources>
    <!-- include main.properties -->
    <resource>
      <directory>src/main/resources</directory>
      <filtering>true</filtering>
      <includes>
        <include>main.properties</include>
      </includes>
    </resource>
  </resources>
  ...
</build>

恰好spring-boot-starter-parent中已經(jīng)設置了這種方式。

      <resource>
        <directory>${basedir}/src/main/resources</directory>
        <filtering>true</filtering>
        <includes>
          <include>**/application*.yml</include>
          <include>**/application*.yaml</include>
          <include>**/application*.properties</include>
        </includes>
      </resource>

如果你是application.properties,你可以通過下面的方式來接收版本號:

application.version = ${project.version}

如果是application.yaml,你可以通過下面的方式來接收版本號:

application:
  version: '@project.version@'

然后如何取值就不用多說了吧。這種方式不依賴jar包,使用起來也很簡單。

Spring Boot提供

Spring Boot其實已經(jīng)內置了獲取項目構建信息的自動配置ProjectInfoAutoConfiguration,它包含一個條件BeanBuildProperties:

    @ConditionalOnResource(
        resources = {"${spring.info.build.location:classpath:META-INF/build-info.properties}"}
    )
    @ConditionalOnMissingBean
    @Bean
    public BuildProperties buildProperties() throws Exception {
        return new BuildProperties(this.loadFrom(this.properties
                                                 .getBuild()
                                                 .getLocation(), "build",                                                     this.properties
                                                 .getBuild().getEncoding()));
    }

這個BuildProperties提供了不少構建信息:

public class BuildProperties extends InfoProperties {
    public BuildProperties(Properties entries) {
        super(processEntries(entries));
    }

    public String getGroup() {
        return this.get("group");
    }

    public String getArtifact() {
        return this.get("artifact");
    }

    public String getName() {
        return this.get("name");
    }

    public String getVersion() {
        return this.get("version");
    }

    public Instant getTime() {
        return this.getInstant("time");
    }
   }

其中的條件build-info.properties可以通過Spring Boot插件spring-boot-maven-plugin執(zhí)行下面的命令生成:

mvn spring-boot:build-info

我們只需要配置插件為:

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

就能使得BuildProperties生效,我們可以輕松取得相關的信息:

{
  "version" : "1.0.23",
  "group" : "cn.felord",
  "artifact" : "spring-boot-version",
  "name" : "spring-boot-version",
  "time" : {
    "epochSecond" : 1620664643,
    "nano" : 591000000
  }
}

看完了這篇文章,相信你對“獲取Maven項目版本號的方式有哪些”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI