[go: up one dir, main page]

0% found this document useful (0 votes)
34 views10 pages

Gradle

Uploaded by

rohithcmsedge
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views10 pages

Gradle

Uploaded by

rohithcmsedge
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Gradle: Gradle is an opensource build and automation tool to our Java-based projects.

Using
Gradle, we can reduce Project Development time and increase Productivity.
Gradle is a multi-language, multi-platform, multi-project and multi-channel build and automation
software
Gradle is an open source, advanced general purpose build management system. It is built on ANT,
Maven, and lvy repositories. It supports Groovy based Domain Specific Language (DSL) over XML.

Advantages of Gradle
Gradle will provide the following advantages compare to Ant and Maven. That’s why all new projects are using
Gradle as Build tool.

 Like Maven, Gradle is also an expressive, declarative, and maintainable build Tool.
 Like Maven, Gradle also supports Dependency Management
 It provides very scalable and high-performance builds.
 It provides Standardized project layout and life-cycle, but full flexibility and the option to fully configure the
defaults.
 It is very easy-to-use Gradle tool and very flexible to implement our own Project required custom logics.
 It supports for project structures that consist of more than one project to build deliverable.
 It is very easy to integrate existing Ant/Maven with Gradle
 It is very easy to migrate from existing Ant/Maven to Gradle

Download Gradle:
This section describes the detailed steps to install the Gradle build tool in your machine:

Download the latest version 3.5

Copy downloaded file and extract it into your local directory.

Add Gradle in to environment variables as mentioned in the below screenshot.

Open your command line and type gradle -version to get version of Gradle that is installed on your
system.

Build Script: Gradle builds a script file for handling two things; one is projects and another one
is tasks. Every Gradle build represents one or more projects. A project represents a library JAR or a
web application or it might represent a ZIP that assembled from the JARs produced by other projects.
In simple words, a project is made up of different tasks.

A task means a piece of work which a build performs. A task might be compiling some classes,
creating a JAR, generating Javadoc, or publishing some archives to a repository. Gradle uses Groovy
language for writing scripts.

So, how are these concepts related to a Gradle build? Well, every Gradle build contains one or more
projects.
The relationships between these concepts are illustrated in the following figure:
We can configure our Gradle build by using the following configuration files:

 The Gradle build script (build.gradle) specifies a project and its tasks.

 The Gradle properties file (gradle.properties): It is used to configure the properties of the build.

 The Gradle Settings file (gradle.settings): It is optional in a build which has only one project. If our
Gradle build has more than one projects, it is mandatory because it describes which projects
participate to our build. Every multi-project build must have a settings file in the root project of the
project hierarchy.

Build phases:
A Gradle build has three distinct phases.

Initialization

Gradle supports single and multi-project builds. During the


initialization phase, Gradle determines which projects are going to
take part in the build, and creates a Project instance for each of these
projects.
Configuration

During this phase the project objects are configured. The build scripts
of all projects which are part of the build are executed. Gradle 1.4
introduced an incubating opt-in feature called configuration on
demand. In this mode, Gradle configures only relevant projects
(see the section called “Configuration on demand”).
Execution

Gradle determines the subset of the tasks, created and configured


during the configuration phase, to be executed. The subset is
determined by the task name arguments passed to
the gradle command and the current directory. Gradle then executes
each of the selected tasks.
Task creation
You can receive a notification immediately after a task is added to a project.
This can be used to set some default values or add behaviour before the
task is made available in the build file.

task hello {
doLast {
println 'tutorialspoint'
}
}

Execute the following command in the command prompt. It executes the above script. You should
execute this, where the build.gradle file is stored.

C:\> gradle –q hello

If the command is executed successfully,

Dependency Configurations: Dependency configuration is nothing but defines a set of


dependencies.

You can use this feature to declare external dependencies, which you want to download from the web.

This defines the following different standard configurations.

Compile − The dependencies required to compile the production source of the project.

Runtime − The dependencies required by the production classes at runtime. By default, also includes the

compile time dependencies.

Test Compile − The dependencies required to compile the test source of the project. By default, it includes

compiled production classes and the compile time dependencies.

Test Runtime − The dependencies required to run the tests. By default, it includes runtime and test

compile dependencies.
Declaring Your Dependencies

apply plugin: ‘java’


dependencies {
compile group: 'org.hibernate', name: 'hibernate-core', version: '3.6.7.Final'

testCompile group: 'junit', name: 'junit', version: '4.+'


}

Repositories
While adding external dependencies. Gradle looks for them in a repository. A repository is just a
collection of files, organized by group, name and version. By default, Gradle does not define any
repositories. We have to define at least one repository explicitly. The following code snippet defines
how to define maven repository. Use this code in build.gradle file.

repositories {
mavenCentral()
}

Java Default Project Layout


Whenever you add a plugin to your build, it assume a certain setup of Java project (similar to Maven).
Take a look at the following directory structure.

 src/main/java contains the Java source code


 src/test/java contains the Java tests
If you follow this setup, the following build file is sufficient to compile, test, and bundle a Java project.

Build a JAVA Project


First, we have to add Java plugin to the build script because it provides tasks to compile Java source
code, run unit tests, create Javadoc and create a JAR file. Use the following line in build.gradle file.

apply plugin: 'java'


The Project Layout of a Java Project
The default project layout of a Java project is following:

 The src/main/java directory contains the source code of our project.


 The src/main/resources directory contains the resources (such as properties files) of our project.
 The src/test/java directory contains the test classes.
 The src/test/resources directory contains the test resources.

