0
0
SpringbootHow-ToBeginner · 4 min read

How to Run a Spring Boot Application: Simple Steps

To run a Spring Boot application, use the command ./mvnw spring-boot:run if you use Maven, or ./gradlew bootRun for Gradle. Alternatively, build a jar file with mvn package or gradle build and run it using java -jar target/app.jar.
📐

Syntax

Spring Boot applications can be run using build tool commands or by running the packaged jar file.

  • Maven: ./mvnw spring-boot:run runs the app directly.
  • Gradle: ./gradlew bootRun runs the app directly.
  • Run packaged jar: Build with ./mvnw package or ./gradlew build, then run java -jar target/app.jar.
bash
./mvnw spring-boot:run

./gradlew bootRun

java -jar target/app.jar
💻

Example

This example shows a simple Spring Boot application with a main class. You can run it using Maven or Gradle commands.

java
package com.example.demo;

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

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
Output
2024-06-01 10:00:00.000 INFO 12345 --- [ main] com.example.demo.DemoApplication : Started DemoApplication in 2.345 seconds (JVM running for 2.789)
⚠️

Common Pitfalls

Common mistakes when running Spring Boot apps include:

  • Not using the wrapper scripts (./mvnw or ./gradlew) which ensure correct tool versions.
  • Running java -jar on an unbuilt or missing jar file.
  • Not having the @SpringBootApplication annotation on the main class.
  • Port conflicts if another app uses the default port 8080.
bash
/* Wrong: Running java -jar without building jar */
java -jar target/demo.jar

/* Right: Build first then run */
./mvnw package
java -jar target/demo.jar
📊

Quick Reference

CommandDescription
./mvnw spring-boot:runRun Spring Boot app using Maven wrapper
./gradlew bootRunRun Spring Boot app using Gradle wrapper
./mvnw packageBuild jar file with Maven
./gradlew buildBuild jar file with Gradle
java -jar target/app.jarRun the built jar file

Key Takeaways

Use the Maven or Gradle wrapper commands to run Spring Boot apps easily.
Build your project before running the jar with java -jar.
Ensure your main class has @SpringBootApplication annotation.
Check for port conflicts if the app does not start.
Use the quick reference commands to run or build your app efficiently.