Introduction to the

Build. gradle is an important file in Gradle because it describes the tasks that can be run in Gradle. In this article, we will take you through how to create a build.gradle file and how to write it.

Project and task

Gradle is a build tool. A build tool is a process of generating an object file by packaging the original code or file through certain tasks based on established rules.

So we have two very important concepts in Gradle: projects and tasks.

Each Gradle build task can contain one or more projects, which can be of various types, such as a Web project or a Java lib project. In order to achieve the goal of the project, tasks need to be defined to assist in the completion of the goal.

Tasks are used to perform specific tasks, such as compiling class files, packaging them into JARS, generating Javadoc, and so on.

A case in point

Let’s use a concrete example to show how gradle works.

First we create a new project directory:

$ mkdir gradle-test
$ cd gradle-test
Copy the code

Gradle provides an init method to easily create the skeleton of a Gradle project.

gradle init
Starting a Gradle Daemon (subsequent builds will be faster)

Select typeof project to generate: 1: basic 2: application 3: library 4: Gradle plugin Enter selection (default: basic) [1..4] 2 Select implementation language: 1: C++ 2: Groovy 3: Java 4: Kotlin 5: Scala 6: Swift Enter selection (default: Java) [1..6] 3 Split functionality across multiple subprojects? : 1: no - only one application project 2: yes - application and library projects Enter selection (default: no - only one application project) [1..2] 1 Select build script DSL: 1: Groovy 2: Kotlin Enter selection (default: Groovy) [1..2] 1 Selecttest framework:
  1: JUnit 4
  2: TestNG
  3: Spock
  4: JUnit Jupiter
Enter selection (default: JUnit 4) [1..4] 1

Project name (default: gradle-test):
Source package (default: gradle.test):

> Task :init
Get more helpWith your project: BUILD SUCCESSFUL at https://docs.gradle.org/6.7/samples/sample_building_java_applications.htmlin 45s
2 actionable tasks: 2 executed
Copy the code

After a series of choices, you can generate a basic Gradle project based on your needs.

Let’s take a look at the generated files and directories:

. ├ ─ ─ app │ ├ ─ ─ build. Gradle │ └ ─ ─ the SRC │ ├ ─ ─ the main │ │ ├ ─ ─ Java │ │ │ └ ─ ─ gradle │ │ │ └ ─ ─test│ ├ ─ ├ ─ ├ ─ ├ ─ │ ├ ─ ├ ─ ├ ─test│ ├─ ├─ │ ├─ ├─test│ │ └ ─ ─ AppTest. Java │ └ ─ ─ resources ├ ─ ─ gradle │ └ ─ ─ wrapper │ ├ ─ ─ gradle - wrapper. Jar │ └ ─ ─ gradle - wrapper. Properties └─ Gradlew └─ Gradlew. └─ Settings. Gradle directories, 8 filesCopy the code

Gradle-wrapper is a tool to automatically set up gradle and install gradle. Gradlew and gradlew. Bat are used to execute gradle tasks.

We’ll focus on two of these configuration files, settings.gradle and build.gradle.

Settings. gradle configures the gradle project to build:

rootProject.name = 'gradle-test'
include('app')
Copy the code

In the example above, rootproject.name specifies the name of the project, and include(‘app’) indicates the need to introduce a subproject called app that contains the actual content to be packaged.

Look again at the build.gradle file in your app:

plugins {
    // Apply the application plugin to add support for building a CLI application in Java.
    id 'application'
}

repositories {
    // Use JCenter for resolving dependencies.
    jcenter()
}

dependencies {
    // Use JUnit test framework.
    testImplementation 'junit: junit: 4.13'

    // This dependency is used by the application.
    implementation : 'com. Google. Guava guava: 29.0 jre'
}

application {
    // Define the main class for the application.
    mainClass = 'gradle.test.App'
}
Copy the code

It is simple, specifying the plug-in, repository address, dependency packages, and the main class path of the application.

With everything ready, we’re ready to build and run.

There are two ways to run this. One is to use the built-in Gradle command, and the other is to use the gradlew generated by gradle for you.

gradle run

> Configure project :app
Repository ${repo.url} replaced by $REPOSITORY_URL .

> Task :app:run
Hello World!
Copy the code
gradle build

