Pengenalan Gradle

Artikel ini adalah sebahagian daripada siri: • Pengenalan kepada Gradle (artikel semasa) • Semut vs Maven vs Gradle

• Menulis Plugin Gradle Khusus

• Membuat Jar Lemak di Gradle

1. Gambaran keseluruhan

Gradle adalah sistem pengurusan binaan berasaskan Groovy yang direka khusus untuk membina projek berasaskan Java.

Arahan pemasangan boleh didapati di sini.

2. Blok Bangunan - Projek dan Tugas

Di Gradle, Build terdiri daripada satu atau lebih projek dan setiap projek terdiri daripada satu atau lebih tugas.

Projek di Gradle boleh memasang balang , perang atau bahkan fail zip .

Tugas adalah satu karya. Ini termasuk menyusun kelas, atau membuat dan menerbitkan arkib Java / web.

Tugas mudah boleh didefinisikan sebagai:

task hello { doLast { println 'Baeldung' } }

Sekiranya kita menjalankan tugas di atas menggunakan perintah gradle -q hello dari lokasi yang sama di mana build.gradle berada, kita akan melihat output di konsol.

2.1. Tugas

Skrip binaan Gradle tidak lain adalah Groovy:

task toLower { doLast { String someString = 'HELLO FROM BAELDUNG' println "Original: "+ someString println "Lower case: " + someString.toLowerCase() } }

Kita dapat menentukan tugas yang bergantung pada tugas lain. Pergantungan tugas dapat didefinisikan dengan melewati argumen dependOn: taskName dalam definisi tugas:

task helloGradle { doLast { println 'Hello Gradle!' } } task fromBaeldung(dependsOn: helloGradle) { doLast { println "I'm from Baeldung" } }

2.2. Menambah Tingkah Laku untuk Tugas

Kami dapat menentukan tugas dan meningkatkannya dengan beberapa tingkah laku tambahan:

task helloBaeldung { doLast { println 'I will be executed second' } } helloBaeldung.doFirst { println 'I will be executed first' } helloBaeldung.doLast { println 'I will be executed third' } helloBaeldung { doLast { println 'I will be executed fourth' } }

doFirst dan doLast menambah tindakan di bahagian atas dan bawah senarai tindakan, masing-masing, dan dapat ditentukan beberapa kali dalam satu tugas .

2.3. Menambah Sifat Tugas

Kami juga dapat menentukan sifat:

task ourTask { ext.theProperty = "theValue" } 

Di sini, kami tetapan berada "theValue" sebagai theProperty daripada ourTask tugas.

3. Menguruskan Pemalam

Terdapat dua jenis pemalam dalam Gradle - skrip, dan binari.

Untuk memanfaatkan fungsi tambahan, setiap plugin perlu melalui dua fasa: menyelesaikan dan menggunakan.

Menyelesaikan cara mencari versi yang betul jar plugin dan menambah kepada classpath projek.

Menggunakan plugin melaksanakan Plugin.apply (T) pada projek tersebut .

3.1. Memohon Plugin Skrip

Dalam aplugin.gradle, kita dapat menentukan tugas:

task fromPlugin { doLast { println "I'm from plugin" } }

Sekiranya kita mahu menerapkan plugin ini ke fail build.gradle projek kita, yang perlu kita buat hanyalah menambahkan baris ini ke build.gradle kita :

apply from: 'aplugin.gradle' 

Sekarang, melaksanakan tugas tugas gradle harus memaparkan tugas fromPlugin dalam senarai tugas.

3.2. Memohon Plugin Binari Menggunakan Plugin DSL

Sekiranya menambah pemalam binari teras, kita boleh menambah nama pendek atau id pemalam:

plugins { id 'application' }

Sekarang jangka tugas dari permohonan plugin perlu disediakan dalam projek untuk melaksanakan apa-apa runnable jar. Untuk menggunakan pemalam komuniti, kita harus menyebutkan id pemalam yang berkelayakan sepenuhnya:

plugins { id "org.shipkit.bintray" version "0.9.116" }

Sekarang, tugas Shipkit harus tersedia dalam senarai tugas gradle .

Batasan pemalam DSL adalah:

  • It doesn't support Groovy code inside the plugins block
  • plugins block needs to be the top level statement in project's build scripts (only buildscripts{} block is allowed before it)
  • Plugins DSL cannot be written in scripts plugin, settings.gradle file or in init scripts

Plugins DSL is still incubating. The DSL and other configuration may change in the later Gradle versions.

3.3. Legacy Procedure for Applying Plugins

We can also apply plugins using the “apply plugin”:

apply plugin: 'war'

If we need to add a community plugin, we have to add the external jar to the build classpath using buildscript{} block.

Then, we can apply the plugin in the build scripts butonly after any existing plugins{} block:

buildscript { repositories { maven { url "//plugins.gradle.org/m2/" } } dependencies { classpath "org.shipkit:shipkit:0.9.117" } } apply plugin: "org.shipkit.bintray-release"

4. Dependency Management

Gradle supports very flexible dependency management system, it's compatible with the wide variety of available approaches.

