Skip to content
Tutorials Center
My learning

Topics

Lesson 70 of 119 ยท Spring Boot

Spring Boot Introduction

What Spring Boot adds to Spring - auto-configuration, starters, an embedded server and executable JARs - and how to create, structure and run your first project.

The Spring Framework gives you dependency injection, Spring MVC, transactions and much more, but on its own it asks you to wire everything: register the DispatcherServlet, create a DataSource, configure Jackson, pick a view resolver, then package a WAR and deploy it to a server. Spring Boot removes that setup. You add a dependency such as "web" or "data-jpa", write your own classes, and run a main method. Boot looks at what is on the classpath, configures sensible defaults, starts an embedded web server, and steps aside as soon as you configure something yourself.

This lesson explains the four ideas that make Boot work (auto-configuration, starters, the embedded server and the executable JAR), shows how to create and run a project, and walks through what happens when SpringApplication.run starts. Spring itself can't run on this page, so the runnable examples rebuild Boot's key tricks in plain Java: conditions that check the classpath, configuration that backs off when you define your own bean, and an application that is its own server. You should know Spring Framework Introduction and Spring MVC first.

What Boot adds to Spring

Boot is not a different framework. A Boot application is a Spring application: the same ApplicationContext, beans, @Controllers and @Transactional. Boot adds:

Feature What it means for you
Auto-configuration Beans you would normally write by hand (DataSource, ObjectMapper, DispatcherServlet, transaction manager) are created automatically when the right library is on the classpath.
Starters One dependency per feature (spring-boot-starter-webmvc) brings a tested set of libraries with matching versions.
Embedded server Tomcat (or Jetty) runs inside your application. No server installation, no WAR deployment.
Executable JAR java -jar app.jar runs the whole application, which fits containers and cloud platforms.
Externalized configuration application.properties/.yml, profiles, environment variables (next lesson: Configuration, Properties and Profiles).
Production features Health checks, metrics and info endpoints with Actuator (see Actuator, Metrics and Observability).

Boot's motto is "opinionated defaults": it makes the common choice for you, and every choice can be changed.

Creating a project

The usual starting point is Spring Initializr at start.spring.io, which is also built into IntelliJ IDEA, VS Code (Spring Boot Extension Pack) and Eclipse. You pick the build tool (Maven or Gradle), the Java version, a group and artifact, and the dependencies, and it generates a ready-to-run project. You can also call it from the command line:

Terminal
curl https://start.spring.io/starter.zip \
  -d type=maven-project -d javaVersion=25 \
  -d groupId=com.example -d artifactId=shop \
  -d dependencies=webmvc,data-jpa,validation,h2 \
  -o shop.zip

The generated project has the standard layout from Setting Up a Java Development Environment:

TEXT
shop/
โ”œโ”€โ”€ mvnw, mvnw.cmd, .mvn/           Maven wrapper (no Maven install needed)
โ”œโ”€โ”€ pom.xml
โ””โ”€โ”€ src/
    โ”œโ”€โ”€ main/
    โ”‚   โ”œโ”€โ”€ java/com/example/shop/
    โ”‚   โ”‚   โ””โ”€โ”€ ShopApplication.java    the main class
    โ”‚   โ””โ”€โ”€ resources/
    โ”‚       โ”œโ”€โ”€ application.properties  configuration
    โ”‚       โ”œโ”€โ”€ static/                 CSS, JS, images served as-is
    โ”‚       โ””โ”€โ”€ templates/              Thymeleaf templates
    โ””โ”€โ”€ test/java/com/example/shop/
        โ””โ”€โ”€ ShopApplicationTests.java   a test that starts the context

The heart of the pom.xml is the parent and the starters:

XML
<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>4.1.1</version>             <!-- use the latest 4.x release -->
</parent>

<properties>
  <java.version>25</java.version>
</properties>

<dependencies>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webmvc</artifactId>   <!-- no <version>: the parent manages it -->
  </dependency>
  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
  </dependency>
</dependencies>

<build>
  <plugins>
    <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>   <!-- builds the executable JAR -->
    </plugin>
  </plugins>
</build>

The parent imports Boot's dependency management (a bill of materials, see Maven in Depth): hundreds of libraries with versions that are tested together. That is why the dependencies have no <version> tags, and why upgrading Boot upgrades Spring, Jackson, Hibernate and Tomcat consistently. With Gradle, the org.springframework.boot plugin plus io.spring.dependency-management (or a platform(...) BOM) does the same; see Gradle in Depth.

Spring Boot 4 (November 2025) renamed some starters: the servlet web starter is now spring-boot-starter-webmvc; the old name spring-boot-starter-web still works but is deprecated. Boot 4 also split its auto-configuration into smaller modules, one per technology. Starters pull in the right modules, so with starters you rarely notice. Boot 3 projects use spring-boot-starter-web.

Starters

A starter is a dependency with almost no code of its own. It exists to pull in a feature's libraries. Some common ones:

