Creating a Spring Boot app

Spring Boot · Essentials · 10 min

Every Spring Boot project starts from this structure, and knowing what each piece does demystifies the framework.

The quickest start is Spring Initializr (start.spring.io, or built into IntelliJ and VS Code): pick Maven or Gradle, Java 17+ (Boot 3 requires 17; 21 is a good choice), and add dependencies such as Spring Web. You get a project with a build file, a main class, application.properties and a test.

Dependencies come as starters: spring-boot-starter-web brings Spring MVC, Jackson for JSON and an embedded Tomcat; spring-boot-starter-data-jpa brings Hibernate and Spring Data. The Spring Boot parent POM (or Gradle plugin) manages compatible versions, so you rarely write version numbers yourself.

The main class is annotated @SpringBootApplication, which combines three things:

  • @Configuration: the class can define beans.
  • @EnableAutoConfiguration: Boot configures components based on what's on the classpath (Tomcat and Spring MVC appear because the web starter is there).
  • @ComponentScan: classes annotated @Component, @Service, @RestController and so on, in this package and its sub-packages, are discovered.

SpringApplication.run(App.class, args) creates the application context, starts the embedded server (port 8080 by default) and keeps running. Put the main class in a root package such as com.example.shop so scanning finds everything below it.

Example

// src/main/java/com/example/demo/DemoApplication.java
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
class HelloController {
    @GetMapping("/hello")
    String hello() {
        return "Hello, Spring Boot!";
    }
}
// ./mvnw spring-boot:run  then  curl localhost:8080/hello  -> Hello, Spring Boot!

Remember

  • Starters bundle consistent dependencies; Boot manages their versions
  • @SpringBootApplication = configuration + auto-configuration + component scan
  • Component scanning covers the main class's package and sub-packages
  • The embedded server makes the app a self-contained process

Watch out for

  • Putting the main class in a sub-package, so controllers in sibling packages are never scanned.

Check yourself

  1. Why is a @RestController in com.example.web not found when the main class is in com.example.app?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.spring.io/spring-boot/reference/using/structuring-your-code.html