Learn the rudimentary mechanism and usage of Gradle 4.4

Overview

This article is a compilation of what Gradle inexperienced people have learned about how Gradle works and how to use it.

environment

reference

Installation

The installation was done manually without using the package manager. Download the archive file from the Install page and extract it to a suitable location. Add the bin in the extracted directory to the environment variable path.

** Version check **

> gradle -v

------------------------------------------------------------
Gradle 4.4
------------------------------------------------------------

Build time:   2017-12-06 09:05:06 UTC
Revision:     cf7821a6f79f8e2a598df21780e3ff7ce8db2b82

Groovy:       2.4.12
Ant:          Apache Ant(TM) version 1.9.9 compiled on February 2 2017
JVM:          1.8.0_144 (Oracle Corporation 25.144-b01)
OS:           Windows 10 10.0 amd64

Usage

gradle [option...] [task...]

How to read build.gradle

From SPRING INITIALIZR that generates a template for an application that uses Spring Boot, generate a template for a web application that uses Gradle for build, and build. I read gradle.

Also, for reference, I generated a template using Maven under the same conditions, and posted its pom.xml below.

Maven

pom.xml


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>

	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>

	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.9.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

Gradle

build.gradle


// 1
buildscript {
	ext {
		springBootVersion = '1.5.9.RELEASE'
	}
	repositories {
		mavenCentral()
	}
	dependencies {
		classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
	}
}

// 2
apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

// 3
group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

// 4
repositories {
	mavenCentral()
}

// 5
dependencies {
	compile('org.springframework.boot:spring-boot-starter-thymeleaf')
	compile('org.springframework.boot:spring-boot-starter-web')
	runtime('org.springframework.boot:spring-boot-devtools')
	compileOnly('org.projectlombok:lombok')
	testCompile('org.springframework.boot:spring-boot-starter-test')
}

1. Settings required to execute the script

pom.xml is a configuration file for maven build, but gradle build.gradle is a build script file written in a programming language called Groovy.

In this part called buildscript, I added the spring-boot-gradle-plugin required when executing the script file to the dependency, which makes the org.springframework.boot plugin available.

Also, such {...} is called a script block, and there are other repositories and dependencies.

buildscript {
	// A
	ext {
		springBootVersion = '1.5.9.RELEASE'
	}
	// B
	repositories {
		mavenCentral()
	}
	// C
	dependencies {
		classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
	}
}

A

ext is a script block called extra properties. Define the property here.

B

I'm setting up a repository to get spring-boot-gradle-plugin. This example uses maven's central repository.

C

We are adding the dependencies needed to run this script file. The description in this part means to add the dependency spring-boot-gradle-plugin to the classpath when executing the script.

43.6. External dependencies for the build script

If your build script needs to use external libraries, you can add them to the script’s classpath in the build script itself.

2. Applying the plugin

Applying a plug-in allows you to perform the tasks it provides.

// A
apply plugin: 'java'
// B
apply plugin: 'eclipse'
// C
apply plugin: 'org.springframework.boot'

A

