簡體   English   中英

在 Gradle 項目中獲取 Kotlin/Java 代碼中的版本

[英]Get Version in Kotlin/Java code in Gradle project

我有一個用 kotlin 編碼的網絡服務,並由 gradle 管理構建/依賴項等......

我想做一件簡單的事情:當有人調用我的網絡服務的version REST 端點時,它返回版本。

既然已經gradle這個處理與該版本version在性能build.gradle ,我認為這將是很容易得到這個值,但現在看來,這是不是...我已經好幾個小時搜索谷歌,一切似乎那么復雜。

知道如何以好的方式處理版本嗎?

這是我現在所擁有的:

構建.gradle

version = "1.0.0"
...

狀態服務.kt

class StatusService : IStatusService {

    //TODO: Here I would like to get the version from the gradle 
    //file instead of maintaining 2 places for the version
    //Something like Gradle.getProperties("version") for example
    override fun getVersion() : String = "1.0.0"

}

我可能完全錯了,所以如果你有另一個等效的解決方案,我也會接受它! 謝謝

一種方法是將版本文件作為Gradle構建的一部分輸出到類路徑中可作為應用程序中的資源訪問的位置。

例如:

您可以將此文件添加到build.gradle文件中,該文件將生成包含項目版本號的屬性文件,並將其添加到應用程序源集中,以便在類路徑中可用。

def generatedVersionDir = "${buildDir}/generated-version"

sourceSets {
    main {
        output.dir(generatedVersionDir, builtBy: 'generateVersionProperties')
    }
}

task generateVersionProperties {
    doLast {
        def propertiesFile = file "$generatedVersionDir/version.properties"
        propertiesFile.parentFile.mkdirs()
        def properties = new Properties()
        properties.setProperty("version", rootProject.version.toString())
        propertiesFile.withWriter { properties.store(it, null) }
    }
}
processResources.dependsOn generateVersionProperties

然后在您的代碼中,您將能夠通過讀取屬性文件來訪問它:

class StatusService : IStatusService {
    private val versionProperties = Properties()

    init {
        versionProperties.load(this.javaClass.getResourceAsStream("/version.properties"))
    }

    override fun getVersion() : String = versionProperties.getProperty("version") ?: "no version"
}

當然,您可能會發現將String輸出到版本文件更簡單,更合適,然后在代碼中將整個文件作為String讀取,而不是使用屬性文件。

Gradle僅出現在編譯中,而不是在運行時。

為此,您必須在編譯時生成一個類。
使用Android項目,生成了BuildConfig.java文件,但我不知道它是Gradle還是Android。

要生成Kotlin代碼,您可以檢查KotlinPoet

考慮簡單的Kotlin Spring Boot示例:

@SpringBootApplication
@RestController
class DemoApplication {
    @Value("\${version}")
    private lateinit var version: String

   @GetMapping("/version")
   fun version() = version
}

fun main(args: Array<String>) {
    runApplication<DemoApplication>(*args)
}

由於屬性可以從application.properties獲取,我們需要生成具有所需版本的文件。 為此,我們可以創建一個包含以下內容的模板屬性文件:

version=###appVersion

現在讓我們告訴Gradle將該模板復制到resource文件夾並放置版本而不是占位符

import org.apache.tools.ant.filters.ReplaceTokens

task preprocessProperties(type: Copy) {
    from 'src/main/resources/templates'
    into 'src/main/resources'
    include 'template.properties'
    rename 'template.properties', 'application.properties'
    filter(ReplaceTokens, beginToken: '###', endToken: '', tokens: [appVersion: '1.0.0'])
}

compileKotlin.dependsOn preprocessProperties

並且,瞧,每次編譯Kotlin源代碼時,您都會獲得一個包含所需版本的屬性文件。

花了一些時間來弄清楚如何將接受的答案轉換為build.gradle.kts ,但這有效:

import java.io.FileOutputStream
import java.util.Properties

version = "your-version"

val generatedVersionDir = "$buildDir/generated-version"

sourceSets {
  main {
    kotlin {
      output.dir(generatedVersionDir)
    }
  }
}

tasks.register("generateVersionProperties") {
  doLast {
    val propertiesFile = file("$generatedVersionDir/version.properties")
    propertiesFile.parentFile.mkdirs()
    val properties = Properties()
    properties.setProperty("version", "$version")
    val out = FileOutputStream(propertiesFile)
    properties.store(out, null)
  }
}

tasks.named("processResources") {
  dependsOn("generateVersionProperties")
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM