This section focuses on writing a Gradle (https://gradle.org/) build script that builds a single Gradle project referred to as computation. The project with the below gradle structure is available for you to download and import in your IDE.
-
Go to this link and download the computation.zip. Once it is downloaded, extract the project from zip.
-
Open your IDE and import the extracted project(from step 1) as Existing Gradle Project.
-
After improting the project, check that your imorted project has the required structure as shown below:
computation ├── build.gradle └── src ├── main │ └── java │ ├── application │ │ └── CompApp.java │ ├── computation │ │ └── Computation.java │ └── view │ └── ComputationPage.java └── test └── java └── computation ├── AllTests.java ├── ComputationTestAddSubstract.java └── ComputationTestDivideMultiply.java
-
Open the build.gradle file and check for the relevant parts as discussed in the steps (5 to 9) below.
-
java
and theapplication
plugins are added in the build configuration script build.gradle.apply plugin: 'java' // This plugin has a predefined 'run' task that we can reuse to use Gradle to execute our application apply plugin: 'application'
-
JUnit libraries are added in the
dependencies
section.repositories { mavenCentral() } dependencies { testImplementation "junit:junit:4.12" }
-
A task
compile(type: JavaCompile)
has been added to specify all source files (both application and test) and set the build/bin as destination dir to put all compiled class files in.task compile(type: JavaCompile) { classpath = sourceSets.main.compileClasspath classpath += sourceSets.test.runtimeClasspath sourceSets.test.java.outputDir = file('build/bin') sourceSets.main.java.outputDir = file('build/bin') }
NoteOne can specify source sets and their variables the following way: /* * specifying sourceSets is not necessary in this case, since * we are applying the default folder structure assumed by Gradle */ sourceSets { main { java { srcDir 'src/main/java' } } test { java { srcDir 'src/test/java'} } }
-
The main class has been specified as shown below. Now, you can proceed and run the application.
mainClassName='application.CompApp'
In the command line issue
gradle run
-
The
jar
Gradle task (defined by thejava
plugin) has been added to produce an executable jar file intodistributable/
.jar { destinationDir=file('distributable') manifest { // It is smart to reuse the name of the main class variable instead of hardcoding it attributes "Main-Class": "$mainClassName" } }
Note
|
The settings.gradle and its usage is to be shown later.
|