Spring Boot

The key features that make Spring Boot stand out include:

  1. Auto-Configuration: Automatically configures your Spring application based on the dependencies you have added (the "magic" of Spring Boot).
  2. Standalone: Applications can run independently without needing to be deployed to an external web server.
  3. Opinionated: It makes "opinions" about which packages and configurations to use, reducing the number of decisions developers need to make.
  4. Starters: Provides a set of convenient dependency descriptors (e.g., spring-boot-starter-web) to simplify build configurations.
  5. Actuator: Provides production-ready features like health checks, metrics, and auditing to monitor your app.

  1. Rapid Development: Drastically reduces the time spent on boilerplate code and configuration.
  2. Embedded Server: No need to install or configure Tomcat, Jetty, or Undertow separately.
  3. No XML Configuration: Eliminates the need for complex XML files; everything is handled via Java Annotations or properties.
  4. Microservices Ready: Its lightweight nature and standalone capabilities make it the go-to framework for microservices architecture.
  5. Easier Dependency Management: Using "Starters" prevents version conflicts between different libraries.

To start a Spring Boot project:

  1. Install Java: Ensure JDK 17 or later is installed.
  2. Spring Initializr: Visit start.spring.io to generate a project structure.
  3. Choose Dependencies: Add "Spring Web," "Spring Data JPA," or others as needed.
  4. Download & Extract: Download the generated ZIP, extract it, and open it in an IDE (like IntelliJ IDEA or Eclipse).
  5. Run: Execute the main method in the generated ...Application.java file.

As of January 2026, the latest stable version is Spring Boot 4.0.2. This version requires Java 17 as a minimum and provides enhanced support for modern Java features and cloud-native deployments.

A Starter is a set of convenient dependency descriptors you can include in your application. Instead of manually adding 10 different libraries for a web app, you just add spring-boot-starter-web.

  • Example: spring-boot-starter-data-jpa pulls in everything needed for database interaction, including Hibernate and Spring Data.

The Actuator is a sub-project that adds several production-grade services to your application. It provides HTTP endpoints that allow you to "look inside" your running app.

  • /actuator/health: Shows application health status.
  • /actuator/metrics: Shows memory usage, CPU usage, etc.
  • /actuator/env: Returns current environment properties.

