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:

Gradle provides many commonly used plugins. Plugins in Gradle can help us improve development efficiency in certain scenarios. More functionality 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, methods, etc. 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 location of source code files under the src/main/java directory, so that only the Java source code files under the specified directory will be compiled.

How to apply a plugin#

Before using a plugin, you need to use the apply method of the Project to apply the plugin. 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, where 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
// Default import for org.gradle.api.plugins
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 when publishing the plugin. This plugin id must be unique, and 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 just need to load the script. The from keyword is used to load the script file, which can be a local file or a file from 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 "Version is ${versionName}, version code is ${versionCode}"
    }
}

The output of the above code is:

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

> Task :taskVersion
Version is 1.0, version code is 1


BUILD SUCCESSFUL in 2s
1 actionable task: 1 executed

As shown above, 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 dependencies in separate Gradle files, making it easier to manage and call these dependencies.

Usage of the apply method#

The Project.apply() method can accept three different types of parameters:

// 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 syntax for 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. Here is an example:

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. Here is an example of using the plugins DSL:

// 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'
}

This is the end of the plugin usage.

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 the necessary operations in this method. Here is an example of developing a simple plugin using Android Studio. The purpose of the plugin is to create a task. We will use Android Studio to create a Groovy project and develop the necessary 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. Here is the content of the file:

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"
            }
        }
    }
}

Next, 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. Here is the content of the file:

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

Here is the configuration of the build.gradle file:

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. Here is a screenshot of the directory structure of the custom plugin project:

image

Finally, to use the plugin in a project, copy the plugin to the libs folder of the project, specify the plugin's classpath, and use the apply method to apply the plugin. Here is an example:

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. This is the basic usage of plugins. 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.