> Configure project :app
Repository ${repo.url} replaced by $REPOSITORY_URL .

BUILD SUCCESSFUL in 2s
7 actionable tasks: 6 executed, 1 up-to-date
Copy the code

You can also upload builds to Gradle Scan with the –scan parameter for a more detailed build analysis:

./gradlew build --scan

BUILD SUCCESSFUL in 0s
7 actionable tasks: 7 executed

Publishing a build scan to scans.gradle.com requires accepting the Gradle Terms of Service defined at https://gradle.com/terms-of-service.
Do you accept these terms? [yes, no] yes

Gradle Terms of Service accepted.

Publishing build scan...
https://gradle.com/s/5u4w3gxeurtd2
Copy the code

Task 1

In the above example, we use gradle default tasks and do not see the use of custom tasks. Next, we will explore how to write your own tasks in build.gradle.

Here we use Groovy to write build.gradle, so we can run it as if it were code.

The task script

Start by creating a very simple task:

task hello {
    doLast {
        println 'Hello www.flydean.com! '}}Copy the code

This defines a task named Hello and prints “hello www.flydean.com!” at the end of execution. .

We run it like this:

gradle -q hello
Hello www.flydean.com!
Copy the code

-q means execute quietly, ignoring gradle’s own log information. Write the task name after Gradle.

If you are familiar with ant commands, gradle tasks are similar to Ant, but much more powerful.

Since it’s a Groovy script, we can execute code in it:

task upper {
    doLast {
        String someString = 'www.flydean.com'
        println "Original: $someString"
        println "Upper case: ${someString.toUpperCase()}"}}Copy the code

Running results:

> gradle -q upper
Original: www.flydean.com
Upper case: WWW.FLYDEAN.COM
Copy the code

Or execute The Times operation:

task count {
    doLast {
        4.times { print "$it "}}}Copy the code
> gradle -q count
0 1 2 3
Copy the code

Task dependent on

A Task in Gradle can depend on other tasks:

task hello {
    doLast {
        println 'Hello www.flydean.com! '
    }
}
task intro {
    dependsOn hello
    doLast {
        println "I'm flydean"}}Copy the code

The order of the two tasks above is independent. The dependent task can be written first, the dependent task next, or vice versa.

Dynamic task

In addition to static tasks, we can also create tasks dynamically using code:

4.times { counter ->
    task "task$counter" {
        doLast {
            println "I'm task number $counter"}}}Copy the code
> gradle -q task1
I'm task number 1
Copy the code

We can also think of a task as an object that calls Gradle’s API to operate on it:

4.times { counter ->
    task "task$counter" {
        doLast {
            println "I'm task number $counter"
        }
    }
}
task0.dependsOn task2, task3
Copy the code

In the example above, we call the API to manually create dependencies between tasks:

> gradle -q task0
I'm task number 2
I'm task number 3
I'm task number 0
Copy the code

You can also call properties between tasks:

task myTask {
    ext.myProperty = "www.flydean.com"
}

task printTaskProperties {
    doLast {
        println myTask.myProperty
    }
}
Copy the code

The default task

If you don’t want to manually specify a task name every time you call gradle, you can use defaultTasks:

defaultTasks 'clean'.'run'

task clean {
    doLast {
        println 'Default Cleaning! '
    }
}

task run {
    doLast {
        println 'Default Running! '
    }
}

task other {
    doLast {
        println "I'm not a default task!"}}Copy the code

The above code executes Gradle and gradle Clean Run equivalently.

External dependencies on build scripts

Since build scripts can be written in Groovy code, what if we want to use external JAR packages in our build scripts?

At this point, we can put the external dependencies in the buildScript () method, and later tasks can use the imported dependencies:

import org.apache.commons.codec.binary.Base64

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath group: 'commons-codec', name: 'commons-codec', version: '1.2'
    }
}

task encode {
    doLast {
        def byte[] encodedString = new Base64().encode('hello world\n'.getBytes())
        println new String(encodedString)}}Copy the code

In the example above, Encode uses an external dependency package, Base64, that was introduced in the BuildScript method.

This article is available at www.flydean.com/gradle-buil…

The most popular interpretation, the most profound dry goods, the most concise tutorial, many tips you didn’t know waiting for you to discover!

Welcome to pay attention to my public number: “procedures those things”, understand technology, more understand you!