Spring Boot · Lesson 1 of 5
Spring Boot Setup and First App
Generate a project and run a first REST endpoint.
- Beginner
- 13 min read
- 3 objectives
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:runThe entry point
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);
}
}@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.
Your first endpoint
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.
// Write your solution here