Starter Brings in
spring-boot-starter-webmvc Spring MVC, embedded Tomcat, Jackson
spring-boot-starter-thymeleaf Thymeleaf and its Spring integration
spring-boot-starter-data-jpa Spring Data JPA, Hibernate, a connection pool (HikariCP)
spring-boot-starter-validation Hibernate Validator (Jakarta Bean Validation)
spring-boot-starter-security Spring Security
spring-boot-starter-actuator Health, metrics and info endpoints
spring-boot-starter-test JUnit Jupiter, AssertJ, Mockito, Spring Test

A database driver is added separately (com.h2database:h2, org.postgresql:postgresql), usually with runtime scope. Starters and auto-configuration work together: the starter puts a library on the classpath, and auto-configuration notices it.

Auto-configuration

An auto-configuration is an ordinary @Configuration class, shipped inside Spring Boot, whose beans are created only when conditions hold. Boot lists its auto-configurations in a file called META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports and evaluates each one at startup. Simplified, the one for Jackson looks like this:

Java
@AutoConfiguration
@ConditionalOnClass(ObjectMapper.class)                  // only if Jackson is on the classpath
public class JacksonAutoConfiguration {

    @Bean
    @ConditionalOnMissingBean                            // only if you didn't define one
    public ObjectMapper objectMapper() {
        return JsonMapper.builder().findAndAddModules().build();
    }
}

The most important conditions:

