Skip to content
javahacks.dev
Spring Boot

Spring Boot Tutorial for Beginners From Zero to an API

Build a small REST API with Spring Boot 4 and JDK 25: generate the project, write a controller, add an in memory service, validate input and run the tests.

6 min read
Summarize in AI
Flat illustration of a start button surrounded by Spring Boot starters, with the Spring Boot, Spring, Gradle, Docker and Apache Maven logos.

This tutorial builds a small notes API with Spring Boot 4 on Java 25, and by the end it creates, reads and lists notes over HTTP, rejects bad input, and has a test that proves it. It assumes you have a JDK installed and can run a command in a terminal. Nothing needs a database yet. The wider map of the framework is in the Spring Boot guide, and this post is the first walk through it.

Step 1: generate the project

Open start.spring.io and choose Maven, Java, the latest stable Spring Boot 4 release, and the dependencies Spring Web and Validation. Download the zip and unpack it. The generated pom.xml has spring-boot-starter-parent as its parent, which manages dependency versions, so the dependencies in the file carry no version numbers. That is deliberate. If you add a version to a Boot-managed dependency, you override the one Boot verified alongside the others, and that is how mismatched libraries start. The Maven details are in creating a project with Maven.

The project includes the Maven wrapper, mvnw. Use it instead of a global Maven, so everyone on the project builds with the same version.

Step 2: read the entry point

src/main/java/dev/javahacks/notes/NotesApplication.javajava
@SpringBootApplication
public class NotesApplication {

    public static void main(String[] args) {
        SpringApplication.run(NotesApplication.class, args);
    }
}

@SpringBootApplication combines three things: it marks the class as configuration, it turns on component scanning for this package and everything beneath it, and it enables auto-configuration, which looks at your classpath and sets up what it finds. Because Spring Web is on the classpath, you get an embedded server and JSON conversion without writing a line of setup.

The scanning rule has a consequence that catches beginners. A class outside dev.javahacks.notes is not found. If you add a controller in dev.other and the URL returns 404, this is the reason. What the container does with the classes it finds is explained in how the container works.

Step 3: a model and a service

java
public record Note(Long id, String title, String body) {
}
java
@Service
public class NoteService {

    private final Map<Long, Note> notes = new ConcurrentHashMap<>();
    private final AtomicLong ids = new AtomicLong();

    public Note create(String title, String body) {
        Note note = new Note(ids.incrementAndGet(), title, body);
        notes.put(note.id(), note);
        return note;
    }

    public Optional<Note> find(long id) {
        return Optional.ofNullable(notes.get(id));
    }

    public Collection<Note> all() {
        return notes.values();
    }
}

A record is the shortest honest model for data that does not change: it gives you the constructor, accessors, equals and toString. The service keeps notes in a map, which keeps the tutorial free of a database. The map is a ConcurrentHashMap and the counter an AtomicLong because Spring serves requests on many threads and a plain HashMap would corrupt itself under load. The step to a real database is Hibernate with Spring Boot.

Step 4: the controller

java
@RestController
@RequestMapping("/notes")
class NoteController {

    private final NoteService service;

    NoteController(NoteService service) {
        this.service = service;
    }

    record NewNote(@NotBlank String title, String body) {
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    Note create(@Valid @RequestBody NewNote request) {
        return service.create(request.title(), request.body());
    }

    @GetMapping("/{id}")
    ResponseEntity<Note> get(@PathVariable long id) {
        return service.find(id)
            .map(ResponseEntity::ok)
            .orElse(ResponseEntity.notFound().build());
    }

    @GetMapping
    Collection<Note> list() {
        return service.all();
    }
}

Four things are happening. A class with one constructor needs no @Autowired: Spring sees the NoteService parameter and supplies the bean. @RestController means every method returns data, which Jackson writes as JSON. @Valid on the body asks Bean Validation to check @NotBlank, and a blank title never reaches your method; the client gets a 400. And get returns a ResponseEntity because it has two outcomes with different statuses, 200 and 404.

Note the request type, NewNote. The client should not send the id, so the incoming shape is different from Note. Reusing one class for input and output is the shortcut that lets a caller choose their own id. The annotations are explained further in REST with Spring MVC.

Step 5: run it and call it

Shell
./mvnw spring-boot:run
Shell
curl -X POST localhost:8080/notes \
  -H 'Content-Type: application/json' \
  -d '{"title":"first","body":"hello"}'
curl localhost:8080/notes/1
curl -i localhost:8080/notes/99

The first call returns the created note with "id":1 and status 201. The second reads it back. The third returns 404 with an empty body, which is what notFound().build() produces. If the application fails to start because the port is taken, the fix is in port 8080 already in use.

Try the validation by hand too: post {"title":""} and read the response. You get a 400 whose body names the failing field. That default error shape is fine for learning and worth replacing later with a consistent error format.

Step 6: a test that checks the rule

java
@WebMvcTest(NoteController.class)
@Import(NoteService.class)
class NoteControllerTest {

    @Autowired
    MockMvc mvc;

    @Test
    void rejectsBlankTitle() throws Exception {
        mvc.perform(post("/notes")
                .contentType("application/json")
                .content("{\"title\":\"\"}"))
            .andExpect(status().isBadRequest());
    }

    @Test
    void createsAndReadsBack() throws Exception {
        mvc.perform(post("/notes")
                .contentType("application/json")
                .content("{\"title\":\"a\",\"body\":\"b\"}"))
            .andExpect(status().isCreated());
        mvc.perform(get("/notes/1"))
            .andExpect(status().isOk());
    }
}

@WebMvcTest loads only the web layer, so the test starts quickly and does not need the whole application. @Import adds the service the controller depends on, since the slice does not scan for services. Run the tests with ./mvnw test. The test framework itself is covered in the JUnit 5 tutorial.

The second test relies on the first note getting id 1, which holds in a fresh context and breaks if test order changes shared state. When tests start to depend on each other, give each one its own data.

Step 7: change a setting without touching code

Open src/main/resources/application.properties and add one line:

properties
server.port=9090

Restart and the API answers on 9090. Every Boot setting works this way, and an environment variable overrides the file, so SERVER_PORT=9091 ./mvnw spring-boot:run wins. That override order, file below environment, is what lets the same jar run in a laptop and a container with different values. You will use it for database URLs and credentials long before you need anything more elaborate.

Add management.endpoints.web.exposure.include=health together with the Actuator starter and you also get /actuator/health, the endpoint a load balancer or Kubernetes probe calls. It is the first piece of operations support worth adding to any service.

What to do when it does not work

Most beginner failures come from four causes. The application does not start and the log ends with a stack trace: read the line that begins with Caused by at the bottom, because that is the real error. A URL returns 404: the class sits outside the scanned package, or the path in the mapping is different from the one you call. A request returns 415: the Content-Type header is missing. A value comes back null: the JSON field name does not match the record component name.

What this tutorial leaves out

The in-memory map loses its data on restart and is shared by all requests, so it is a teaching device and not a design. There is no security, no persistence, no logging configuration and no packaging. Continue with the guide for those. The official Spring Boot reference is the complete source, and the Getting Started guides cover specific tasks one at a time.

Also inSpring MVC
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.