DEV Community

kundan kumar
kundan kumar

Posted on

1.Spring Boot Core & Basics

Demystifying Spring Boot Core & Basics: The Ultimate Deep-Dive Interview Guide

Whether you are preparing for a senior engineering interview or architecting modern enterprise systems, Spring Boot Core & Basics is the foundational filter interviewers use to distinguish developers who merely use annotations from those who understand the framework's runtime mechanics.

1. What is Spring Boot, and how is it different from the Spring Framework?

The Core Philosophy

The traditional Spring Framework is an enterprise-grade Inversion of Control (IoC) and Dependency Injection (DI) framework. While modular and expressive, Spring historically suffered from configuration overhead: developers had to manually wire database drivers, dispatchers, template engines, and transaction managers through hundreds of lines of XML or verbose @Configuration classes, package them as WAR files, and deploy them to external servlet containers.

Spring Boot is not an alternative to the Spring Framework; it is an opinionated, rapid-application-development platform built directly on top of Spring. It provides automatic configuration, production-grade observability, curated dependency sets, and embedded servers to turn multi-day setup pipelines into seconds.

Architectural Comparison

Dimension Spring Framework Spring Boot
Primary Goal Provides core DI, IoC, AOP, and modular enterprise capabilities. Eliminates boilerplate configuration and accelerates bootstrapping.
Configuration Model Explicit configuration: Developers must define every DataSource, DispatcherServlet, and ViewResolver manually. Convention over Configuration: Applies opinionated defaults automatically via @EnableAutoConfiguration.
Server & Deployment Requires an external application server (Tomcat, Jetty, WildFly). Deployed as a WAR. Contains an embedded servlet container (Tomcat/Jetty/Undertow). Deployed as an executable fat JAR.
Dependency Management Manual specification of every library and transitive version; high risk of version conflicts (JAR Hell). Uses Starters and a centralized Bill of Materials (BOM) to eliminate version incompatibilities.
Production Readiness Requires custom code or third-party libraries for health checks, metrics, and application telemetry. Native Actuator endpoints out of the box (/health, /metrics, /prometheus).
Bootstrap Entry Point web.xml or WebApplicationInitializer mapped inside an external container. Standard Java public static void main(String[] args) method invoking SpringApplication.run().

Interview Tip: Emphasize that Spring Boot does not generate code or replace Spring APIs. At runtime, it configures the exact same Spring beans you would have configured manually, using conditional evaluation (@Conditional).


2. What are the advantages of using Spring Boot?

When an interviewer asks for advantages, avoid generic phrases like "it's fast." Group your response into structural architectural pillars:

  1. Auto-Configuration (@EnableAutoConfiguration): Analyzes the classpath, system properties, and existing bean definitions to automatically wire the ApplicationContext without boilerplate code.
  2. Curated Starters (spring-boot-starter-*): Single, cohesive dependencies that aggregate compatible transitive libraries tested against a verified BOM.
  3. Embedded Web Servers: Bundles Apache Tomcat, Jetty, or Undertow directly into the application archive. No external container configuration or installation is required.
  4. Production-Ready Observability via Actuator: Provides operational insights (metrics, health indicators, thread dumps, loggers, env variables) via secure HTTP/JMX endpoints.
  5. Zero Code Generation & Zero XML: Relies entirely on runtime reflection, dynamic proxies, and Java metadata. No XML parsing bottlenecks or code synthesis steps.
  6. Cloud-Native & Container Ergonomics: Built-in support for Docker Layered JARs, Cloud-Native Buildpacks, Graceful Shutdown, and GraalVM Ahead-Of-Time (AOT) compilation for near-instant native startup.

3. What is the purpose of the @SpringBootApplication annotation?

@SpringBootApplication is the primary meta-annotation placed on the root bootstrap class. It serves as the unified entry point that activates Spring Boot’s auto-configuration engine, initiates component scanning, and defines the root configuration class.

@SpringBootApplication
public class InventoryServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(InventoryServiceApplication.class, args);
    }
}
Enter fullscreen mode Exit fullscreen mode

Key Attributes Interviewers Expect You to Know:

  • scanBasePackages / scanBasePackageClasses: Overrides the default component scan root package.
  • exclude / excludeName: Excludes specific auto-configuration classes (e.g., exclude = {DataSourceAutoConfiguration.class}).
  • proxyBeanMethods (inherited from @SpringBootConfiguration): Controls whether @Bean methods inside the class are wrapped in CGLIB dynamic proxies to enforce singleton lifecycle semantics (defaults to true).

