DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Implementing a Serverless DevOps Pipeline With AWS Lambda and CodePipeline
  • File Upload Security and Malware Protection
  • Top 10 Pillars of Zero Trust Networks
  • Getting Started With the YugabyteDB Managed REST API

Trending

  • Implementing a Serverless DevOps Pipeline With AWS Lambda and CodePipeline
  • File Upload Security and Malware Protection
  • Top 10 Pillars of Zero Trust Networks
  • Getting Started With the YugabyteDB Managed REST API
  1. DZone
  2. Coding
  3. Java
  4. Gradle: Modernization of Build Process

Gradle: Modernization of Build Process

Want to learn more about building a project using the Gradle build plugin? Check out this tutorial to learn how!

Aayushi Garg user avatar by
Aayushi Garg
·
Updated Mar. 16, 20 · Tutorial
Like (8)
Save
Tweet
Share
16.91K Views

Join the DZone community and get the full member experience.

Join For Free

Many of you are stuck with the question of which build system is best for your project?

It depends on many factors, including the size of your project, your need for customization, dependency handling, external dependency, and a few other variables that can help you choose. Let’s take a look.

Gradle is a build automation system that is fully open source and uses concepts of other build tools, like Apache Maven and Apache Ant. It supports development and subsequent deployment using Java, Scala, and Groovy, with other project workflows and languages being introduced in the future. It is open source and provides an end-to-end process from development to deployment.

Why Choose Gradle Over Maven or Ant?

Shorter Scripts

Gradle does not use XML and tends to become unmanageably big when used with all but very small projects. Instead, it had its own DSL based on Groovy (one of JVM languages). As a result, Gradle build scripts tend to be much shorter and clearer than those written for Ant or Maven.

Out-of-Box Features

Gradle has a lot of tasks already available out-of-the-box or through plugins that are open source. For example, this simple line of code adds 20+ tasks waiting for us to use.

apply plugin: 'java'


Flexibility

Maven provides a very rigid model that makes customization tedious and sometimes impossible. While this can make it easier to understand any given Maven build, as long as you don’t have any special requirements, it also makes it unsuitable for many automation problems. Customization of targets (goals) is hard in Maven. Gradle, on the other hand, is built with an empowered and responsible user in mind.

Faster

The top three features that make Gradle much faster than Maven or Ant are:

  • Incrementality — Gradle avoids work by tracking the input and output of tasks and only running what is necessary and only processing files that changed when possible.
  • Build Cache — Reuses the build outputs of any other Gradle build with the same inputs, including between machines.
  • Gradle Daemon — A long-lived process that keeps the build information "hot" in memory.

Developer Friendly

It brings the convenience of a Groovy-based DSL along with the advantages of Ant and Maven. With Gradle, you can easily manipulate the build process and its logic to create multiple versions of your app. It’s much easier to use and a lot more concise and flexible, when compared to Ant or Maven alone.

How to Build Your First Gradle Java Project?

1. Run the Init Task

Gradle comes with a built-in plugin called Build Init Plugin. This plugin runs many tasks internally to produce a built-in structure of your Java project. Now, run the command:

mkdir demo-gradle
cd demo-gradle
gradle init –type java-application


The init task runs the wrapper task first, which generates the gradlew and gradlew.bat wrapper scripts and creates a project with a basic structure. It generates  build.gradle,  settings.gradle,  folder for wrapper files, default java source folder, default java test folder.

build.gradle
 gradle
  wrapper
  gradle-wrapper.jar
  gradle-wrapper.properties
gradlew
gradlew.bat
settings.gradle
src
  main
   java
    App.java
test
 java
   AppTest.java


Now,  settings.gradle assigns the name of the root project to demo-gradle, which is the default.

rootProject.name = 'demo-gradle'


The build file adds the Java and application plugins. The generated  build.gradle file has many comments.

2. Generate Your own Build.Gradle File

Now, the build.gradle file can be composed based on projects requirement.

apply plugin: java
repositories {
jcenter() // or mavenCentral(), google()
}
sourceCompatibility = 1.8
targetCompatibility = 1.8
mainClassName = 'App'
dependencies {
compile 'com.google.guava:guava:21.0'
testCompile  'junit:junit:4.12'
}
jar{
from { configurations.compile.collect { it.isDirectory() ? it : zipTree(it) }}
manifest{
attributes 'Main-Class': ‘App’
}
}


In the repositories block, you add names of the repositories that Gradle should search for the libraries you use.

In sourceCompatibility and targetCompatibility, we define Java version compatibility.

Dependency Management in Gradle

In Gradle, dependencies are grouped into a named set of dependencies. These groups are called configurations, and we use them to declare the external dependencies of our project. The dependencies added to the compile configuration are required when our the source code of our project is compiled. The testCompile configuration contains the dependencies that are required to compile the tests of our project. This configuration contains the compiled classes of our project and the dependencies added to the compile configuration.

 configuration group-id:artifact-id:version 


3. Execute the Build

To build the project, run the build command.

gradle build


We can run the regular Gradle command, but when the project includes a Gradle script, then it is good form to use it instead.

The first time you run the build, Gradle will check whether or not you already have the Guava and JUnit libraries in your cache under your ~/.gradle directory. If not, the libraries will be downloaded and stored there. The next time you run the build, the cached versions will be used. The build task compiles the classes, runs the tests, and generates a test report.

4. Run the Application

gradle run


The run task tells Gradle to execute the main method in the class assigned to the mainClassName property.

5. Integration With S3 bucket Using Custom Tasks

Tasks are the cornerstone of getting things done in Gradle. To create a straightforward Gradle task, we need to add its definition to our build.gradlefile:

In the buildscript block, you define settings needed to perform your project building and created a task named  syncContents to sync the content with s3fs with help of plugin ' jp.classmethod.aws.s3.'

buildscript {
  repositories {
    maven {
      url "https://plugins.gradle.org/m2/"
    }
  }
  dependencies {
    classpath "jp.classmethod.aws:gradle-aws-plugin:0.+"
  }
}
import jp.classmethod.aws.gradle.s3.CreateBucketTask;
import jp.classmethod.aws.gradle.s3.SyncTask;
import com.amazonaws.services.s3.model.ObjectMetadata;
apply plugin: 'jp.classmethod.aws.s3'
aws {
  profileName = "test"
  region = 'ap-northeast-1'
}
// task to create the bucket.
task createBucket(type: CreateBucketTask) {
            bucketName "mybuc132"
            ifNotExists true
}
// task to sync the data.
task syncContents(type: SyncTask) {
            source file("build/libs") // must be directory
            bucketName "mybuc132"
            // to set all file's metadata "no-cache, no-store"
            metadataProvider { bucket, key, file ->
                        ObjectMetadata m = new ObjectMetadata()
                        m.setCacheControl("no-cache, no-store")
                        return m
            }
}


To run this particular task, we need to execute the following commands:

gradle createBucket
gradle syncContents


Now, you have a new project that you generated using Gradle’s build plugin. Enjoy!

Gradle Build (game engine) Apache Maven

Opinions expressed by DZone contributors are their own.

Trending

  • Implementing a Serverless DevOps Pipeline With AWS Lambda and CodePipeline
  • File Upload Security and Malware Protection
  • Top 10 Pillars of Zero Trust Networks
  • Getting Started With the YugabyteDB Managed REST API

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: