Access project extra properties in buildscript clo

2019-01-09 15:20发布

问题:

I am new to gradle and have some question about project properties.

I need to declare spring boot dependences at multiple locations in my build.gradle and I'd like to use a variable to define the version. What is the best way in gradle? (in Maven, I use properties)

My attempt is use extra properties, but it cannot access the property in the buildscript closure. I googled around and read many articles accessing properties in custom tasks. What did I miss?

ext {
    springBootVersion = '1.1.9.RELEASE'
}

buildscript {

    print project.springBootVersion //fails here

    repositories {
        mavenLocal()
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${project.springBootVersion}")
    }
}

install {
    repositories.mavenInstaller {
        pom.project {
            parent {
                groupId 'org.springframework.boot'
                artifactId 'spring-boot-starter-parent'
                version "${project.springBootVersion}" //this one works
            }
        }
    }
}

回答1:

Moving the ext block inside the buildscript block solves the problem for me. Not sure if this is officially supported though, as it's effectively configuring project.ext from the (very special) buildscript block.



回答2:

This will not work.

First of all buildscript block is evaluated at the very beginning, before any other part of groovy script. Hence, properties defined in ext block just does not exist at that time.

Secondly, I'm unsure about if exchanging properties between buildscript and other part of script is possible.



回答3:

Because the buildscript block is evaluated first, before springBootVersion has been defined. Therefore, the variable definition must go in the buildscript block before any other definitions: Source Here

buildscript {

    ext {
        springBootVersion = '1.1.9.RELEASE'
    }

    print project.springBootVersion //Will succeed

    repositories {
        mavenLocal()
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${project.springBootVersion}")
    }
}


标签: gradle