1. 程式人生 > >基於groovy語言的DSL程式設計基礎(專案構建)

基於groovy語言的DSL程式設計基礎(專案構建)

Gradle是一種基於依賴的程式語言,你可以在已有的task中自定義task或者依賴規則。對比我們最常用的語言,比如java、Object-C,Gradle就像同時包含了配置虛擬機器、位元組碼解釋規則、code語法。Gradle會讓這些task按照順序執行,且只執行一次。有些build tools工具會在任何一個task執行前構建完成一個基於依賴的task佇列,便於完成它指定的編譯任務,比如com.android.tools.build。

一次Gradle構建包含三個階段:Initialization(初始化)、Configuration(配置)、Execution(執行)

1)Initialization

Gradle支援同時至少一個專案的構建,在Initialization階段,Gradle決定哪個專案可以參與構建(build),併為它們分別建立一個Project例項。

2)Configuration

參與構建的所有專案的build script會被執行(從Gradle 1.4開始,有關聯的專案才會被配置)

3)Execution

Gradle劃分完成在配置階段被建立的即將執行的task,通過gradle命令引數和當前目錄確定這些task是否應該得到執行。

Setting檔案

Gradle確定一個預設名為setting.gradle的setting檔案,這個檔案會在Initialization階段執行。同時構建多個專案時,必須在所有專案的頂層目錄中放置一個setting.gradle檔案,這個檔案用來確定哪個專案參與接下來的構建過程。如果只有個專案,可以沒有setting.gradle檔案。

單專案構建舉例:

settings.gradle

println 'This is executed during the initialization phase.'
build.gradle
println 'This is executed during the configuration phase.'

task configured {
    println 'This is also executed during the configuration phase.'
}

task test << {
    println 'This is executed during the execution phase.'
}

task testBoth {
    doFirst {
      println 'This is executed first during the execution phase.'
    }
    doLast {
      println 'This is executed last during the execution phase.'
    }
    println 'This is executed during the configuration phase as well.'
}

執行命令:gradle test testBoth
> gradle test testBoth
This is executed during the initialization phase.
This is executed during the configuration phase.
This is also executed during the configuration phase.
This is executed during the configuration phase as well.
:test
This is executed during the execution phase.
:testBoth
This is executed first during the execution phase.
This is executed last during the execution phase.

BUILD SUCCESSFUL

Total time: 1 secs

附註:在一段Gradle指令碼中,可以通過一個project物件實現對屬性的訪問和方法的呼叫。同樣的,在setting檔案中,可以通過setting(比如Setting類物件)物件實現對屬性的訪問和方法的呼叫。