Condition Matches when
@ConditionalOnClass / @ConditionalOnMissingClass A class is (or isn't) on the classpath
@ConditionalOnBean / @ConditionalOnMissingBean A bean of a type already exists (or doesn't)
@ConditionalOnProperty A configuration property has a given value
@ConditionalOnWebApplication The app is a servlet or reactive web app
@ConditionalOnResource A file exists on the classpath

@ConditionalOnClass is what makes the classpath decide. Here is that idea, using what really is on this page's classpath (H2, Jackson and JUnit, but no Spring or PostgreSQL). It prints a report in the style of Boot's condition evaluation report, then uses the beans that were "auto-configured".

Java The classpath decides: conditional configuration

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice Class.forName(name, false, loader): Boot also checks classes without loading them, because initializing a library just to test for it would be slow and could fail. Boot goes further than this demo: it reads conditions from the compiled bytecode before any class is loaded.

To see the real report in your app, start it with --debug (or set debug=true in application.properties). The "Negative matches" section answers the common question "why is my bean not created?". To turn an auto-configuration off completely, exclude it: @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) or the property spring.autoconfigure.exclude.

Backing off: your beans win

The second rule of auto-configuration is just as important: if you define a bean yourself, Boot's default for that type backs off. Boot guarantees this by processing auto-configurations after all of your own configuration, so @ConditionalOnMissingBean sees your beans. Defining your own ObjectMapper bean replaces Boot's; defining your own DataSource replaces the auto-configured pool.

The next program rebuilds this mechanism with reflection. It reads an AutoConfiguration.imports list, loads each class, checks its class-level and bean-level conditions, and only then calls the @Bean methods. The user's configuration runs first and defines its own Clock, so the auto-configured Clock backs off, while the Greeter is created only because a property allows it.

Java Auto-configuration that backs off

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The greeting says "Good morning" because the Greeter received your fixed clock (9:30 UTC), not the system clock. Change greeter.enabled to "false" in the properties map and the Greeter disappears, so the last line fails with a NullPointerException. In Spring Boot you would get a clear startup error instead: "required a bean of type Greeter that could not be found".

Backing off works by type. If you define a bean of a slightly different type (for example a JsonMapper subclass where Boot looks for ObjectMapper, or the other way around), you may end up with two beans, or Boot's default may still be created. When in doubt, check the condition evaluation report. And prefer customizing over replacing: Boot offers customizer beans (for example for the Jackson mapper builder) and many spring.* properties, so you keep Boot's defaults and change one detail.

The main class

Every Boot application has a class like this in its root package:

Java
package com.example.shop;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

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

@SpringBootApplication combines three annotations:

  • @SpringBootConfiguration: this class is a @Configuration, so it may contain @Bean methods.
  • @EnableAutoConfiguration: evaluate the auto-configurations.
  • @ComponentScan: scan this package and its sub-packages for @Component, @Service, @Repository, @Controller and @Configuration classes.

That last point explains a classic mistake: a controller in com.example.web (a sibling package, not a sub-package of com.example.shop) is never found, and its URLs return 404. Keep the main class in the top-level package, with everything else below it.

SpringApplication.run then does roughly this:

  1. Prepare the Environment: read command-line arguments, environment variables, application.properties and profiles.
  2. Print the banner and create the right ApplicationContext (servlet web, reactive web or plain).
  3. Load bean definitions: component scanning, your @Configuration classes, then auto-configurations.
  4. Create the singletons. For a web app, this starts the embedded Tomcat on port 8080.
  5. Call every ApplicationRunner and CommandLineRunner bean, then publish ApplicationReadyEvent.
  6. Register a shutdown hook, so Ctrl+C or SIGTERM closes the context: Tomcat stops accepting requests, in-flight requests finish (graceful shutdown is on by default since Boot 3.4), and @PreDestroy methods run.

A typical startup log (shortened):

TEXT
  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
...
INFO  ShopApplication       : Starting ShopApplication using Java 25 with PID 12345
INFO  ShopApplication       : No active profile set, falling back to 1 default profile: "default"
INFO  TomcatWebServer       : Tomcat initialized with port 8080 (http)
INFO  TomcatWebServer       : Tomcat started on port 8080 (http) with context path '/'
INFO  ShopApplication       : Started ShopApplication in 1.42 seconds (process running for 1.7)

The final runnable example plays the same sequence in plain Java: read properties (with server.port=0 meaning "any free port", exactly as in Boot), create beans, start an embedded HTTP server from main, run a "command-line runner", handle a request, and shut down in order.

Java An application that is its own server

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Without the System.exit(0) call, this program would never finish: the server's thread keeps the JVM alive after main returns. That is exactly why a Boot web application keeps running after SpringApplication.run returns, and why it stops only when it receives a signal and its shutdown hook closes the context.

Running the application

During development, run the main class from your IDE, or use the build tool:

Terminal
./mvnw spring-boot:run            # Maven
./gradlew bootRun                 # Gradle

To ship it, build the executable JAR and run it with plain Java:

Terminal
./mvnw clean package              # creates target/shop-0.0.1-SNAPSHOT.jar
java -jar target/shop-0.0.1-SNAPSHOT.jar --server.port=9090

This "fat" JAR contains your classes under BOOT-INF/classes, every dependency as a nested JAR under BOOT-INF/lib, and a small launcher (org.springframework.boot.loader.launch.JarLauncher) that knows how to load nested JARs. One file, one command, no external server, which is exactly what a container image needs (see Docker for Java Developers). You can still build a WAR for an external Tomcat if your organization requires it, but new projects rarely do.

Two development helpers are worth adding early:

  • DevTools (spring-boot-devtools, scope runtime/developmentOnly): restarts the application automatically when classes change and disables template caching. It is excluded from the packaged JAR.
  • Docker Compose support (spring-boot-docker-compose): if the project has a compose.yaml with, say, PostgreSQL, Boot starts it on bootRun and configures the connection for you.

Your first endpoint

Put it all together and a working web application is two small classes:

Java
package com.example.shop.web;

@RestController
public class HelloController {
    @GetMapping("/hello")
    public Map<String, String> hello(@RequestParam(defaultValue = "world") String name) {
        return Map.of("message", "Hello, " + name + "!");
    }
}

Run ShopApplication, open http://localhost:8080/hello?name=Ada, and the response is {"message":"Hello, Ada!"}. You didn't configure Tomcat, the DispatcherServlet or Jackson: the webmvc starter put them on the classpath, and auto-configuration set them up. Building REST APIs with Spring Boot continues from here.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You add the PostgreSQL driver to a Boot project and define no DataSource bean. What happens at startup?

    DataSource auto-configuration is conditional on the classes being present and on no user-defined DataSource bean.
  2. 2. You define your own ObjectMapper bean in a @Configuration class. What does Boot's Jackson auto-configuration do?

    Auto-configurations are processed after user configuration, so @ConditionalOnMissingBean sees your bean and skips the default.
  3. 3. The main class is in com.example.shop and a controller is in com.example.web. Requests to the controller's URLs return 404. Why?

    Component scanning starts at the package of the main class. Keep the main class in the root package of the application.
  4. 4. What does a starter such as spring-boot-starter-webmvc contain?

    Starters have almost no code. They put libraries on the classpath, and auto-configuration reacts to those libraries.
  5. 5. Why does "java -jar app.jar" work for a Boot application without installing a web server?

    The Boot plugin packages an executable fat JAR with BOOT-INF/lib and a launcher. The application starts its own server.

Summary

  • Spring Boot is Spring with auto-configuration, starters, an embedded server, executable JARs and externalized configuration.
  • Create projects with Spring Initializr; the spring-boot-starter-parent (or Gradle plugin) manages compatible dependency versions.
  • Auto-configurations are conditional @Configuration classes: @ConditionalOnClass lets the classpath decide, @ConditionalOnMissingBean lets your own beans win, @ConditionalOnProperty lets settings decide.
  • Run with --debug to see the condition evaluation report; exclude auto-configurations you don't want.
  • @SpringBootApplication = configuration + auto-configuration + component scanning from the main class's package downward.
  • SpringApplication.run prepares the environment, creates the context, starts the server, calls runners and registers a graceful shutdown hook.
  • Run with spring-boot:run / bootRun during development and java -jar in production.

Next: Configuration, Properties and Profiles shows how Boot reads settings from files, environment variables and the command line, and how to bind them to typed objects.