Initializing new Java projects with Gradle

I’ve used Maven for years for dependency management, but Gradle has better support for initializing a new Java source project compared to Maven. Although Maven has archetypes, I can never remember the syntax so usually just copy and paste a pom.xml file from somewhere else.

With Gralde you can ‘gradle init’ a new project and just follow the prompts:

> gradle init

Welcome to Gradle 8.1.1!

Here are the highlights of this release:
 - Stable configuration cache
 - Experimental Kotlin DSL assignment syntax
 - Building with Java 20

For more details see https://docs.gradle.org/8.1.1/release-notes.html

Starting a Gradle Daemon (subsequent builds will be faster)

Select type of project to generate:
  1: basic
  2: application
  3: library
  4: Gradle plugin
Enter selection (default: basic) [1..4] 2

Select implementation language:
  1: C++
  2: Groovy
  3: Java
  4: Kotlin
  5: Scala
  6: Swift
Enter selection (default: Java) [1..6] 3

Generate multiple subprojects for application? (default: no) [yes, no] n                          nolease enter 'yes' or 'no': 
Select build script DSL:
  1: Groovy
  2: Kotlin
Enter selection (default: Groovy) [1..2] 1

Select test framework:
  1: JUnit 4
  2: TestNG
  3: Spock
  4: JUnit Jupiter
Enter selection (default: JUnit Jupiter) [1..4] 1

Project name (default: java21playground): 
Source package (default: java21playground): 
Enter target version of Java (min. 7) (default: 21): 
Generate build using new APIs and behavior (some features may change in the next minor release)? (no


> Task :init
Get more help with your project: https://docs.gradle.org/8.1.1/samples/sample_building_java_applications.html

BUILD SUCCESSFUL in 1m 7s
2 actionable tasks: 2 executed

With Maven you add your dependencies to a <dependencies> block in your pom.xml, like

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.8.2</version>
        <scope>test</scope>
    </dependency>
</dependencies>

Dependencies with the default scope are considered part of your compile and runtime classpath, <scope>test</scope> indicates on the test classpath only.

With Gradle you do the same with your build.gradle properties file, in the dependencies section:

dependencies {
    testImplementation 'junit:junit:4.13.2'

    implementation 'com.google.guava:guava:31.1-jre'
}

implementation dependencies are for runtime, testimplementation are for test only.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.