init.gradle从命令行读取属性

时间:2013-11-14 16:38:49

标签: java properties gradle init

在我的gradle脚本中,我已经能够成功读取这样的属性:

def environment = hasProperty('env') ? env : 'dev'

使用这个我可以执行这样的构建脚本:

gradlew clean assemble -Penv=prod

当我尝试将其移至init.gradle文件时,我的问题就出现了。该文件被识别,我可以使用我在脚本中定义的其他属性,但是我无法从命令行获取任何属性。我怎么能这样做?

我的init.gradle文件:

allprojects {
    buildscript {
        repositories {
            mavenCentral()
        }
        dependencies {
            classpath 'com.android.tools.build:gradle:0.6.+'
        }
    }
    project.ext['nexusDomainName'] = 'https://example.com/nexus'
    project.ext['compileSdkVersion'] = 19
    project.ext['buildToolsVersion'] = "19"
    project.ext['minSdkVersion'] = 8
    project.ext['targetSdkVersion'] = 19

    project.ext['sourceCompatibility'] = '1.7'
    project.ext['targetCompatibility'] = '1.7'

    //hasProperty('release') is always false
    project.ext['archiveType'] = hasProperty('release') ? '' : '-SNAPSHOT'
    project.ext['archiveUrl'] = hasProperty('release') ? "$nexusDomainName/content/repositories/releases/" : "$nexusDomainName/content/repositories/snapshots/"


    // This buildEnv property won't read either
    project.ext['buildEnv'] = hasProperty('env') ? env : 'dev'
    println "prepping for $buildEnv"
    project.ext['archivesBaseNameSuffix'] = (project.ext['buildEnv'] == 'stage' || project.ext['buildEnv'] == 'dev') ? '-' + project.ext['buildEnv'] : ''

    repositories {
        mavenLocal()
        maven {
            credentials {
                username 'username'
                password 'password'
            }
            url "$nexusDomainName/content/groups/public/"
        }
        mavenCentral()
    }
}

1 个答案:

答案 0 :(得分:1)

-P设置项目属性,该属性在init脚本中不会立即可用。 (您可以从init脚本访问项目及其属性,但在创建项目之前,该访问将延迟。)但是,使用 system 属性(-D)应该可以正常工作。