---
title: "Gradle task 接收参数"
author: "qingfeng825"
date: "2020-06-09T09:55:41Z"
tags: []
categories: ["开源软件"]
slug: "gradle-task"
draft: false
lastmod: "2020-06-09T14:32:54Z"
id: 2514623
url: "https://qingfeng825.iteye.com/blog/2514623"
---

//1. 执行gradle task 时传递参数

./gradlew test -Pkey=value

 

//2. gradle get 属性  
def KEY\_FROM\_PROPERTY = (project.hasProperty("key") &&  project.getProperty("key")!="unspecified") ? project.getProperty("key") : ""  
println KEY\_FROM\_PROPERTY  
//3. gradle  get 环境变量  
def KEY\_FROM\_ENV = System.getenv("key")  
println KEY\_FROM\_ENV

 

//4. 在gradle脚本可以拿到key 的值，但是在test task 执行的时候拿不到key值

原因： The -P flag is for gradle properties, and the -D flag is for JVM properties. Because the test may be forked in a new JVM, the -D argument passed to gradle will not be propagated to the test - it sounds like that is the behavior you are seeing.

解决方案： 取出-p 定义的属性，在test task 中再定义一个系统属性,

    test {  
    systemProperty "key", project.getProperty("key")  
}

或者你用-D 时，用下面的语句

   test {  
        systemProperty "key", System.getProperty("key")  
    }