banner
jzman

jzman

Coding、思考、自觉。
github

Gradle Plugin in the Gradle Series

In the previous few articles, we learned the basic knowledge of Gradle build tasks and understood the concepts of Project and Task. It is recommended to read the previous articles first:

Gradle provides many commonly used plugins, and these plugins can help us improve development efficiency in certain scenarios. More functionalities can be achieved by extending existing plugins. For example, the Android Gradle plugin is based on the built-in Java plugin.

  1. Purpose of plugins
  2. How to apply a plugin
  3. Custom plugins

Purpose of plugins#

Let's first understand the purpose of Gradle plugins, which mainly include the following aspects:

  1. Adding tasks to the project, which can be used for testing, compiling, and packaging the project.
  2. Adding dependencies to the project, which can be used to configure the dependencies required during the project build process.
  3. Adding new extension properties and methods to existing object types in the project, which can facilitate project configuration and build optimization. For example, the android{} block in Android project build is an extension added by the Android Gradle plugin to the Project object.
  4. Defining conventions for the project. For example, using the Java Gradle plugin can define the storage location of source code files under the src/main/java directory, so that the Java source code files under the specified directory can be compiled.

How to apply a plugin#

Before using a plugin, you need to apply the plugin using the apply method of the Project object. Plugins can be divided into binary plugins and script plugins.

Using binary plugins#

Binary plugins are plugins that implement the org.gradle.api.Plugin interface. Each Java Gradle plugin has a plugin id, and you can use the following syntax to apply a Java plugin:

apply plugin: 'java'

The above code applies the Java plugin to our project. In this case, java is the plugin id of the Java plugin. Each core plugin provided by Gradle has a unique plugin id. The specific type corresponding to java is org.gradle.api.plugins.JavaPlugin. Therefore, you can also use the following syntax to apply the Java plugin:

apply.plugin:org.gradle.api.plugins.JavaPlugin
// Import org.gradle.api.plugins by default
apply.plugin:JavaPlugin

Binary plugins are generally packaged in a Jar file. When customizing a plugin, you need to specify the plugin's plugin id during the release. This plugin id must be unique. You can use the package name to ensure the uniqueness of the plugin id.

Using script plugins#

Using script plugins is actually using a script file. When using a script plugin, you need to load the script. The from keyword is used to specify the script file, which can be a local file or a script file on the internet. Here is an example of defining a script and using it in the build.gradle file:

// version.gradle file
ext {
    versionName = "1.0"
    versionCode = 1
}

The following code uses this script file in the build file:

// build.gradle file
apply from: 'version.gradle'

task taskVersion {
    doLast {
        println "The version is ${versionName}, and the version code is ${versionCode}"
    }
}

The output of the above code is:

PS E:\Gradle\study\GradlePlugin> gradle taskVersion

> Task :taskVersion
The version is 1.0, and the version code is 1


BUILD SUCCESSFUL in 2s
1 actionable task: 1 executed

As you can see, the plugin script is applied using apply from. Using script plugins allows you to organize the scripts used in the build into separate files, making it easier to manage and call different scripts. For example, you can define utility methods and version numbers used by various dependencies in separate Gradle files for unified calling and management.

Usage of the apply method#

The Project.apply() method can accept three different parameters, as follows:

// Closure as a parameter
void apply(Closure closure);
// Configure an ObjectConfigurationAction
void apply(Action<? super ObjectConfigurationAction> action);
// Map as a parameter
void apply(Map<String, ?> options);

You can use the above three methods to configure a plugin. The usage of the three methods is as follows:

// Map as a parameter
apply plugin: 'java'
// Closure as a parameter
apply {
    plugin 'java'
}
// Configure an ObjectConfigurationAction
apply(new Action<ObjectConfigurationAction>() {

    @Override
    void execute(ObjectConfigurationAction objectConfigurationAction) {
        objectConfigurationAction.plugin('java')
    }
})

Using third-party plugins#

Most of the time, you need third-party plugins to build your project. To use them, you need to configure the classpath in the buildscript{} block. For example, when using the Android Gradle plugin, you need to configure the corresponding classpath in the build.gradle file, as shown below:

buildscript {
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}

The buildscript{} block is mainly used to configure the dependencies required for project build before the project is built. After configuring these dependencies, you can use the plugin as follows:

// You must configure the corresponding classpath in buildscript{} before using it
apply plugin: 'com.android.application'

Applying plugins using the plugins DSL#

The plugins DSL is a new way to apply plugins and can only be used in Gradle 2.1 and above. The usage is as follows:

// Using the plugins DSL
plugins {
    id 'java'
}
// If the third-party plugin is hosted on https://plugins.gradle.org/, you don't need to configure the classpath in buildscript{}
plugins {
    id "plugin id" version 'plugin version'
}

The above is the usage of plugins.

Custom plugins#

Most of the time, you need to customize plugins to perform certain project build operations. Custom plugins must implement the Plugin interface, and the apply method in the interface will be executed when the plugin is applied. You can implement this method to perform relevant operations. Let's use Android Studio to develop a simple plugin, which creates a task. We will create a Groovy project in Android Studio and develop the corresponding code.

In Android Studio, create a module, delete all files except src/main and build.gradle, and then create a .groovy file to implement the Plugin interface. The file content is as follows:

package com.manu.plugin

import org.gradle.api.Plugin
import org.gradle.api.Project

/**
 * Custom plugin
 */
class MPlugin implements Plugin<Project> {

    @Override
    void apply(Project target) {
        target.task('taskPlugin') {
            doLast {
                println "Custom plugin creates a task"
            }
        }
    }
}

Then, specify the plugin's plugin id. Create the resources/META-INF/gradle-plugins directory under src/main, and create a properties file with the plugin id. The file content is as follows:

// Specify the implementation class of the plugin
implementation-class=com.manu.plugin.MPlugin

The build.gradle file should be configured as follows:

apply plugin: 'groovy'

dependencies {
    // Gradle SDK
    compile gradleApi()
    // Groovy SDK
    compile localGroovy()
}

Now, a simple plugin is defined. To use it conveniently, generate a JAR file for this plugin project. Then, you can use it in other projects. Copy the plugin to a project, such as the libs folder of the project, specify the classpath of the plugin in the buildscript{}, and use the apply method to apply the plugin:

apply plugin: 'com.manu.plugin'

buildscript {
    dependencies {
        classpath files('libs/plugin.jar')
    }
}

The output of the above code is:

PS E:\Gradle\study\GradlePlugin> gradle taskPlugin

> Task :taskPlugin
Custom plugin creates a task


BUILD SUCCESSFUL in 2s
1 actionable task: 1 executed

Because the plugin creates a task named taskPlugin, you can use this task. The basic usage of plugins has been described above. Next, we will continue to learn about the usage of Java Gradle plugins.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.