Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access project extra properties in buildscript closure

Tags:

gradle

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
            }
        }
    }
}
like image 952
Yugang Zhou Avatar asked Dec 09 '14 06:12

Yugang Zhou


People also ask

What is EXT in build Gradle?

ext is shorthand for project. ext , and is used to define extra properties for the project object. (It's also possible to define extra properties for many other objects.) When reading an extra property, the ext. is omitted (e.g. println project. springVersion or println springVersion ).


2 Answers

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.

like image 108
Peter Niederwieser Avatar answered Oct 22 '22 23:10

Peter Niederwieser


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}")
    }
}
like image 23
Darush Avatar answered Oct 23 '22 01:10

Darush