Sub topic 3
Running a Spring Boot Application
Assume you know basic Java, Maven, HTTP, and how to use a terminal. A generated Spring Boot project includes a Maven wrapper, which lets you run Maven without installing a matching Maven version.
Running the application
From the project directory, start the application with:
./mvnw spring-boot:runSpring Boot creates an application context, applies auto-configuration, and starts the embedded web server. By default, the server listens on port 8080.
Adding a first REST endpoint
A REST endpoint is an HTTP URL that returns data. Place this class in the same package, or a child package, as the main application class so component scanning can find it.
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello() {
return "Hello, Spring Boot!";
}
}Test it while the application is running:
curl http://localhost:8080/helloThe response is:
Hello, Spring Boot!Configuring the application
Spring Boot reads key-value settings from src/main/resources/application.properties.
server.port=8081
spring.application.name=demoAfter changing the port, restart the application and call http://localhost:8081/hello.
Packaging an executable JAR
Build a runnable JAR with the Maven wrapper:
./mvnw clean package
java -jar target/demo-0.0.1-SNAPSHOT.jarThe Spring Boot Maven plugin packages application classes and dependencies together. The resulting JAR can run on any compatible JDK.
Next steps: DevTools and Actuator
Spring Boot DevTools can speed up development with automatic restarts. Actuator adds operational endpoints for health checks and monitoring. Add either only when you understand which endpoints are exposed and protect them in deployed environments.
Exercise
Why might a controller work in one package but not another?
Show answer
The main class scans its package and descendants. A controller outside that tree may not be discovered unless you configure component scanning.