kotlindesktop-applicationgradle-kotlin-dsl

Share variables between build.gradle.kts and the application


Is it possible to share variables between build.gradle.kts and the main application? I would like to specify the application's name and version and few other settings only once.


Solution

  • There is a way using build sources. You can reference this code in your build.gradle.kts and your application, so you can define your variables there. Organizing Gradle Projects - Use buildSrc to abstract imperative logic

    Example:

    Project structure:

    root/
    ├── build.gradle.kts
    ├── buildSrc/
    │   └── src/
    │       └── main/
    │           └── kotlin/
    │               └── Versions.kt
    └── src/
        └── main/
            └── kotlin/
                └── com/
                    └── example/
                        └── MyAppApplication.kt
    

    Code:

    // buildSrc/src/main/kotlin/Versions.kt
    object Versions {
        const val appName = "MyAwesomeApp"
        const val appVersion = "1.0.0"
    }
    
    // build.gradle.kts
    plugins {
        id("org.springframework.boot") version "3.0.0"
        kotlin("jvm") version "1.8.0"
    }
    
    group = "com.example"
    version = Versions.appVersion // Using the version variable
    
    application {
        applicationName = Versions.appName // Using the appname
    }
    
    dependencies {
        implementation("org.springframework.boot:spring-boot-starter")
        implementation(files("./buildSrc/build/libs/buildSrc.jar")) // Add the buildSrc.jar as dependency to use it in your main code. 
    }
    
    // src/main/kotlin/com/example/MyAppApplication.kt
    package com.example.myapp
    
    import Versions
    
    @SpringBootApplication
    class MyAppApplication {
        init {
            println("App Name: ${Versions.appName}, Version: ${Versions.appVersion}")
        }
    }
    
    fun main(args: Array<String>) {
        runApplication<MyAppApplication>(*args)
    }
    

    Hope this helps.