4. Which annotations does @SpringBootApplication combine internally?

@SpringBootApplication is composed of three fundamental annotations (the "Spring Boot Trinity"):

1. @SpringBootConfiguration

A specialization of Spring's standard @Configuration. It marks the class as a source of bean definitions for the ApplicationContext. The distinction is that @SpringBootConfiguration allows Spring's testing infrastructure (@SpringBootTest) to automatically locate the primary configuration root.

2. @EnableAutoConfiguration

Enables Spring Boot's auto-configuration discovery mechanism. Under the hood, it imports AutoConfigurationImportSelector, which reads auto-configuration candidates from:

  • META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports (Spring Boot 3.x)
  • META-INF/spring.factories (Spring Boot 2.x)

3. @ComponentScan

Directs Spring to scan for classes annotated with @Component, @Service, @Repository, @Controller, and @RestController. By default, scanning starts from the package of the annotated class and scans downward through all sub-packages.


5. What is the role of the SpringApplication.run() method?

SpringApplication.run() is not just a helper method; it is the orchestrator of the entire application bootstrap pipeline.

ConfigurableApplicationContext context = SpringApplication.run(MyApplication.class, args);
Enter fullscreen mode Exit fullscreen mode

Step-by-Step Execution Sequence

  1. Instantiation of SpringApplication:
    • Deduces the application type: WebApplicationType.SERVLET, REACTIVE, or NONE (batch/worker) based on classpath markers.
    • Loads BootstrapRegistryInitializer and ApplicationContextInitializer candidates.
    • Loads ApplicationListener instances from imports.
    • Determines the main application entry-point class.
  2. Environment Preparation:
    • Creates the ConfigurableEnvironment (resolving OS environment variables, JVM system properties, command-line arguments, and application.yml/.properties).
    • Binds the environment to the Spring application.
  3. Banner Printing: Prints the ASCII art banner unless explicitly suppressed (Banner.Mode.OFF).
  4. Context Creation:
    • Instantiates the matching ApplicationContext (e.g., AnnotationConfigServletWebServerApplicationContext for servlet-based web apps).
  5. Context Preparation:
    • Applies initializers, attaches the prepared environment, registers command-line arguments, and fires the ApplicationEnvironmentPreparedEvent.
  6. Context Refresh (The Core Step):
    • Executes refresh() from AbstractApplicationContext.
    • Evaluates BeanFactoryPostProcessors, registers BeanPostProcessors.
    • Starts the embedded web server (e.g., binds Tomcat to port 8080).
    • Eagerly instantiates all singleton beans.
  7. Post-Refresh & Runner Execution:
    • Locates and invokes all beans implementing ApplicationRunner and CommandLineRunner.
  8. Event Publication: Publishes the ApplicationReadyEvent. The application is now fully initialized.

6. What is the significance of the main method in a Spring Boot application?

In traditional Java EE architectures, the servlet container was the host process: Tomcat started first, parsed web.xml, and loaded the application WAR into its memory space.

In Spring Boot, this model is inverted (Inversion of Deployment):

  • The Java main method is the driver of the entire operating system process.
  • The application runs as a standalone Java process (java -jar my-service.jar).
  • The embedded Tomcat/Jetty server is treated as an internal Spring bean inside the ApplicationContext rather than an external supervisor.

question6

When packaged as an executable Fat JAR, the Main-Class entry in META-INF/MANIFEST.MF points to Spring Boot's internal loader class: org.springframework.boot.loader.launch.JarLauncher. This launcher sets up an isolated class loader capable of reading nested JARs and finally delegates execution to your application's main() method.


7. Explain the concept of "opinionated defaults" in Spring Boot.

"Opinionated Defaults" embodies the Convention over Configuration pattern. Spring Boot makes educated, opinionated assumptions about how a modern production backend should be constructed, providing pre-configured sensible defaults:

  • Default Server: Assumes you need Apache Tomcat listening on port 8080.
  • Default Database Connection Pool: Assumes HikariCP is the best connection pool for performance.
  • Default JSON Parser: Assumes Jackson (ObjectMapper) is the serialization engine.
  • Default Logging Engine: Assumes SLF4J with Logback, pre-configured for console output with ANSI color-coding and timestamp formatting.
  • Default ORM Provider: Assumes Hibernate when Spring Data JPA is present.

The "Escape Hatch" Principle

Spring Boot is opinionated, but not stubborn. Every single default can be overridden. If you define your own custom bean, Spring Boot's conditional logic (@ConditionalOnMissingBean) detects it and steps back.


