首页 > 解决方案 > 无法获取未知属性“localProperties”

问题描述

我想在build.gradle中读取local.properties中定义的属性(如此处所述所以在根build.gradle文件中我有以下内容:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

def localProperties = new Properties()
if (project.rootProject.file('local.properties').canRead()) {
    localProperties.load(project.rootProject.file("local.properties").newDataInputStream())
}

buildscript {

    ext {
        ...
    }

    repositories {
        google()
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
    dependencies {
        classpath "com.android.tools.build:gradle:$gradleVersion"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"


        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven {
            url "https://maven.google.com"
        }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

在模块的build.gradle文件中,我有以下内容:

android {
    ...
    defaultConfig {
        ...
        buildConfigField "String", "TOKEN", localProperties['token']
    }
}

但同步后出现以下错误:

无法获取 com.android.build.gradle.internal.dsl.DefaultConfig 类型的 DefaultConfig_Decorated{name=main, ...} 的未知属性“localProperties”。

我哪里错了?如何解决这个问题呢?

标签: androidgradle

解决方案


我遇到了一些问题。变量localProperties不是内置的,而是您自己定义的。您可以添加

Properties localProperties = new Properties()
    File file = project.rootProject.file('local.properties')
    if (file.exists()) {
        localProperties.load(file.newDataInputStream())
    }

给你在 defaultConfig 块中的 build.gradle。


推荐阅读