Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Get started with Gradle Java build


May 25, 2021 Gradle


Table of contents


Get started with Java build

Java plug-in

As you can see, Gradle is a universal tool. I t can be scripted to build anything you want to implement and really implement out-of-the-box. But only if you need to write good code in the script.

Most Java projects have similar basic processes: compile source files, do unit tests, and create jar packages. Y ou don't have to write code for every project to do this with Gradle. G radle already offers the perfect plug-in to solve these problems. P lug-ins are extensions of Gradle, in short, to add some very useful default configurations for you. G radle brings a lot of plug-ins, and you can easily write and share your own plug-ins. Java plugin is one of them, providing you with features such as compilation, testing, packaging, and more.

The Java plug-in defines many default values for the project, such as the Java source file location. I f you follow these default rules, you don't need to write too much code in your script file. Of course, Gradle also allows you to customize some of the rules in your project, and in fact, since the java project is built on plug-ins, you can also build without the plug-in writing your own code.

Later chapters show you a number of in-depth examples of how to use Java plug-ins to manage and multi-project builds, and so on. But in this section we need to understand the basic usage of Java plug-ins first.

A basic Java project

Take a look at this small example below, and to use the Java plug-in, just add the following code to your script.

With the Java plug-in

build.gradle
apply plugin: 'java'

Note: Sample code can be found under samples/java/quickstart in the Gralde distribution package.

That's all you need to do to define a Java project. This will add the Java plug-in and some of its built-in tasks for you.

What tasks have been added?

You can run the gradle tasks to list the tasks. This allows you to see what tasks the Java plug-in has added for you.

The standard directory structure is as follows:

project  
    +build  
    +src/main/java  
    +src/main/resources  
    +src/test/java  
    +src/test/resources  

By default, Gradle searches for packaged source code from src/main/java and test source code under src/test/java A nd src/main/resources are packaged, and all files under src/test/resources are added to the class path to perform tests. All files are output under build, and packaged files are output under build/libs.

Build the project

