Chapter 02

Your first application

Ten minutes to a running REST endpoint — and then a careful look at what each generated file and each startup log line actually means.

⏱ 16 min readLevel: beginnerHands-on

Prerequisites

  • JDK 17 or newer (java -version). JDK 21 is a good default in 2026.
  • Maven 3.9+ or Gradle 8+ — or neither, since the generated project includes a wrapper.
  • An IDE with Spring support helps but is not required.

Generating the project

start.spring.io is the canonical way. It is also a plain HTTP API, which is faster from a terminal:

terminal
curl https://start.spring.io/starter.zip \
  -d type=maven-project \
  -d language=java \
  -d bootVersion=3.3.4 \
  -d javaVersion=17 \
  -d groupId=com.bitsnippets \
  -d artifactId=bookstore \
  -d packageName=com.bitsnippets.bookstore \
  -d dependencies=web,validation,data-jpa,postgresql,actuator,devtools \
  -o bookstore.zip

unzip bookstore.zip -d bookstore
cd bookstore
Pick fewer starters than you think you need

Every starter you add turns on auto-configuration you may not want. spring-boot-starter-security in particular will lock every endpoint the moment it appears on the classpath. Add starters when you need them — it is one line.

The build file

pom.xml
<project>
  <modelVersion>4.0.0</modelVersion>

  <!-- the parent pins ~400 dependency versions that are known to work together -->
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>3.3.4</version>
    <relativePath/>
  </parent>

  <groupId>com.bitsnippets</groupId>
  <artifactId>bookstore</artifactId>
  <version>0.0.1-SNAPSHOT</version>

  <properties>
    <java.version>17</java.version>
  </properties>

  <dependencies>
    <!-- note: no versions. The parent supplies them. -->
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-validation</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-devtools</artifactId>
      <scope>runtime</scope>
      <optional>true</optional>
    </dependency>

    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <!-- this is what makes the jar executable -->
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>
build.gradle.kts
plugins {
    java
    id("org.springframework.boot") version "3.3.4"
    id("io.spring.dependency-management") version "1.1.6"
}

group = "com.bitsnippets"
version = "0.0.1-SNAPSHOT"

java {
    toolchain { languageVersion = JavaLanguageVersion.of(17) }
}

repositories { mavenCentral() }

dependencies {
    implementation("org.springframework.boot:spring-boot-starter-web")
    implementation("org.springframework.boot:spring-boot-starter-validation")
    implementation("org.springframework.boot:spring-boot-starter-actuator")
    developmentOnly("org.springframework.boot:spring-boot-devtools")
    testImplementation("org.springframework.boot:spring-boot-starter-test")
}

tasks.test { useJUnitPlatform() }

@SpringBootApplication, taken apart

It is a convenience annotation for three others. Knowing which three explains most "why isn't my bean found" problems.

equivalent, written out
@SpringBootConfiguration   // a @Configuration that Boot can find as the app's root
@EnableAutoConfiguration   // turn on the conditional configuration machinery
@ComponentScan             // scan THIS package and everything below it
public class BookstoreApplication {

    public static void main(String[] args) {
        SpringApplication.run(BookstoreApplication.class, args);
    }
}
The package of your main class matters

@ComponentScan starts from the package containing the annotated class. If BookstoreApplication lives in com.bitsnippets.bookstore, then a @Service in com.bitsnippets.util is invisible — you get "required a bean of type … that could not be found". Always put the main class in the root package of your application.

Customising the launch

BookstoreApplication.java
public static void main(String[] args) {
    SpringApplication app = new SpringApplication(BookstoreApplication.class);

    app.setBannerMode(Banner.Mode.OFF);              // no ASCII art in the logs
    app.setDefaultProperties(Map.of("server.port", "8081"));
    app.setAdditionalProfiles("dev");                // in addition to any active profile

    app.run(args);
}

A working endpoint

catalog/BookController.java
package com.bitsnippets.bookstore.catalog;

import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/books")
public class BookController {

    // In-memory for now; chapter 8 replaces this with a real repository.
    private final Map<Long, Book> store = new ConcurrentHashMap<>();
    private final AtomicLong sequence = new AtomicLong();

    @GetMapping
    public List<Book> findAll() {
        return List.copyOf(store.values());
    }

    @GetMapping("/{id}")
    public Book findById(@PathVariable Long id) {
        Book book = store.get(id);
        if (book == null) {
            throw new BookNotFoundException(id);
        }
        return book;
    }

