设置属性从build.gradle中的local.properties读取

时间:2017-05-09 17:58:01

标签: gradle build.gradle

我使用的是等级v3.4。我已将以下属性移动到名为local.properties的文件(与build.gradle相同的目录):

local.properties

nexusUsername=someuser
nexusPassword=somepassword

的build.gradle

File secretPropsFile = file('./local.properties')
if (secretPropsFile.exists()) {
    Properties p = new Properties()
    p.load(new FileInputStream(secretPropsFile))
    p.each { name, value ->
       project.set name, value
    }
} else {
    throw new IllegalStateException("secret.properties could not be located for build process")
}

我收到以下异常:

Could not find method set() for arguments [nexusUsername, someuser] on root project 'some-java-project of type org.gradle.api.Project.

1 个答案:

答案 0 :(得分:2)

您获得的错误是正确的。要设置属性,您需要使用ext。请查看docs

所以下面的代码将完成这项工作:

File secretPropsFile = file('./local.properties')
if (secretPropsFile.exists()) {
    Properties p = new Properties()
    p.load(new FileInputStream(secretPropsFile))
    p.each { name, value ->
        ext[name] = value
    }
} else {
    throw new IllegalStateException("secret.properties could not be located for build process")
}

println project.nexusPassword
println project.nexusUsername //property is set in project's scope via ext