8. What is the difference between Spring Boot and Spring MVC?

This is one of the most frequently asked basic questions in junior to mid-level interviews. Many developers confuse the two because spring-boot-starter-web pulls in Spring MVC.

Tabular Comparison

Dimension Spring MVC Spring Boot
Framework Type Presentation-tier Web & REST framework. Application bootstrapping and auto-configuration framework.
Architectural Scope Focuses strictly on HTTP handling: DispatcherServlet, Controllers, Request Mappings, and Model/View binding. Focuses on the entire application lifecycle: dependency packaging, configuration, metrics, embedded runtimes, and persistence wiring.
Servlet Setup Requires manual registration of DispatcherServlet in web.xml or via WebApplicationInitializer. Automatically creates, configures, and registers DispatcherServlet at / out of the box.
Server Requirement Cannot run on its own; must be deployed onto an external servlet container (Tomcat, Jetty). Runs independently as a standalone JVM process using an embedded web server.
Relation to Each Other Built within the core Spring Framework. Packages, auto-configures, and manages Spring MVC via spring-boot-starter-web.

9. What are the different ways to create a Spring Boot application?

There are 4 standard mechanisms to scaffold a Spring Boot application:

  1. Spring Initializr Web UI (start.spring.io): The official web generator allowing developers to select build tools (Maven/Gradle), language (Java/Kotlin/Groovy), Spring Boot version, packaging (JAR/WAR), Java baseline, and dependencies.
  2. IDE Built-in Wizards: IntelliJ IDEA Ultimate, Eclipse (STS - Spring Tool Suite), and VS Code (Spring Boot Extension Pack) integrate directly with the Spring Initializr API.
  3. Spring Boot CLI (spring init): A terminal-based tool enabling fast CLI scaffolding (e.g., spring init -d=web,data-jpa --build=gradle my-app).
  4. Manual Build Configuration: Writing a pom.xml or build.gradle file manually by adding spring-boot-starter-parent and desired starters, then creating a @SpringBootApplication entry point.

10. What is Spring Initializr, and how do you use it?

Spring Initializr is an extensible web service and open-source project (spring-io/initializr) that generates the skeleton structure for Spring Boot applications.

How it Works Internally

Initializr exposes a RESTful metadata API endpoint at https://start.spring.io. When you interact with the UI, IDE, or CLI, it sends an HTTP GET/POST request with query parameters describing the project requirements. The service returns a dynamically assembled .zip archive containing:

  • Standard Maven/Gradle directory structure (src/main/java, src/main/resources, src/test/java).
  • Pre-configured pom.xml or build.gradle containing correct starters and BOM definitions.
  • Maven Wrapper (mvnw, .mvn/) or Gradle Wrapper (gradlew) to ensure consistent builds without local tool installations.
  • Default application.properties or application.yml.
  • A baseline @SpringBootApplication class and a passing context-load test.

Using Spring Initializr via cURL

curl https://start.spring.io/starter.zip \
  -d dependencies=web,data-jpa,postgresql \
  -d javaVersion=21 \
  -d bootVersion=3.3.0 \
  -d artifactId=order-service \
  -d name=order-service \
  -o order-service.zip && unzip order-service.zip
Enter fullscreen mode Exit fullscreen mode

11. What is the minimum Java version required for Spring Boot 3.x?

Direct Answer

The minimum requirement for Spring Boot 3.x is Java 17 LTS.

Deep Architectural Rationale (Senior Interview Perspective)

When interviewers ask this question, they are testing whether you understand the structural ecosystem changes that occurred between Spring Boot 2.x and 3.x:

  1. Jakarta EE 9/10 Namespace Migration:
    • Oracle transferred Java EE to the Eclipse Foundation. Due to trademark restrictions on the javax name, all enterprise packages changed from javax.* to jakarta.* (e.g., jakarta.persistence, jakarta.servlet, jakarta.annotation).
    • Spring Boot 3 completely dropped support for javax.* web/persistence specifications.
  2. Modern Java Language Features in Framework Internals:
    • Spring Framework 6.x and Spring Boot 3.x internally leverage modern Java features including Java Records for immutable DTOs/projections, sealed classes, pattern matching, and enhanced switch expressions.
  3. GraalVM Native Image Compilation:
    • Spring Boot 3 introduced first-class Ahead-Of-Time (AOT) engine support powered by GraalVM. AOT requires Java 17+ bytecode semantics to generate optimized native binaries with sub-50ms startup times.
  4. Virtual Threads (Project Loom):
    • Beginning in Spring Boot 3.2+ (on Java 21 LTS), applications can execute high-throughput blocking I/O using lightweight Virtual Threads by setting a single property:
   spring.threads.virtual.enabled=true
