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:runruns the app directly. - Gradle:
./gradlew bootRunruns the app directly. - Run packaged jar: Build with
./mvnw packageor./gradlew build, then runjava -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 (
./mvnwor./gradlew) which ensure correct tool versions. - Running
java -jaron an unbuilt or missing jar file. - Not having the
@SpringBootApplicationannotation 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
| Command | Description |
|---|---|
| ./mvnw spring-boot:run | Run Spring Boot app using Maven wrapper |
| ./gradlew bootRun | Run Spring Boot app using Gradle wrapper |
| ./mvnw package | Build jar file with Maven |
| ./gradlew build | Build jar file with Gradle |
| java -jar target/app.jar | Run 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.