Spring Boot Setup and First App
Generate a project and run a first REST endpoint.
What you will learn
- Create a project with Initializr
- Explain auto-configuration
- Return JSON
Spring Boot is the most widely used way to build Java backends. The Spring Framework provides dependency injection and a huge ecosystem; Spring Boot adds auto-configuration and sensible defaults so you can get a production-ready service running in minutes instead of days of XML and setup.
Generate a project
Go to start.spring.io, choose Maven or Gradle, Java 17 or newer, and add these dependencies: Spring Web, Validation, Spring Data JPA and H2 Database. Download, unzip and open it in your IDE.
cd demo
./mvnw spring-boot:run # Windows: mvnw.cmd spring-boot:runpackage 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);
}
}@SpringBootApplication combines three things: configuration, component scanning (find your classes in this package and below) and auto-configuration. Because Spring Web is on the classpath, Boot automatically starts an embedded Tomcat server on port 8080. No separate server installation is needed.
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(@RequestParam(defaultValue = "world") String name) {
return "Hello, " + name + "!";
}
@GetMapping("/health")
public java.util.Map<String, String> health() {
return java.util.Map.of("status", "ok");
}
}curl 'http://localhost:8080/hello?name=Ada'
curl http://localhost:8080/healthHello, Ada!
{"status":"ok"}Returning a Map or an object is converted to JSON automatically by Jackson.
Project layout
src/main/java: your code.src/main/resources/application.properties(or.yml): configuration such as the port.src/test/java: tests.pom.xml/build.gradle: dependencies and build.
Add the spring-boot-starter-actuator dependency to get /actuator/health and metrics endpoints for free, which is what monitoring tools and load balancers use.
Try it yourself
Add GET /time that returns the current server time as a string, and change the port to 9090 in application.properties.
Show solution
@GetMapping("/time")
public String time() {
return java.time.Instant.now().toString();
}
// application.properties: server.port=9090