Enter fullscreen mode Exit fullscreen mode

12. What are the key components of Spring Boot?

Spring Boot is constructed around five foundational subsystems:

  1. Spring Boot Starters: Curated dependency descriptors grouping functional dependencies under a unified version management umbrella.
  2. Auto-Configuration Engine: The conditional configuration subsystem driven by @EnableAutoConfiguration and @Conditional* annotations.
  3. Spring Boot Actuator: The operations management module exposing runtime telemetry, health indicators, audit hooks, and metric scrapers.
  4. Spring Boot DevTools: The developer productivity engine providing classloader-isolated live reloads, automatic server restarts, and cache invalidation during development.
  5. Spring Boot CLI: The command-line interface leveraging Groovy and Grape for rapid prototyping and executable scripting.

13. What is spring-boot-starter-parent and why is it used?

spring-boot-starter-parent is a special parent POM in Maven that enterprise applications can inherit from to establish a standardized build and runtime baseline.

What It Configures Under the Hood:

  1. Centralized Dependency Management: Inherits from spring-boot-dependencies (the master BOM). It manages compatible versions for over 200 common third-party libraries (Hibernate, Jackson, Logback, Mockito, etc.). You do not need to specify <version> tags in your own dependencies.
  2. Default Compiler Configuration: Sets default Java version source/target flags and enforces UTF-8 character encoding.
  3. Resource Filtering: Configures Maven resource filtering on application.properties and application.yml files, allowing property interpolation using the @..@ delimiter syntax (e.g., app.version=@project.version@).
  4. Plugin Configurations: Pre-configures plugins like spring-boot-maven-plugin, maven-surefire-plugin, and maven-failsafe-plugin with repackaging goals to produce executable fat JARs.

What if You Cannot Inherit from spring-boot-starter-parent?

Many enterprises require projects to inherit from an internal corporate parent POM (corp-parent-pom). In Maven, multiple inheritance is illegal.

The Solution: Import the BOM directly in the <dependencyManagement> section using scope=import:

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>3.3.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>
Enter fullscreen mode Exit fullscreen mode

14. How does Spring Boot simplify dependency management?

Traditional Java projects frequently suffer from "JAR Hell"—runtime ClassNotFoundException or NoSuchMethodError caused by transitive dependency collisions (e.g., Library A pulls Jackson 2.12, while Library B pulls Jackson 2.15).

Spring Boot resolves this using a two-tier strategy:

1. Bill of Materials (BOM) Pattern

Through spring-boot-dependencies, the Spring team rigorously tests and curates an exact matrix of compatible versions across the entire Java backend ecosystem. When you declare dependencies:

<dependencies>
    <!-- Notice: NO <version> tag! -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

The version is automatically resolved to the exact compatible version defined by the BOM, completely eliminating manual version coordination.

2. Functional Aggregation (Starters)

Instead of searching for and adding separate dependencies for Spring Web, Tomcat, Jackson Core, Jackson Databind, and Jakarta Validation, you add one starter: spring-boot-starter-web. The starter brings in the entire cohesive stack.


15. What is the Spring Boot CLI and what can you do with it?

The Spring Boot CLI is a lightweight command-line interface designed for rapid prototyping, system automation, and script execution using Groovy.

Key Capabilities:

  • Run Standalone Groovy Scripts (spring run): Allows you to write concise Groovy files without explicit package declarations, imports, or build files. The CLI uses Groovy Grape (@Grab) to automatically resolve missing imports (like @RestController, @GetMapping) and download corresponding starters on the fly:
@RestController
class HelloController {
    @GetMapping("/")
    String home() {
        "Hello from Spring Boot CLI!"
    }
}
Enter fullscreen mode Exit fullscreen mode

Executing spring run HelloController.groovy compiles the script, downloads Spring Web, spins up an embedded Tomcat server, and serves the endpoint on port 8080.

  • Project Scaffolding (spring init): Generates new Spring Boot skeletons from the terminal:
spring init --dependencies=web,data-jpa --build=maven my-project
Enter fullscreen mode Exit fullscreen mode
  • Packaging Executables (spring jar): Packages Groovy scripts into standard executable fat JARs (spring jar app.jar HelloController.groovy).

series navigation

⬅️ Previous: Series Introduction & Roadmap
➡️ Next: Part 02 — Auto-Configuration & Configuration
📌 View the Complete Series Roadmap


Top comments (0)