    @PostMapping
    @ResponseStatus(HttpStatus.CREATED)
    public Book create(@RequestBody Book book) {
        long id = sequence.incrementAndGet();
        Book saved = new Book(id, book.title(), book.author(), book.price());
        store.put(id, saved);
        return saved;
    }
}
catalog/Book.java
package com.bitsnippets.bookstore.catalog;

import java.math.BigDecimal;

// A record is enough for now — Jackson handles them natively.
public record Book(Long id, String title, String author, BigDecimal price) { }
terminal
./mvnw spring-boot:run

curl -X POST localhost:8080/api/books \
     -H "Content-Type: application/json" \
     -d '{"title":"Effective Java","author":"Bloch","price":42.00}'

# {"id":1,"title":"Effective Java","author":"Bloch","price":42.00}

curl localhost:8080/api/books/1

Nothing registered that controller, nothing configured JSON, nothing started a server. All three were auto-configured because spring-boot-starter-web is on the classpath and BookController is in a scanned package.

Reading the startup log

console
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::                (v3.3.4)

INFO 12044 --- [main] c.b.bookstore.BookstoreApplication : Starting BookstoreApplication using Java 21
INFO 12044 --- [main] c.b.bookstore.BookstoreApplication : No active profile set, falling back to 1 default profile: "default"
INFO 12044 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port 8080 (http)
INFO 12044 --- [main] o.a.c.c.C.[Tomcat].[localhost].[/]      : Initializing Spring embedded WebApplicationContext
INFO 12044 --- [main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 812 ms
INFO 12044 --- [main] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 1 endpoint beneath base path '/actuator'
INFO 12044 --- [main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port 8080 (http) with context path '/'
INFO 12044 --- [main] c.b.bookstore.BookstoreApplication       : Started BookstoreApplication in 1.61 seconds (process running for 1.9)
LineWhy you care
No active profile setYou are on default. In any deployed environment this line should name a real profile — if it does not, your config is not being applied.
Tomcat initialized with port 8080Confirms it is a servlet web application. If this line is missing, Boot decided the app is not a web app and will exit immediately.
Exposing 1 endpoint beneath '/actuator'Actuator is present. Chapter 12 opens this up properly.
Started … in 1.61 secondsTrack this number. A sudden jump usually means a new auto-configuration started doing real work at boot.

DevTools and fast feedback

spring-boot-devtools restarts the application when compiled classes change. It is a restart, not true hot-swapping, but it is fast because it reloads only your classes and keeps the unchanged library classloader.

application.yml
spring:
  devtools:
    restart:
      enabled: true
      # do not restart for template or static asset changes
      exclude: static/**,public/**,templates/**
    livereload:
      enabled: true

DevTools also sets sensible development defaults for you: template caching off, more detailed error pages, and H2 console enabled if present. It is automatically disabled in a fully packaged jar, so it cannot leak into production.

Running code at startup

common/SeedData.java
@Component
@Profile("dev")                     // only in the dev profile — see chapter 5
public class SeedData implements ApplicationRunner {

    private static final Logger log = LoggerFactory.getLogger(SeedData.class);

    private final BookService books;

    public SeedData(BookService books) {
        this.books = books;
    }

    @Override
    public void run(ApplicationArguments args) {
        if (args.containsOption("skip-seed")) {
            return;
        }
        books.create(new Book(null, "Effective Java", "Bloch", new BigDecimal("42.00")));
        log.info("Seeded development data");
    }
}

Use ApplicationRunner for parsed arguments, CommandLineRunner for the raw String[]. Both run after the context is ready but before the application is considered started. Order several with @Order.

Troubleshooting the first run

SymptomCauseFix
App starts and exits immediately No web starter, so it is not a web application Add spring-boot-starter-web
Port 8080 was already in use Another process (often a previous run) --server.port=8081, or server.port=0 for a random port
required a bean of type … could not be found Class outside the scanned package tree Move it under the main class's package, or add @ComponentScan
Failed to configure a DataSource JPA starter present, no database URL Configure spring.datasource.url, or drop the starter for now
Every request returns 401 with a password in the log Security starter on the classpath See chapter 10 — do not just remove it
ClassNotFoundException: javax.servlet… A Boot 2-era library on a Boot 3 classpath Upgrade the library to its Jakarta version

Your @Service is in com.example.util and the main class is in com.example.app. What happens?

@ComponentScan only scans the main class's package and its sub-packages. com.example.util is a sibling, not a child, so it is never scanned. Move the main class up to com.example, or list the extra package explicitly.