All output files of our build are created under the build directory. This directory contains the following subdirectories which
are relevant to this blog post (there are other subdirectories too, but we will talk about them in the future):

 The classes directory contains the compiled .class files.


 The libs directory contains the jar or war files created by the build.

apply plugin: 'java'


sourceSets {
main {
java {
srcDir 'src'
}
}

test {
java {
srcDir 'test'
}
}

Adding a Main Class to Our Build


Let’s create a simple main class which prints the words: “HomeController”

The source code of the HomeController class looks as follows:


package com.cmsedge.firstgradle;

import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

public class HomeController {


public static void main(String args[])
{

System.out.println("hello world jar");


}
The HelloWorld class was added to the src/main/java directory

The Tasks of a Java Project


The Java plugin adds many tasks to our build but the tasks which are relevant for this blog post
are:
 The assemble task compiles the source code of our application and packages it to a jar file. This task
doesn’t run the unit tests.
 The build task performs a full build of the project.
 The clean task deletes the build directory.
 The compileJava task compiles the source code of our application.
We can also get the full list of runnable tasks and their description by running the following command at
the command prompt:

gradle tasks

This is a good way to get a brief overview of our project without reading the build script. If we run this
command in the root directory of our example project, we see the following output:

E:\ravi workspace\firstgradle>gradle tasks

:tasks

------------------------------------------------------------

All tasks runnable from root project

------------------------------------------------------------

Build tasks

-----------

:tasks

------------------------------------------------------------
All tasks runnable from root project

------------------------------------------------------------

Build tasks

-----------

assemble - Assembles the outputs of this project.

build - Assembles and tests this project.

buildDependents - Assembles and tests this project and all projects that depend on it.

buildNeeded - Assembles and tests this project and all projects it depends on.

classes - Assembles classes 'main'.

clean - Deletes the build directory.

jar - Assembles a jar archive containing the main classes.

testClasses - Assembles classes 'test'.

Build Setup tasks

-----------------

init - Initializes a new Gradle build. [incubating]

wrapper - Generates Gradle wrapper files. [incubating]

Documentation tasks

-------------------

javadoc - Generates Javadoc API documentation for the main source code.

Help tasks

----------

dependencies - Displays all dependencies declared in root project 'first-java-project'.

dependencyInsight - Displays the insight into a specific dependency in root project 'first
java-project'.

help - Displays a help message

projects - Displays the sub-projects of root project 'first-java-project'.

properties - Displays the properties of root project 'first-java-project'.


tasks - Displays the tasks runnable from root project 'first-java-project'.

Verification tasks

------------------

check - Runs all checks.

test - Runs the unit tests.

Rules

-----

Pattern: build<ConfigurationName>: Assembles the artifacts of a configuration.

Pattern: upload<ConfigurationName>: Assembles and uploads the artifacts belonging to a


configuration.

Pattern: clean<TaskName>: Cleans the output files of a task.

To see all tasks and more detail, run with --all.

BUILD SUCCESSFUL

Total time: 2.792 secs

Let’s move on and find out how we can package our Java project.

We can package our application by using two different tasks:

If the run the command gradle assemble at command prompt, we see the following output:

E:\ravi workspace\firstgradle>gradle assemble

:compileJava

:processResources

:classes

:jar

:assemble
BUILD SUCCESSFUL

Total time: 3.163 secs

If we run the command gradle build at command prompt, we see the following output:

E:\Ravi Workspace\firstgradle>gradle build

:compileJava UP-TO-DATE

:processResources NO-SOURCE

:classes UP-TO-DATE

:jar UP-TO-DATE

:assemble UP-TO-DATE

:compileTestJava UP-TO-DATE

:processTestResources NO-SOURCE

:testClasses UP-TO-DATE

:test UP-TO-DATE

:check UP-TO-DATE

:build UP-TO-DATE

BUILD SUCCESSFUL

Total time: 1.686 secs

The outputs of these commands demonstrate that the difference of these tasks is that:

 The assemble task runs only the tasks which are required to package our application.
 The build task runs the tasks which are required to package our application AND runs automated
tests.
Both of these commands create the first-java-project.jar file to the build/libs directory.
The default name of the created jar file is created by using the following template: [project name].jar, and
the default name of the project is the same than the name of the directory in which it is created. Because
the name of our project directory is firstgradle project, the name of created jar is firstgradle.jar.

We can now try to run our application by using the following command:

Java -cp "E:\Ravi Workspace\firstgradle\build\libs\firstgradle.jar"


com.cmsedge.firstgradle.HomeController
//java -jar firstgradle.jar

When we do this, we see the following output:

No main manifest attribute, in firsgradle.jar or

Error: Could not find or load main class com.cmsedge.firstgradle.Home

The problem is that we haven’t configured the main class of the jar file in the manifest file. Let’s find out
how we can fix this problem.

Configuring the Main Class of a Jar File


The Java plugin adds a jar task to our project, and every jar object has a manifest property which is an
instance of Manifest.
We can configure the main class of the created jar file by using the attributes() method of
the Manifest interface. In other words, we can specify the attributes added to the manifest file by using a
map which contains key-value pairs.
We can set the entry point of our application by setting the value of the Main-Class attribute. After we
have made the required changes to the build.gradle file, its source code looks as follows (the relevant part
is highlighted):

apply plugin:’java’
jar
{
manifest
{
attributes 'Main-Class':
'com.cmsedge.firstgradle.HomeController'
}

After we have created a new jar file by running either the gradle jar or gradle build command, we can run
the jar file by using the following command

java -cp "E:\Ravi Workspace\firstgradle\build\libs\firstgradle.jar" com.cmsedge.firstgradle.HomeController

Output: Hello World

You might also like