如何在Java和Gradle Project中使用buildConfigField

时间:2018-02-18 11:05:50

标签: java gradle build.gradle

我来自Android背景。我正在使用Java,Kotlin和Gradle为Alexa创建一项技能。出于某种原因,我想像在android中那样在buildConfigField中声明一个常量,并从生成的BuildConfig.fieldName访问该字段。

我试过了,但BuildConfig从未生成过。

buildConfig {
    buildConfigField 'String', 'HOME', 'TEST_HOME'
}

build.gradle(完整档案)

apply plugin: 'java'
apply plugin: 'kotlin'

version = '1.0'

compileJava {
    targetCompatibility = JavaVersion.VERSION_1_8
    sourceCompatibility = JavaVersion.VERSION_1_8
}

buildConfig {
    buildConfigField 'String', 'HOME', 'TEST_HOME'
}


jar {
    buildConfigField "String", "MY_CLOUD_API", '"http://12.3.456.789:123"'
    manifest {
        attributes 'Implementation-Title': 'Gradle Quickstart',
                   'Implementation-Version': version
    }
}

repositories {
    jcenter()
    mavenCentral()
}

sourceSets {
    main {
        java {
            srcDirs 'src'
        }
        resources {
            srcDirs 'src/resources'
        }
    }
}

dependencies {
    compile 'com.amazon.alexa:alexa-skills-kit:1.5.0'
    compile 'com.amazonaws:aws-lambda-java-core:1.0.0'
    compile 'com.amazonaws:aws-java-sdk-dynamodb:1.9.40'
    compile 'com.amazonaws:aws-lambda-java-log4j:1.0.0'

    compile 'log4j:log4j:1.2.17'
    compile 'org.apache.commons:commons-lang3:3.3.2'
    compile 'org.apache.directory.studio:org.apache.commons.io:2.4'
    compile 'org.eclipse.jetty:jetty-server:9.0.6.v20130930'
    compile 'org.eclipse.jetty:jetty-servlet:9.0.6.v20130930'
    compile 'org.slf4j:slf4j-api:1.7.10'
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
}

task fatJar(type: Jar) {
    baseName = project.name + '-fat'
    from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
    with jar
}

build.dependsOn fatJar
buildscript {
    ext.kotlin_version = '1.2.21'
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}
compileKotlin {
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

1 个答案:

答案 0 :(得分:1)

buildConfigField android插件中定义为gradle 不能在另一个范围内使用它。