Best practices for dependency management in Gradle are versioning, dynamic versioning, resolving version conflicts and managing transitive dependencies.

4.1. Dependency Configuration

Dependencies are grouped into different configurations. A configuration has a name and they can extend each other.

If we apply the Java plugin, we'll have compile, testCompile, runtime configurations available for grouping our dependencies. The default configuration extends “runtime”.

4.2. Declaring Dependencies

Let's look at an example of adding some dependencies (Spring and Hibernate) using several different ways:

dependencies { compile group: 'org.springframework', name: 'spring-core', version: '4.3.5.RELEASE' compile 'org.springframework:spring-core:4.3.5.RELEASE', 'org.springframework:spring-aop:4.3.5.RELEASE' compile( [group: 'org.springframework', name: 'spring-core', version: '4.3.5.RELEASE'], [group: 'org.springframework', name: 'spring-aop', version: '4.3.5.RELEASE'] ) testCompile('org.hibernate:hibernate-core:5.2.12.Final') { transitive = true } runtime(group: 'org.hibernate', name: 'hibernate-core', version: '5.2.12.Final') { transitive = false } }

We're declaring dependencies in various configurations: compile, testCompile, and runtime in various formats.

Sometimes we need dependencies that have multiple artifacts. In such cases, we can add an artifact-only notations @extensionName (or ext in the expanded form) to download the desired artifact:

runtime "org.codehaus.groovy:groovy-all:[email protected]" runtime group: 'org.codehaus.groovy', name: 'groovy-all', version: '2.4.11', ext: 'jar'

Here, we added the @jar notation to download only the jar artifact without the dependencies.

To add dependencies to any local files, we can use something like this:

compile files('libs/joda-time-2.2.jar', 'libs/junit-4.12.jar') compile fileTree(dir: 'libs', include: '*.jar')

When we want to avoid transitive dependencies,we can do it on configuration level or on dependency level:

configurations { testCompile.exclude module: 'junit' } testCompile("org.springframework.batch:spring-batch-test:3.0.7.RELEASE"){ exclude module: 'junit' }

5. Multi-Project Builds

5.1. Build Lifecycle

In the initialization phase, Gradle determines which projects are going to take part in a multi-project build.

This is usually mentioned in settings.gradle file, which is located in the project root. Gradle also creates instances of the participating projects.

In the configuration phase, all created projects instances are configured based on Gradle feature configuration on demand.

In this feature, only required projects are configured for a specific task execution. This way, configuration time is highly reduced for a large multi-project build. This feature is still incubating.

Finally, in the execution phase, a subset of tasks, created and configured are executed. We can include code in the settings.gradle and build.gradle files to perceive these three phases.

In settings.gradle :

println 'At initialization phase.'

In build.gradle :

println 'At configuration phase.' task configured { println 'Also at the configuration phase.' } task execFirstTest { doLast { println 'During the execution phase.' } } task execSecondTest { doFirst { println 'At first during the execution phase.' } doLast { println 'At last during the execution phase.' } println 'At configuration phase.' }

5.2. Creating Multi-Project Build

We can execute the gradle init command in the root folder to create a skeleton for both settings.gradle and build.gradle file.

All common configuration will be kept in the root build script:

allprojects { repositories { mavenCentral() } } subprojects { version = '1.0' }

The setting file needs to include root project name and subproject name:

rootProject.name = 'multi-project-builds' include 'greeting-library','greeter'

Now we need to have a couple of subproject folders named greeting-library and greeter to have a demo of a multi-project build. Each subproject needs to have an individual build script to configure their individual dependencies and other necessary configurations.

If we'd like to have our greeter project dependent on the greeting-library, we need to include the dependency in the build script of greeter:

dependencies { compile project(':greeting-library') }

6. Using Gradle Wrapper

If a Gradle project has gradlew file for Linux and gradlew.bat file for Windows, we don't need to install Gradle to build the project.

If we execute gradlew build in Windows and ./gradlew build in Linux, a Gradle distribution specified in gradlew file will be downloaded automatically.

If we'd like to add the Gradle wrapper to our project:

gradle wrapper --gradle-version 4.2.1

The command needs to be executed from the root of the project. This will create all necessary files and folders to tie Gradle wrapper to the project. The other way to do the same is to add the wrapper task to the build script:

task wrapper(type: Wrapper) { gradleVersion = '4.2.1' }

Sekarang kita perlu melaksanakan tugas pembungkus dan tugas itu akan mengaitkan projek kita dengan pembungkus. Selain fail gradlew , folder pembungkus dihasilkan di dalam folder gradle yang mengandungi balang dan fail sifat.

Sekiranya kita ingin beralih ke Gradle versi baru, kita hanya perlu menukar entri dalam gradle- wrapper.properties .

7. Kesimpulannya

Dalam artikel ini, kami melihat Gradle dan melihat bahawa ia mempunyai fleksibiliti yang lebih besar daripada alat binaan lain yang ada dalam hal menyelesaikan konflik versi dan menguruskan pergantungan transitif.

Kod sumber untuk artikel ini terdapat di GitHub.

Seterusnya » Semut vs Maven vs Gradle