Personal wechat public number: Practice, welcome to pay attention to exchange.

Gradle plugins: Gradle plugins: Gradle plugins: Gradle plugins

  • First introduction to Gradle series
  • Gradle: Groovy Basics
  • Gradle series build script basics
  • Gradle series understanding Gradle tasks
  • Gradle plugin for Gradle series
  • Gradle series of Java Gradle plug-ins
  • Gradle series of Android Gradle plugin
  • Gradle series Android Gradle base configuration
  • Android Gradle advanced Configuration
  • The Gradle series builds Maven private server libraries from scratch

This article is mainly to learn the Java Gradle plug-in related knowledge, because Java Gradle plug-in related content is the basis of Android Gradle plug-in. Gradle builds projects using Gradle to help developers do repetitive tasks such as configuring third-party dependencies, compiling source files, unit testing, and packaging for distribution. Using Gradle plug-ins makes it easier to build projects and improve development efficiency. Here’s what WE learned today:

  1. The use of Java Gradle plug-ins
  2. The project structure of the Java plug-in convention
  3. Configuring third-party Dependencies
  4. How do I build a Java project
  5. SourceSet SourceSet concept
  6. Tasks that Java plug-ins can add
  7. Properties that Java plug-ins can add
  8. Multi-project construction
  9. Release the component

The use of Java Gradle plug-ins

To use a Gradle plugin, use the apply() method of Project:

Java is the plugin ID of the Java Gradle plugin
apply plugin:'java'
Copy the code

After using the Java plug-in, you will add default Settings and conventions for the current project, such as the location of the source code, the location of the unit test code, the location of the resource file, etc. The default Settings are generally used.

The project structure of the Java plug-in convention

The Java plugin sets some default Settings and conventions. Let’s take a look at the default project directory for a Java project. The directory structure is basically as follows:

JavaGradle └ ─ SRC ├ ─ the main │ ├ ─ Java │ └ ─ resources └ ─ test ├ ─ Java └ ─ resourcesCopy the code

SRC /main/ Java is the default directory for storing source code, SRC /main/resources is the directory for storing configuration files, etc. Arc /test is the directory for storing unit test files. Main and test are two sets of source code built into the Java Gradle plugin. You can also define other sets of source code as follows:

apply plugin : 'java'

sourceSets{
    // Specify a new collection of source code
    vip{
        
    }
}
Copy the code

Create a Java and Resources directory under SRC. The contents of these directories are similar to the default. The default directory structure is as follows:

// The source directory
src/vip/java
// Resource file directory
src/vip/resource
Copy the code

The directory structure is implemented by default in Java Gradle. You can also modify the location of the directory as follows:

sourceSets{
    // Change the default directory, the following is the same as the default directory, if you need to configure other directories to change
    main{
        java{
            srcDir 'src/java'
        }
        
        resources{
            srcDir 'src/resources'}}}Copy the code

Configuring third-party Dependencies

Gradle needs to specify the type and location of the jar dependencies that it depends on. For each dependency, Gradle needs to specify the type and location of the jar dependencies that it depends on.

// Configure the warehouse location
repositories{
    // Repository types include JCenter, Ivy, Maven central, Maven local, Maven private, etc
    mavenCentral()
    mavenLocal()
    maven {
        uri "http"//xxxx
    }
    jcenter()
    google()
    / /...
}

// Configure specific dependencies
dependencies{
    // Depend on three elements: group, name, version
    // Correspond to Maven GAV(groupid, artifactid, version)
    
    // Complete
    compile group: 'com.squareup.okhttp3', name: 'okhttp', version:'3.0.1'
    / / short
    compile 'com. Squareup. Okhttp3: okhttp: 3.0.1'
}
Copy the code

Compile is a compile-time dependency. Gradle provides other dependencies as well.

TestRuntime: depends only when test cases are run. Archives: Depends only when components such as JAR packages are releaseddefault: Default dependency configurationCopy the code