[java plugin] Applying (https://docs.gradle.org/4.4/userguide/java_plugin.html) will allow you to perform tasks such as compiling java source code and running unit tests.

B

I'm applying the eclipse plugin. Running the eclipse task of this plugin will generate an eclipse project file. This plugin is a standard Gradle plugin.

> gradle eclipse

If you want to clear the project files, run the cleanEclipse task.

> gradle cleanEclipse

C

I'm applying the spring boot plugin. You can run the application developed with spring boot by running the bootRun task of this plugin.

> gradle bootRun

It also adds a task called bootRepackage that depends on the assemble task.

> gradle help --task bootRepackage

> Task :help
Detailed task information for bootRepackage

Path
     :bootRepackage

Type
     RepackageTask (org.springframework.boot.gradle.repackage.RepackageTask)

Description
     Repackage existing JAR and WAR archives so that they can be executed from the command line using 'java -jar'

Group
     build

Check available tasks

You can see what tasks you can perform in your project with the tasks task.

> gradle tasks

Supported programming languages

In addition to Java, Gradle also supports Groovy, scala, etc. (Not only this)

Groovy

apply plugin: 'groovy'

Scala

apply plugin: 'scala'

3. Setting properties referenced when running the script

group and version are properties related to the project, and sourceCompatibility are properties used by the java plugin.

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

The type of property referenced by the project is Project in the DSL reference, and the type of property used by the java plugin. Can be found in the User Guide Chapter 48. The Java Plugin.

You can see what properties your project has in the propertyis task.

> gradle properties

Define your own properties

Your own properties are defined in a script block called ext.

Example


ext {
  limitDate = '2017-12-01'
}

4. Repository settings

In repositories, set the repository to resolve build dependencies and upload artifacts. In this example, the source of the library set as the dependency is the central repository of maven.

repositories {
	mavenCentral()
}

When using a local maven repository

mavenLocal()

When using the JCenter repository

jcenter()

5. Add external dependencies

Add the library settings that the project build depends on. compile, runtime, etc. are called dependency configuration. For example, compile sets the libraries required when compiling the source code.

dependencies {
	compile('org.springframework.boot:spring-boot-starter-thymeleaf')
	compile('org.springframework.boot:spring-boot-starter-web')
	runtime('org.springframework.boot:spring-boot-devtools')
	compileOnly('org.projectlombok:lombok')
	testCompile('org.springframework.boot:spring-boot-starter-test')
}

The above is a shortened description method (group: name: version), and the dependency can also be described as follows. The version attribute can be omitted depending on the repository to be used.

dependencies {
	compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf'
	compile group: 'org.springframework.boot', name: 'spring-boot-starter-web'
	runtime group: 'org.springframework.boot', name: 'spring-boot-devtools'
	compileOnly group: 'org.projectlombok', name: 'lombok'
	testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test'
}

To specify an arbitrary version, specify it with the version attribute as shown below.

compileOnly group: 'org.projectlombok', name: 'lombok', version: '1.16.18'

You can check the project dependencies in the dependencies task.

> gradle dependencies

You can also output only specific dependencies by specifying the optional --configuration.

> gradle dependencies --configuration compileOnly

> Task :dependencies

------------------------------------------------------------
Root project
------------------------------------------------------------

compileOnly - Compile only dependencies for source set 'main'.
\--- org.projectlombok:lombok: -> 1.16.18

BUILD SUCCESSFUL in 1s
1 actionable task: 1 executed

Optional dependencies

Spring Boot reference [B.3 Generating your own meta-data using the annotation processor](https://docs.spring.io/spring-boot/docs/1.5.9.RELEASE/reference/htmlsingle/#configuration- It is described in metadata-annotation-processor).

In the dependency setting in maven, you can specify optional as follows.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

To do the same thing with Gradle, you need to use propdeps-plugin and make the following settings.

buildscript {
	repositories {
		maven { url 'http://repo.spring.io/plugins-release' }
	}
	dependencies {
		classpath('io.spring.gradle:propdeps-plugin:0.0.9.RELEASE')
	}
}
apply plugin: 'propdeps'

dependencies {
    optional("org.springframework.boot:spring-boot-configuration-processor")
}

compileJava.dependsOn(processResources)

Executing a task

The tasks that are added by Java plug-in and are frequently used are as follows.

Run the build task to build the project.

> gradle clean build

Check task dependencies

The execution of a task may depend on other tasks. Below is a tree view of the build task dependencies. (I used a plugin called com.dorongold.task-tree to display the tree.)

From this tree you can see that the build task depends on the assemble and check tasks.

> gradle build taskTree --no-repeat

> Task :taskTree

------------------------------------------------------------
Root project
------------------------------------------------------------

:build
+--- :assemble
|    +--- :bootRepackage
|    |    +--- :findMainClass
|    |    |    \--- :classes
|    |    |         +--- :compileJava
|    |    |         \--- :processResources
|    |    \--- :jar
|    |         \--- :classes *
|    \--- :jar *
\--- :check
     \--- :test
          +--- :classes *
          \--- :testClasses
               +--- :compileTestJava
               |    \--- :classes *
               \--- :processTestResources


(*) - subtree omitted (printed previously)

Task definition

You can define and run your own tasks in build.gradle. Below is a basic sample of task definitions.

task myTask {
    description = 'My Task description'
    group = 'My Tasks'

    doLast {
        println "running ${name}"
    }
}

Logging

Log level

  1. ERROR
  2. QUIET
  3. WARNING
  4. LIFECYCLE
  5. INFO
  6. DEBUG

Log output

Use logger to output the log.

task logOutput {

	doLast {
		logger.error('error log message')
		logger.quiet('quiet log message')
		logger.warn('warning log message')
		logger.lifecycle('lifecycle log message')
		logger.info('info log message')
		logger.debug('debug log message')
		logger.trace('trace log message')
		println('log message via println')
	}

}

You can select the output log level as a command line option. If not specified, the default is LIFECYCLE. Note that the default log level for println is set to QUIET.

> gradle logOutput

> Task :logOutput
error log message
quiet log message
warning log message
lifecycle log message
log message via println

BUILD SUCCESSFUL in 1s
1 actionable task: 1 executed

The options that can be specified are

To change the log level of println, add the following settings.

logging.captureStandardOutput LogLevel.INFO

Supplement

Other tasks

buildEnvironment

Displays information about the build environment of the project.

> gradle buildEnvironment

components

Displays detailed information about the component.

> gradle components

dependencies

Shows a tree view of project dependencies.

> gradle dependencies

dependencyInsight

> gradle dependencyInsight --dependency org.springframework:spring-webmvc

> Task :dependencyInsight
org.springframework:spring-webmvc:4.3.13.RELEASE (selected by rule)
\--- org.springframework.boot:spring-boot-starter-web:1.5.9.RELEASE
     +--- compileClasspath
     \--- org.springframework.boot:spring-boot-starter-thymeleaf:1.5.9.RELEASE
          \--- compileClasspath

(*) - dependencies omitted (listed previously)


BUILD SUCCESSFUL in 1s
1 actionable task: 1 executed

projects

> gradle projects

properties

> gradle properties

tasks

> gradle tasks
> gradle tasks --all

help

> gradle help --task <task name>

Build Init Plugin

currently incubating

Chapter 17. Build Init Plugin

Usage

No explicit application of the plugin is required.

The Build Init plugin is an automatically applied plugin, which means you do not need to apply it explicitly.

Tasks

init task

Create a template for your project. JUnit is selected as the testing framework.

> gradle init --type java-library

You can choose TestNG or spock instead of JUnit.

> gradle init --type java-library --test-framework testng
> gradle init --type java-library --test-framework spock

Wrapper Plugin

currently incubating

Chapter 23. Wrapper Plugin

Tasks

wrapper

Generate the execution environment of Gradle.

> gradle wrapper
> gradle wrapper --gradle-version=4.4
> gradle wrapper --distribution-type=ALL --gradle-version=4.4

Project Report Plugin

Chapter 29. The Project Report Plugin

Usage

apply plugin: 'project-report'

Tasks

dependencyReport

> gradle dependencyReport
> gradle dependencyReport --configuration default

htmlDependencyReport

> gradle htmlDependencyReport

propertyReport

> gradle propertyReport

taskReport

> gradle taskReport
> gradle taskReport --all

projectReport

> gradle projectReport

Build Dashboard Plugin

currently incubating

Chapter 30. The Build Dashboard Plugin

Usage

apply plugin: 'build-dashboard'

Tasks

buildDashboard

> gradle buildDashboard

3rd party Plugin

Third-party plugins can be found at Gradle --Plugins.

Spring Boot Gradle plugin

Usage

apply plugin: 'org.springframework.boot'

Tasks

Flyway Gradle plugin

Usage

plugins {
    id "org.flywaydb.flyway" version "5.0.3"
}

Tasks

Recommended Posts

Learn the rudimentary mechanism and usage of Gradle 4.4
About the mechanism of the Web and HTTP
Background and mechanism of Fabric-loader
This and that of the JDK
[Rails] Differences and usage of each_with_index and each.with_index
[Challenge CircleCI from 0] Learn the basics of CircleCI
Examine the memory usage of Java elements
About the operation of next () and nextLine ()
[Ruby] Classification and usage of loops in Ruby
Introduction and usage explanation of Font Awesome
Reference information for investigating and analyzing the memory usage status of Tomcat
[Rails] We have summarized the storage locations and usage of developer and user images.
Check the version of the JDK installed and the version of the JDK enabled
Think about the combination of Servlet and Ajax
Compare the speed of the for statement and the extended for statement.
[Java] The confusing part of String and StringBuilder
Introduction and basic usage of Simple Calendar gem
I compared the characteristics of Java and .NET
About next () and nextLine () of the Scanner class
What are the advantages of DI and Thymeleaf?
ArrayList and the role of the interface seen from List
Please note the division (division) of java kotlin Int and Int
[For beginners] DI ~ The basics of DI and DI in Spring ~
The comparison of enums is ==, and equals is good [Java]
[Grails] About the setting area and the setting items of application.yml
Convert the array of errors.full_messages to characters and output
Organizing the current state of Java and considering the future
Java language from the perspective of Kotlin and C #
[CentOS] Download and build the specified version of Git
Arbitrate the fight between PowerMock and jacoco with Gradle
Until the use of Spring Data and JPA Part 2
Learn for the first time java # 3 expressions and operators
Verification of the relationship between Docker images and containers
Until the use of Spring Data and JPA Part 1
I summarized the types and basics of Java exceptions
[Technical memo] About the advantages and disadvantages of Ruby
[Ruby] Class nesting, inheritance, and the basics of self
Automatically set the width and height of the UI Label