The Java plug-in adds a number of tasks for you. B ut they only work when you need to build a project. T he most common is the build task, which builds the entire project. When you perform the gradle build, Gralde compiles and performs unit tests and packages the following class and resource files for src/main/*

Build a Java project

Run the output of the gradle build

Output of gradle build
> gradle build
:compileJava
:processResources
:classes
:jar
:assemble
:compileTestJava
:processTestResources
:testClasses
:test
:check
:build
BUILD SUCCESSFUL
Total time: 1 secs

Some of the other more commonly used tasks are as follows:

clean

Delete the build directory and all the files that were built.

assemble

The jar file is compiled and packaged, but unit tests are not performed. S ome other plug-ins may enhance the functionality of this task. For example, if you use a War plug-in, this task will give your project a War package.

check

Compile and test the code. S ome other plug-ins may also enhance the functionality of this task. For example, if you use the Code-quality plug-in, this task performs checkstyle extra.

External dependencies

Typically, a Java project has many external dependencies. Y ou need to tell Gradle how to find and reference these external files. I n Gradle, Jar packages are usually present in the warehouse. W arehouses can be used to search for dependent or published project products. The following is an example of a Maven warehouse.

Add a Maven warehouse

build.gradle
repositories {
    mavenCentral()
}

Add dependencies. Here is a declaration of the commons-collections required for the compilation period and the junit for the test period.

Add dependencies

build.gradle
dependencies {
    compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
    testCompile group: 'junit', name: 'junit', version: '4.+'
}

Learn more about Dependency Management Foundation

Custom items

The Java plug-in adds many default configurations to your project. T hese defaults are usually sufficient for a normal project. B ut if you don't think it's appropriate to modify it, it's easy. Looking at the following example, we specify the version number for the Java project and the version of the JDK used, and add some properties to mainfest.

Custom MANIFEST. Mf

build.gradle
sourceCompatibility = 1.5
version = '1.0'
jar {
    manifest {
        attributes 'Implementation-Title': 'Gradle Quickstart', 'Implementation-Version': version
    }
}

What are the available properties?

You can perform gradle properties to get a list of properties for the project. Use this command to see the properties added by the plug-in and the default values.

Java plug-ins add common tasks as if they were written in a Build file. T his means that the mechanisms shown in the previous sections can be used to modify the behavior of these tasks. F or example, you can set the properties of a task, add task behavior, change task dependencies, or even override overrides the entire task. I n the following example, we'll modify the test task, which is a Test-type task. Let's add some system properties to it as it executes.

Add system properties to the test

build.gradle
test {
    systemProperties 'property': 'value'
}

Publish the jar package

How do I publish a jar package? Y ou need to tell Gradle where to publish. I n Gradle, jar packages are typically published to a warehouse. I n the following example, we'll publish the jar package to the local directory. Of course, you can also publish to remote warehouses or multiple remote warehouses.

Publish the jar package

build.gradle
uploadArchives {
    repositories {
       flatDir {
           dirs 'repos'
       }
    }
}

Execute the gradle uploadArchives to publish the jar package.

Create an Eclipse file

To import a project into Eclipse, you need to add another plug-in to your script file.

Eclipse plugin

build.gradle
apply plugin: 'eclipse'

Perform a gradle eclipse to generate an Eclipse project file.

A summary of the sample

This is a complete script from the sample code summary:

Java Example - A complete build script

build.gradle
apply plugin: 'java'
apply plugin: 'eclipse'
sourceCompatibility = 1.5
version = '1.0'
jar {
    manifest {
        attributes 'Implementation-Title': 'Gradle Quickstart', 'Implementation-Version': version
    }
}
repositories {
    mavenCentral()
}
dependencies {
    compile group: 'commons-collections', name: 'commons-collections', version: '3.2'
    testCompile group: 'junit', name: 'junit', version: '4.+'
}
test {
    systemProperties 'property': 'value'
}
uploadArchives {
    repositories {
       flatDir {
           dirs 'repos'
       }
    }
}

Multi-project build

Now let's look at an example of a typical multi-project build. The project structure is as follows:

Multi-project build-project structure

Build layout
multiproject/
  api/
  services/webservice/
  shared/

备注: 本示例代码可在 Gradle 发行包的 samples/java/multiproject 位置找到

There are three projects here. T he api project is used to generate a jar file for clients that provides Java clients for XML webservice. W ebservice is a web app that generates XML. The shared project contains code common to the two projects mentioned above.

Multi-project build definitions

Defining a multi-project build requires creating a setting profile at the root (in this case, the multiproject level) to indicate which projects the build contains. And this file must be called settings.gradle This example has the following profile:

Settings.gradle in multi-project builds

settings.gradle
include "shared", "api", "services:webservice", "services:shared"

Public configuration

There are always some common configurations for multi - project construction. I n this case, we define some common configurations on the root project in the form of configuration injection. T he root project is like a container, and the sub-project iterates through its configuration and injects it into its own configuration. This allows us to simply define the master configuration order for all projects:

Multi-project build - public configuration

build.gradle
subprojects {
    apply plugin: 'java'
    apply plugin: 'eclipse-wtp'
    repositories {
       mavenCentral()
    }
    dependencies {
        testCompile 'junit:junit:4.11'
    }
    version = '1.0'
    jar {
        manifest.attributes provider: 'gradle'
    }
}

It's worth noting that we've applied Java plug-ins to every sub-project. T his means that what we learned in the previous sections is also available in sub-projects. So you can compile, test, package, and so on at the root project directory.

Engineering dependency

Engineering dependencies can be established in the same build, and jar packages for one project can be made available to another project. F or example, we can have api engineering to rely on the jar package of shared engineering. This way, Gradle always builds the shared project before building the api.

Multi-project build-engineering dependency

api/build.gradle
dependencies {
    compile project(':shared')
}

Package the publication

For how to publish, see below:

Multi-project build-release

api/build.gradle
task dist(type: Zip) {
    dependsOn spiJar
    from 'src/dist'
    into('libs') {
        from spiJar.archivePath
        from configurations.runtime
    }
}
artifacts {
   archives dist
}

What's next?

In this chapter, we learned how to build a basic Java project. B ut that's a small part of the ground, and there's a lot more you can do with Gradle. Learn more about the Java plug-in, The Java Plugin, and you can find more examples in the samples/java directory in the Gradle distribution package.

Also, don't forget to continue reading Dependency Management Basics