gradle中的条件依赖

Slo*_*lok 6 java gradle

我正在使用gradle进行多项目构建。我有一个要求选择依赖项取决于在命令行中注入的属性的条件。

方案1:

        dependencies {

            if( ! project.hasProperty("withsources")){


             compile 'com.xx.yy:x-u:1.0.2'

            }else{
              println " with sources"
              compile project (':x-u')
            }

        }
Run Code Online (Sandbox Code Playgroud)

1.每当我执行gradle run -Pwithsources

    it is printing "withsources" 
Run Code Online (Sandbox Code Playgroud)

2.但是对于gradle run

    it is printing "withsources" 
Run Code Online (Sandbox Code Playgroud)

方案2:

        dependencies {

            if(  project.hasProperty("withsources")){


             compile 'com.xx.yy:x-u:1.0.2'

            }else{
              println " with sources"
              compile project (':x-u')
            }

        }
Run Code Online (Sandbox Code Playgroud)

1.每当我执行gradle run -Pwithsources

    it is not printing "withsources" 
Run Code Online (Sandbox Code Playgroud)

2.但是对于gradle run

    it is not printing "withsources" 
Run Code Online (Sandbox Code Playgroud)

我不知道它总是进入其他循环。任何人都可以在这里提供帮助。

Ran*_*niz 7

在看不到完整的build.gradle之前,我无法真正地说出您的问题所在,但您的一般做法是正确的。

这是一个对我有用的小例子:

plugins {
    id "java"
}

repositories {
    jcenter()
}

dependencies {
    if (project.hasProperty("gson")) {
        implementation "com.google.gson:gson:2.8.5"
    } else {
        implementation "org.fasterxml.jackson.core:jackson-core:2.9.0"
    }
}
Run Code Online (Sandbox Code Playgroud)

无财产:

$ gradle dependencies --configuration implementation
:dependencies

------------------------------------------------------------
Root project
------------------------------------------------------------

implementation - Implementation only dependencies for source set 'main'. (n)
\--- org.fasterxml.jackson.core:jackson-core:2.9.0 (n)

(n) - Not resolved (configuration is not meant to be resolved)

BUILD SUCCESSFUL in 0s
1 actionable task: 1 executed
Run Code Online (Sandbox Code Playgroud)

带有属性:

$ gradle -Pgson dependencies --configuration implementation
:dependencies

------------------------------------------------------------
Root project
------------------------------------------------------------

implementation - Implementation only dependencies for source set 'main'. (n)
\--- com.google.gson:gson:2.8.5 (n)

(n) - Not resolved (configuration is not meant to be resolved)

BUILD SUCCESSFUL in 0s
1 actionable task: 1 executed
Run Code Online (Sandbox Code Playgroud)

您是否有可能在其他地方定义了withsources?像在gradle.properties中一样?

  • 请忽略这是我的错误未检查gradle.properties (2认同)