Spring Boot looks at the classpath (the libraries you've added). If it sees a specific library, it assumes you want to use it and configures it automatically.

Example: If h2.jar is on the classpath and you haven't configured a database connection, Spring Boot automatically configures an in-memory database for you.

Spring Data JPA is a layer that makes it easy to implement JPA-based (Java Persistence API) repositories. It reduces the amount of "boilerplate" code required to interact with databases.

  • Magic Methods: You can define an interface like findByLastName(String name), and Spring Data JPA will automatically generate the SQL query for you.

You use the @RestController and @RequestMapping annotations.

In this example, visiting localhost:8080/api/greet would return the string "Hello, Spring Boot!".

Feature Spring Framework Spring Boot
Goal Provides a comprehensive programming model Simplifies Spring development
Configuration Requires manual XML or Java config Auto-configuration (Convention over Configuration)
Server Needs an external server (Tomcat) Built-in embedded server
Complexity High (lots of boilerplate) Low (Rapid Application Development)

Definition and Function

The @SpringBootApplication annotation is a "meta-annotation" used to mark the main class of a Spring Boot application. It serves as the entry point and triggers the framework's automatic setup processes. By placing this on your main class, you enable the fundamental features required to run a standalone Spring application.


The Three Combined Annotations

This single annotation is a convenience wrapper that combines the following three core functionalities:

  • @SpringBootConfiguration:
    • Indicates that the class provides Spring Boot application configuration.
    • It is a specialized version of the standard @Configuration annotation, allowing the framework to automatically find and load your bean definitions.
  • @EnableAutoConfiguration:
    • Tells Spring Boot to start adding beans based on the libraries found on the classpath.
    • Example: If spring-boot-starter-web is present, this annotation triggers the setup of an embedded Tomcat server and Spring MVC.
  • @ComponentScan:
    • Directs Spring to search the current package and its sub-packages for components, configurations, and services (classes marked with @Component, @Service, @Repository, or @RestController).
    • This allows the framework to automatically register your classes as Spring Beans.

Core Differences

Both application.properties and application.yml (YAML) are used to configure Spring Boot applications. While they achieve the same end goal of providing configuration metadata, they differ significantly in syntax and structure.

Feature application.properties application.yml
Format Key-Value pairs. Hierarchical/Tree structure.
Readability Can become repetitive with long keys. Highly readable due to indentation.
Repetition Requires full prefix for every line. Uses indentation to group related settings.
List Support Uses indexed keys (e.g., list[0]). Uses native YAML list syntax (-).
Profiles Requires separate files (e.g., application-dev.properties). Supports multi-profile documents in a single file using --- separators.


Syntax Comparison

application.properties Properties files use a flat structure. This can lead to significant redundancy as the application grows:

application.yml YAML uses indentation (spaces) to represent hierarchy, which is more concise and visually organized:

Key Technical Considerations

  • Loading Order: If both files exist in the same location, Spring Boot will load application.properties after application.yml, meaning the properties file will override the YAML file.
  • Limitations: Unlike properties files, YAML files cannot be loaded using the @PropertySource annotation; they must be loaded via the main Spring Boot application configuration.

Definition and Purpose

Spring Boot Profiles provide a way to segregate parts of your application configuration and make it available only in certain environments (e.g., Development, Testing, Production). This prevents the need to change code when deploying to different infrastructures.


Configuration Methods

You can define profile-specific properties using two primary naming conventions:

  • Properties Files: Create files named application-{profile}.properties.
    • Example: application-dev.properties and application-prod.properties.
  • YAML Files: Use a single application.yml file with document separators (---) to define blocks for different profiles.

How to Activate Profiles

There are several ways to tell Spring Boot which profile to use at runtime:

  • Application Properties: Set spring.profiles.active=prod inside the default application.properties file.
  • Command Line: Pass an argument when running the JAR file:
    • java -jar app.jar --spring.profiles.active=prod
  • JVM System Parameter: Use the -D flag:
    • java -Dspring.profiles.active=prod -jar app.jar
  • Environment Variables: Set an OS environment variable named SPRING_PROFILES_ACTIVE.
  • Programmatically: Use SpringApplication.setAdditionalProfiles("dev") in the main method before running the app.

Usage in Code

Beyond configuration files, you can use profiles to control bean creation:

  • @Profile Annotation: Apply @Profile("dev") to a class or a @Bean method. That bean will only be loaded into the Application Context if the "dev" profile is active.

Role and Purpose

The CommandLineRunner and ApplicationRunner interfaces are used to execute a specific block of code immediately after the Spring ApplicationContext is loaded and the application has started, but before it begins handling requests.

They are commonly used for "startup" tasks such as:

  • Seeding a database with initial data.
  • Checking if specific environment variables are set.
  • Starting background processes or messaging listeners.

Key Differences

The primary difference between the two is how they handle command-line arguments.

Feature CommandLineRunner ApplicationRunner
Method Signature run(String... args) run(ApplicationArguments args)
Argument Type Raw String array. Sophisticated ApplicationArguments object.
Data Parsing Requires manual parsing of strings. Provides built-in methods to access "option" (e.g., --key=value) and "non-option" arguments.
Implementation Details
  • Registration: You can implement these interfaces in a class marked with @Component, or define them as a @Bean in a configuration class.
  • Ordering: If multiple runners are defined, you can control their execution sequence using the @Order annotation or the Ordered interface.
  • Exception Handling: If the run method throws an exception, the application will fail to start and shut down.

Overview

Spring Boot uses Externalized Configuration allow the same application code to work in different environments. You can use properties files, YAML files, environment variables, and command-line arguments to feed configuration into your beans.

The Hierarchy of Overriding

Spring Boot uses a specific order of precedence to resolve configuration conflicts. If a property is defined in multiple places, the higher-priority source wins.

Order of Precedence (from highest to lowest):
  1. Command-line arguments (e.g., --server.port=9000).
  2. Java System properties (-Dserver.port=9000).
  3. OS Environment variables.
  4. Profile-specific application properties (e.g., application-dev.properties) outside of the packaged JAR.
  5. Profile-specific application properties inside the packaged JAR.
  6. Application properties (application.properties) outside of the packaged JAR.
  7. Application properties inside the packaged JAR.
Methods for Accessing Configuration

To inject these external values into your Java code, Spring Boot provides two primary mechanisms:

  • @Value("${property.name}"): Used for injecting individual values directly into fields. It is simple but can become disorganized if you have many properties.
  • @ConfigurationProperties:
    • Provides type-safe configuration by mapping groups of properties to a Java object.
    • Supports hierarchical structures and validation.
    • Example: Mapping all properties starting with mail.* to a MailProperties class.
Relaxed Binding

Spring Boot uses "relaxed binding," meaning the property name in the configuration file doesn't have to be an exact match with the field name in the code.

  • Property source<: spring.my-example.url, SPRING_MYEXAMPLE_URL, or spring.myExample.url
  • Java field: myExampleUrl
  • All of the above will successfully bind to the same field.

Overview

Spring Initializr is a web-based service (accessible via start.spring.io) that acts as a project bootstrapping tool. It allows developers to generate a pre-configured Spring Boot project structure with all the necessary dependencies and build settings.

Key Features
  • Build Tool Selection: Choose between Maven or Gradle.
  • Language Support: Supports Java, Kotlin, and Groovy.
  • Version Management: Automatically selects compatible versions of Spring Boot and the selected Java version (e.g., Java 17, 21).
  • Dependency Management: Offers a searchable directory of "Starters" (Web, Security, Data JPA, etc.), which are then automatically added to the pom.xml or build.gradle file.
  • Metadata Configuration: Allows customization of Group ID, Artifact ID, and Package name.
How it Speeds Up Development
  • Eliminates Boilerplate: You don't have to manually create the directory structure (src/main/java, src/main/resources, etc.).
  • Automates Dependency Resolution: It handles the complex "dependency hell" by ensuring all selected libraries are compatible with the specific Spring Boot version chosen.
  • Ready-to-Run: The generated project includes the @SpringBootApplication main class and an empty configuration file, allowing you to run the app immediately after downloading.
  • IDE Integration: Most modern IDEs (IntelliJ IDEA, Eclipse, VS Code) have Spring Initializr built-in, allowing you to create projects without leaving the editor.

Core Definitions

All three annotations—@Component, @Service, and @Repository—are specialized versions of the same base annotation. They serve as "markers" that tell Spring to automatically detect the class during component scanning and register it as a Spring Bean in the Application Context.


Comparison Table
Annotation Purpose Architectural Layer Special Functionality
@Component Generic stereotype. Any None; used when the class doesn't fit a specific layer.
@Service Marks a service bean. Service Layer None; used to indicate that the class contains business logic.
@Repository Marks a data access bean. Persistence Layer Exception Translation: Converts low-level database exceptions into Spring's DataAccessException.

Key Distinctions
  • @Component (The Parent): This is the most general annotation. Technically, you could use @Component for every bean in your application, and it would function correctly. However, it is considered poor practice because it lacks semantic meaning.
  • @Service (Semantic Naming): Like @Component, it has no extra specialized behavior. It is used strictly for readability and to define the middle tier of your application where the business rules reside.
  • @Repository (The Exception Handler): This is more than just a label. It tells Spring to catch platform-specific exceptions (like SQLException) and re-throw them as consistent, unchecked Spring exceptions. This makes your data access code more robust and portable across different database technologies.
Usage Recommendation

Always use the most specific annotation possible. Use @Repository for DAO classes, @Service for business logic classes, and only fall back to @Component for utility classes or cross-cutting concerns that don't belong to a specific layer.

Methods for Exclusion

Even though Auto-Configuration is one of Spring Boot's most powerful features, there are scenarios—such as using a custom database setup or a specific security configuration—where you may need to disable a specific auto-configured bean or class.


  1. Using the @SpringBootApplication Annotation
  2. The most common way to exclude a class is via the exclude attribute on the main application class. This tells Spring Boot to ignore specific auto-configuration classes during the startup process.

  3. Using the @EnableAutoConfiguration Annotation
  4. If you are using @EnableAutoConfiguration separately (rather than through the @SpringBootApplication wrapper), you can use the same exclude attribute:

    • By Class: @EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class})
    • By Class Name (String): @EnableAutoConfiguration(excludeName = {"org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration"})
      • Note: Use excludeName if the class is not on your current compile-time classpath.
  5. Via Application Properties
  6. You can also exclude auto-configuration classes externally without changing the source code. This is particularly useful for environment-specific exclusions.

    • In application.properties:
    • In application.yml:
  • Why Exclude Auto-Configuration?
    • Custom Implementations: You want to provide your own complex bean definition and prevent Spring from creating its default version.
    • Performance: Disabling unnecessary features (like embedded MongoDB or Mail services) can slightly improve startup time.
    • Troubleshooting: Temporarily disabling a specific module to isolate a configuration error.

    Core Definitions

    In Spring Boot, both annotations are used to define classes that handle incoming HTTP requests. However, they differ in how they process the data and what they return to the client.


    Comparison Table
    Feature @Controller @RestController
    Purpose Used for traditional web applications with views. Used for RESTful web services (APIs).
    Return Value Typically returns a String (the name of a View/HTML template). Returns Data (JSON or XML) directly in the HTTP response body.
    Response Body Requires @ResponseBody on every method to return data. Includes @ResponseBody by default for all methods.
    Model Support Frequently uses the Model object to pass data to a template. Does not use a View model; serializes objects directly.

    Key Distinctions
    • @Controller (Traditional Web):
      • It is a stereotype for the presentation layer.
      • When a method returns a String like "home", the Spring ViewResolver looks for a file named home.html (if using Thymeleaf) to render.
      • To return data (like a JSON object) from a specific method in a @Controller, you must manually add the @ResponseBody annotation to that method.
    • @RestController (API Development):
      • This is a convenience annotation that combines @Controller and @ResponseBody.
      • It assumes that every method in the class will return a data object rather than a visual template.
      • Spring automatically uses HttpMessageConverters (like Jackson for JSON) to convert your Java objects into the format requested by the client.
    Code Comparison
    Using @Controller:
    Using @RestController:

    Overview

    In Spring Boot, @ControllerAdvice is a specialized interceptor that allows you to handle exceptions across the entire application in one global, centralized location. Instead of using try-catch blocks in every controller method, you can define how to respond to specific errors once.

    Mechanism: How It Works

    A class annotated with @ControllerAdvice acts as a "global interceptor" for exceptions thrown by any method in any @Controller or @RestController. When an exception occurs, Spring searches this class for a matching handler method.

    • @ExceptionHandler: Used inside the advice class to define which specific exception type the method should catch (e.g., EntityNotFoundException.class).
    • @ResponseStatus: Optionally used to define the specific HTTP status code (like 404 or 500) that should be returned.

    Implementation Example

    Below is a standard implementation for a global error handler that returns a structured JSON error response.

    Key Benefits
    • Consistency: Ensures that every error response follows the same data structure (e.g., always including a timestamp and error code).
    • Code Cleanliness: Removes error-handling logic from business controllers, making them easier to read and maintain.
    • Centralization: Allows for easy updates to error-handling logic in a single file rather than hunting through dozens of controllers.
    • Type Safety: You can target specific exception hierarchies, allowing for different responses for validation errors versus database errors.

    Difference: @ControllerAdvice vs @RestControllerAdvice

    Just like @Controller vs @RestController, @RestControllerAdvice is a convenience annotation that combines @ControllerAdvice and @ResponseBody. It ensures that the return value of the error handler is automatically converted into JSON/XML for the response body.

    Core Purpose

    The spring-boot-starter-web is a "starter" dependency that bundles all the necessary libraries to build web applications, including RESTful services, using Spring MVC. It follows the "opinionated" approach of Spring Boot by providing a pre-configured stack so you don't have to manually import individual dependencies for routing, JSON parsing, or server management.


    Key Components Included

    When you add this single dependency to your pom.xml or build.gradle, it transitively pulls in the following core modules:

    • Spring MVC: The framework used to build web components like Controllers and View Resolvers.
    • Embedded Tomcat: By default, it includes an Apache Tomcat server, allowing the application to run as a standalone .jar file without an external server installation.
    • Jackson: A library used for automatic serialization and deserialization of Java objects to and from JSON.
    • Validation: Provides Hibernate Validator for handling @Valid and JSR-303 bean validation.
    • Spring Boot Starter: The base starter that includes auto-configuration support, logging (Logback), and YAML support.

    Usage Scenarios

    This dependency is required for:

    1. REST APIs: Building endpoints that return JSON or XML data.
    2. Traditional Web Apps: Serving HTML pages using template engines like Thymeleaf or FreeMarker.
    3. Microservices: Creating the web-based communication layer for service-to-service interaction.

    Comparison: Web vs. WebFlux
    Feature spring-boot-starter-web spring-boot-starter-webflux
    Model Blocking / Synchronous (One thread per request). Non-blocking / Asynchronous (Event-loop).
    Stack Servlet-based (Spring MVC). Reactive-stack (Project Reactor).
    Server Default: Tomcat. Default: Netty.

    Overview

    Spring Data JPA provides built-in support for Pagination and Sorting through the PagingAndSortingRepository interface (which JpaRepository extends). This allows you to retrieve large datasets in smaller, manageable chunks and organize them by specific fields without writing manual SQL.


    1. Repository Interface
    2. To enable these features, your repository must extend JpaRepository or PagingAndSortingRepository.

    3. Using Pageable and Sort
    4. The core of the implementation lies in the Pageable interface and the PageRequest implementation.

      • Sorting Only: Use the Sort class to define fields and directions.
        • Example: Sort.by("price").descending()
      • Pagination: Use PageRequest.of(pageNumber, pageSize).
      • Combined: PageRequest.of(pageNumber, pageSize, Sort.by("price").ascending()).

    5. Implementation in the Service Layer
    6. The service layer typically converts raw parameters (from a controller) into a PageRequest object.

      Component Description
      Page Number The zero-based index of the page to retrieve (e.g., 0 for the first page).
      Page Size The number of records to return per page.
      Page Object The returned container that includes the data (List) plus metadata (total elements, total pages, current page).
      Example Service Method:
    7. The Page Response
    8. When you return a Page object, Spring Boot serializes it into a JSON structure that helps frontend clients manage navigation:

      • content: The list of items for the current page.
      • totalElements: Total number of rows in the database.
      • totalPages: Total pages calculated based on size.
      • number: Current page index.

    Core Definitions

    A Standalone Server is a separate software installation (like Tomcat, WildFly, or GlassFish) that exists independently of your application. You must deploy your application code (usually as a .war file) into this pre-installed environment.

    An Embedded Server is a library (like tomcat-embed-core) that is bundled directly inside your application’s .jar file. When you run your application, the server starts as part of the application process.


    Key Comparison
    Feature Embedded Server (Spring Boot Default) Standalone Server (Traditional)
    Packaging Packaged as a FAT JAR. Packaged as a WAR file.
    Installation No server installation required on the host. Server must be installed and configured on the host.
    Deployment Run via simple command: java -jar app.jar. Copy WAR file to the server's webapps folder.
    Versions Server version is managed via project dependencies. Server version is fixed by the infrastructure team.
    Configuration Configured via application.properties. Configured via server-specific files (e.g., server.xml).
    Isolation Each app has its own dedicated server process. Multiple apps often share one server instance.

    Advantages of Embedded Servers
    • Simplified Deployment: You only need a Java Runtime Environment (JRE) on the target machine. This is ideal for Docker containers and cloud-native environments.
    • Consistency: The server version is exactly the same in Development, Testing, and Production, eliminating "it works on my machine" issues.
    • Easy Scaling: Since each instance is self-contained, you can easily spin up multiple instances of a microservice on different ports or containers.
    • Version Control: Server configurations and version upgrades are handled in your code (e.g., pom.xml), making them part of your version control history.
    When to Use a Standalone Server
    • When your organization has a dedicated operations team that manages large, centralized application server clusters.
    • When you need to deploy multiple different applications into a single shared environment to save memory resources (though this is becoming less common with the rise of Microservices).

    Overview

    In Spring Boot, both RestTemplate and WebClient are used to make HTTP requests to external services. While RestTemplate has been the standard for years, WebClient is the modern, preferred alternative introduced in Spring 5.


    Key Comparison
    Feature RestTemplate WebClient
    Programming Model Synchronous / Blocking. Asynchronous / Non-blocking (Reactive).
    Library Spring Web (Servlet API). Spring WebFlux (Project Reactor).
    Efficiency One thread per request; scales poorly. High concurrency with fewer threads.
    Status Maintenance Mode (no new features). Active Development (Modern standard).
    API Style Template-based (Method-heavy). Functional / Fluent API (Chainable).

    1. RestTemplate (Legacy/Standard)
    2. RestTemplate blocks the executing thread until the response is received. It is simple to use for traditional applications where high concurrency is not a primary concern.

      Example Usage:
    3. WebClient (Modern/Recommended)
    4. WebClient belongs to the WebFlux library but can be used in both synchronous and asynchronous applications. It supports streaming and is highly efficient under heavy load.

      Example Usage (Non-blocking):

      Example Usage (Synchronous/Blocking): If you are in a standard Spring Boot Web app but want to use WebClient synchronously, you can append .block():

      Why Switch to WebClient?
      • Future-Proof: Spring has officially placed RestTemplate in maintenance mode.
      • Functional API: The builder-style syntax is more readable and flexible
      • Error Handling: Provides better built-in mechanisms for retries and status code handling.

    Overview

    Spring WebFlux is a non-blocking, reactive-stack web framework introduced in Spring 5. It is designed to handle a massive number of concurrent connections with very few threads, unlike the traditional Spring MVC, which uses a "one thread per request" model.

    It is built on Project Reactor and uses reactive types like Mono (for 0–1 elements) and Flux (for 0–N elements).


    Key Comparison: Spring MVC vs. Spring WebFlux
    Feature Spring MVC Spring WebFlux
    Model Blocking / Synchronous. Non-blocking / Asynchronous.
    Stack Servlet API (Thread-per-request). Event-loop (Event-driven).
    Concurrency Limited by thread pool size. Highly scalable with fixed threads.
    Default Server Apache Tomcat. Netty.
    Data Types Imperative (List<T>, Object). Reactive (Mono<T>, Flux<T>).

    When to Use Reactive Programming

    Reactive programming introduces complexity in debugging and a steep learning curve. Therefore, it should only be used in specific scenarios:

    • High Concurrency: When your application needs to handle thousands of simultaneous connections without consuming massive amounts of RAM for thread stacks.
    • I/O Intensive Tasks: When your service spends a lot of time waiting for other services (Microservices) or slow database queries. Reactive programming allows the thread to perform other work while waiting for the I/O to complete.
    • Streaming Data: When you need to push data to clients in real-time (e.g., live stock tickers, chat applications, or telemetry data).
    • Limited Resources: When running in environments with constrained CPU and memory, as WebFlux utilizes resources more efficiently than blocking frameworks.
    When to Avoid It
    • If your application is a simple CRUD app with a small user base.
    • If you are using blocking drivers (like traditional JDBC for relational databases). Since the "chain" is only as strong as its weakest link, one blocking call in a reactive flow will block the entire event loop.
    • If your team is not experienced with functional programming and the Reactor API, as stack traces in reactive code are significantly harder to read.

    From The Same Category

    Laravel

    Browse FAQ's

    Flask

    Browse FAQ's

    ASP.NET

    Browse FAQ's

    Django

    Browse FAQ's

    DocsAllOver

    Where knowledge is just a click away ! DocsAllOver is a one-stop-shop for all your software programming needs, from beginner tutorials to advanced documentation

    Get In Touch

    We'd love to hear from you! Get in touch and let's collaborate on something great

    Copyright copyright © Docsallover - Your One Shop Stop For Documentation