The Java Gradle plugin also supports different dependencies for different sets of source code. Compile and compile are different dependencies for different sets of source code. Compile and compile are different dependencies for different sets of source code. Specific reference is as follows:

// Configure different dependencies for different collections of source code
dependencies{
    // The configuration format is sourceSetCompile and sourceSetRuntime
    mainCompile 'com. Squareup. Okhttp3: okhttp: 3.0.1'
    vipCompile 'com. Squareup. Okhttp3: okhttp: 2.0.1'
}
Copy the code

The above introduction is an external library dependency, in addition to the development will also encounter Module dependency, file dependency, in fact, Module dependency is actually a subproject dependency, file is generally jar package dependency.

The Gradle file must include the subproject in the setting. Gradle file. This is also the case with setting. Gradle file. It then relies on a subproject as follows:

// Depends on a subproject
dependencies{
    //setting.gradle file include ':childProject'
    
    // Depend on subprojects
    compile project('childProject')
}
Copy the code

File dependency is mainly the dependency of JAR package, generally put jar package in the libs directory of the project, and then put jar package, specific reference is as follows:

// Rely on a jar package
dependencies{
    // Configure a single JAR
    compile file('libs/java1.jar')
    // Configure multiple jars
    compile files('libs/java1.jar'.'libs/java2.jar')
    // All files with the suffix JAR will be attached to the project
    compile fileTree(dir:'libs',include:'*.jar')
}
Copy the code

How do I build a Java project

All operations in Gradle are task-based. The Java Gradle plugin also has a set of built-in tasks to help you build your project. Run the Build task and Gradle starts building the current project. Gradle compiles source code files, processes resource files, generates JAR packages, compiles test code, runs unit tests, and more.

If there is a clean task in Android development, running clean removes the Build folder and other files generated by the build project. If the build fails, try clean and build. In addition, there are check tasks, which will be used in unit testing. Javadoc tasks can facilitate the generation of Doc API documents in Java format. The purpose of learning Java project construction is to learn Android project construction preparation. So much for how to build a Java project using Gradle.

SourceSet SourceSet concept

SourceSet is a collection of Java source code and resource files that the Java Gradle plugin uses to describe and manage source code and its resources. Therefore, the source code set can be used to configure the location of the source code file, set the properties of the source code set, etc. The source code set can be grouped for different businesses. For example, the Java Gradle plug-in provides the main and test source code directories by default, one for business code, the other for unit test, very convenient.

The Java Gradle plugin provides a sourceSet attribute and a sourceSet{} closure under Project to access and configure a sourceSet. SourceSet is a SourceSetContainer. The common properties of a sourceSet are as follows:

// For example, main, test, etc. represent the names of the source set
name(String)
// Represents the compiled class file directory of the source set
output.classDir(File)
// Indicates the directory of resource files generated after compilation
output.resourcesDir(File)
// Represents the classpath required by the compiled source set
compileClasspath(FileCollection)
// Represents the Java source file for the source set
java(SourceDirectorySet)
// Represents the directory where the Java source files for this source set are located
java.srcDirs(Set)
// Represents the resource file of the source set
resources(SourceDirectorySet)
// Indicates the directory where the resource files of the source set reside
resources.srcDirs(Set)
Copy the code

Set the output directory of the main source set as follows:

// Sets the properties of a source set
sourceSets{
    main{
        // The source set name is read-only
        println name
        // Set other properties
        // Obsolete as of 4.0. Instead, dir
        output.classesDir = file("a/b")
// output.dir("a/b")
        output.resourcesDir = file("a/b")
        //....}}Copy the code

Tasks that Java plug-ins can add

The project is built using a series of Gradle plugins. The following are common tasks in Java projects:

The name of the task type describe
Default source set common task
compileJava JavaCompile Indicates that Java source files are compiled using Javac
processResources Copy Indicates that the resource file is copied to the generated resource file directory
classes Task Represents a directory of class and resource files generated by assembly
compileTestJava JavaCompile Indicates that Java source files are compiled and tested using Javac
processTestResources Copy Indicates that the resource file is copied to the generated resource file directory
testClasses Task Represents test classes and associated resource files generated by assembly
jar Jar Represents the assembly jar file
javadoc Javadoc Indicates that Java API documentation is generated using Javadoc
uploadArchives Upload Represents uploading a build that contains the Jar, configured using the Archives {} closure
clean Delete Represents cleaning up the directory files generated by the build
cleanTaskName Delete Represents the deletion of files generated by the specified task, for example, cleanJar is the deletion of files generated by the JAR task
Customize source set tasks (SourceSet is the name of the specific SourceSet)
compileSourceSetJava JavaCompile Represents the source code for the specified source set compiled using Javac
processSouceSetResources Copy Indicates that the resource files of the specified source set are copied to the resource directory in the build file
sourcesSetClasses Task Represents a directory of classes and resource files that assemble a given source set

Properties that Java plug-ins can add

Common properties from Java Gradle plugins are added to Project and can be used directly as follows:

The attribute name type describe
sourceSets SourceSetContauner A set of sources for Java projects that can be configured within closures
sourceCompatibility JavaVersion The Version of Java used to compile Java source files
targetCompatinility JavaVersion Compile the Java version of the generated class
archivesBaseName String The name of the package as a JAR or zip file
manifest Manifest Used to access and configure the manifest file
libsDir File Store the generated class library directory
distsDir File The directory where the generated publications are stored

Multi-project construction

Setting. Gradle specifies whether or not to build these subprojects, and whether or not to use these subprojects must be configured in the main project dependencies. Library dependencies, project dependencies and file dependencies are used here. Subprojects and AllProjects are often used in multi-project configuration, as follows:

// Subproject unified configuration
subprojects{
    // Config subprojects all use the Java Gradle plugin
    apply plugin: 'java'
    // Configure subprojects using Maven central libraries
    repositories{
        mavenCentral()
    }
    // Other general configurations
    / /...
}
// All projects are unified
allprojects{
    // Configure all projects to use the Java Gradle plug-in
    apply plugin: 'java'
    // All projects are configured using Maven central libraries
    repositories{
        mavenCentral()
    }
    // Other general configurations
    / /...
}
Copy the code

Release the component

A Gradle build can be a JAR package, a zip package, etc. A build can be a jar package, a zip package, etc.

/** * Publish artifacts to project folder/or mavenLocal() */
apply plugin : 'java'
// Generate jar tasks, similar to custom wrapper
task publishJar(type:Jar)
// Build version
version '1.0.0'
Artifacts are configured via artifacts{} closures
artifacts{
    archives publishJar
}
// Upload the component
uploadArchives{
    repositories{
        flatDir{
            name 'libs'
            dirs "$projectDir/libs"
        }
        // Publish the build to mavenLocal()
        mavenLocal()
    }
}
Copy the code

The uploadArchives task will generate the corresponding JAR file in the corresponding location by executing the following command:

/ / uploadArchives execution
gradle uploadArchives
Copy the code

After successful execution, you should see the generated JAR file in the libs directory of your project, as shown below:

After successful execution, you will see the generated JAR file in the user’s.m2/repository directory, as shown below:

Here is how to publish the JAR to maven private server. The code is as follows:

/** * Publish components to Maven private server */
apply plugin : 'java'
apply plugin : 'maven'
// Generate jar tasks, similar to custom wrapper
task publishJar(type:Jar)
// Build version
version '1.0.0'
Artifacts are configured via artifacts{} closures
artifacts{
    archives publishJar
}
// Upload the component
uploadArchives{
    repositories{
        mavenDeployer{
            repository(url:'http://xxx') {// Warehouse user name and password
                authentication(userName:'username'.password:'pass')
            }
            snapshotRepository(url:'http://xxx'){
                authentication(userName:'username'.password:'pass')}}}}Copy the code

The upload process is also run to uploadArchives task, have maven private server can try, about Java Gradle plugin learning to stop, next enter Android Gradle plugin learning, can pay attention to the public number: Jzm-blog, communicate and learn together.