How to Create Spring Boot Application Using Gradle

Creating a Spring Boot project using Gradle is also straightforward. Similar to Maven, you can use the Spring Initializr web tool to set it up, or you can manually create it. 

Using Spring Initializr Web Tool 

Go to Spring Initializr.

Choose the project settings: 

  • Project: Gradle Project 
  • Language: Java Spring Boot 
  • version: Latest stable (default) 
  • Project Metadata: Fill in Group, Artifact, etc. 
  • Dependencies: Choose your desired dependencies (e.g., Spring Web, Spring Data JPA, Thymeleaf, etc.) 

Click on "Generate" to download the zip file. Extract the zip file and open it in your favorite IDE. 

Manually Creating Project 

1. Create Project Structure: Create a new directory and inside it, create the following directories and files:

my-spring-boot-app/
├── src/
│   └── main/
│       └── java/
│           └── com/
│               └── example/
│                   └── MyApp.java
├── build.gradle

2. Edit build.gradle: Open build.gradle and add the following content:

plugins {
    id 'org.springframework.boot' version '3.1.3' // use the latest version
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.example'
version = '1.0-SNAPSHOT'
sourceCompatibility = '17'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
    useJUnitPlatform()
}

Make sure you use the latest Spring Boot version. 

3. Edit MyApp.java: Open src/main/java/com/example/MyApp.java and add the following content:

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}

4. Build and Run: Navigate to your project directory and run the following commands:

./gradlew clean build
./gradlew bootRun

If you're on Windows, you would use gradlew.bat instead of ./gradlew. Your Spring Boot application should now be running at http://localhost:8080/. Just as with Maven, you can add various other dependencies based on your project needs by adding them to your build.gradle.


Comments