Technical Interview Prep: Top Spring Boot Interview Questions & Concepts
Spring Boot is an open-source, Java-based framework built on top of the traditional Spring framework. It eliminates boilerplate XML/Java configurations and simplifies enterprise Java development through auto-configuration, embedded web servers, and opinionated starter dependencies.
1. Core Philosophy: Spring Framework vs. Spring Boot
Java offers cross-platform independence and automatic memory management via the JVM, but traditional Java web application setup requires extensive configuration. Spring Boot was created to solve this complexity.
### Real-Life Analogy: Unfurnished vs. Furnished Housing
- Traditional Spring: Renting an empty, unfurnished apartment. You receive a structured space, but you must manually buy, transport, and assemble the bed, tables, chairs, wardrobe, and appliances. If part sizes or assembly steps conflict, the setup breaks.
- Spring Boot: Renting a fully furnished luxury apartment. You walk in with your suitcase and immediately start living. It provides a pre-configured bed, plants, lighting, and utilities out of the box, while still allowing you to swap out furniture if needed.
Key Conceptual Differences
2. Fundamental Architectural Features & Starters
Spring Boot operates on four architectural pillars designed to streamline development:
- Auto-Configuration: Dynamically configures beans based on dependencies detected in your build file (
pom.xmlorbuild.gradle). - Spring Boot Starters: Curated dependency descriptors that bundle related libraries into single imports, eliminating version mismatch bugs.
- Actuator: Exposes production-ready monitoring endpoints (
/actuator/health,/actuator/metrics) without extra configuration. - Spring Initializr: A web tool (start.spring.io) to generate project skeletons pre-populated with chosen dependencies.
Common Spring Boot Starters
3. Application Bootstrapping & Deconstructing @SpringBootApplication
A Spring Boot application is driven by a main class decorated with @SpringBootApplication.
Complete Code Execution Example
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("/")
public String home() {
return "Hello, welcome to this website!";
}
}
Breakdown of @SpringBootApplication
The @SpringBootApplication annotation is a meta-annotation that combines three core Spring annotations:
@Configuration: Marks the class as a source of bean definitions for the application context.@EnableAutoConfiguration: Instructs Spring Boot to start adding beans based on class-path settings, other beans, and various property settings.@ComponentScan: Tells Spring to scan the current package and its sub-packages for Spring components (Controllers, Services, Repositories).
Equivalent explicit configuration without @SpringBootApplication:
@Configuration
@EnableAutoConfiguration
@ComponentScan
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
4. Externalized Configuration & Environment Tuning
Spring Boot allows developers to externalize configuration settings using application.properties or application.yml. This decouples environment-specific settings (database URLs, passwords, server ports) from source code.
Changing Server Port Dynamically
To run the application on port 8081 instead of default 8080, update application.properties:
server.port=8081
Property Injection with @Value
You can inject values directly from configuration files into Spring components using @Value("${property.key}").
src/main/resources/application.properties
person.name=Rose
Controller Implementation
package com.example.demo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ProfileController {
@Value("${person.name}")
private String personName;
@GetMapping("/greet")
public String greet() {
return "Hello " + personName + ", welcome to this website!";
}
}
Format Comparison: Properties vs. YAML
Spring Boot natively supports both .properties and .yml (YAML) formats. YAML provides hierarchical structures that reduce repetitive prefixes.
Application Properties Standard
spring.application.name=demo-app
server.port=8080
management.endpoints.web.exposure.include=health,metrics
person.name=Rose
Equivalent YAML Configuration (application.yml)
spring:
application:
name: demo-app
server:
port: 8080
management:
endpoints:
web:
exposure:
include: "health,metrics"
person:
name: Rose
5. Developer Experience, Observability & Embedded Servers
Spring Boot DevTools
During local development, modifying Java source files usually requires manually stopping the server, rebuilding, and running the application again. Adding spring-boot-devtools enables:
- Automatic Restart: Automatically restarts the application context whenever files on the classpath are modified.
- LiveReload: Triggers a browser refresh whenever static resources (HTML, CSS, JS) are modified.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-devtools</artifactId>
<scope>runtime</scope>
</dependency>
Embedded Web Servers
Spring Boot applications package web servers inside the application artifact itself.
- Default Server: Apache Tomcat (
spring-boot-starter-webautomatically bundles Tomcat). - Alternatives: Jetty or Undertow (can be swapped in by excluding Tomcat from the starter POM).
Spring Boot Actuator
### Real-Life Analogy: Car Dashboard
A car dashboard displays critical metrics (speed, fuel gauge, oil pressure, engine fault lights) at a glance without requiring you to open the engine block. Spring Boot Actuator provides the same operational visibility for running applications.
Setup & Usage
- Add the starter dependency:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
- Expose health and metrics endpoints in
application.properties:
management.endpoints.web.exposure.include=health,metrics
- Accessing metrics:
- URL:
http://localhost:8080/actuator/health - JSON Response:
JSON
{ "status": "UP" }
- URL:
In production, tools like Prometheus scrape these endpoints to generate real-time metrics dashboards in Grafana.
6. Component Stereotypes & Dependency Injection Architecture
Spring uses stereotype annotations to designate Java classes for core tasks like web handling, business logic, and database access.
Stereotype Breakdown
### Real-Life Analogy: E-Commerce Store Architecture
@Component: Utility function that generates random order tracking numbers.@Service: Shopping Cart Engine calculating discounts, taxes, and final order totals.@Repository: Database Data Access Object reading and saving records to PostgreSQL or MySQL tables.@RestController: Store Checkout API receiving "Click Buy" HTTP requests from the mobile app and returning confirmation JSON.
Auto-Configuration Mechanic: Road Trip Analogy
- Manual Setup: You plan a road trip manually by researching car rentals, mapping every stop on a paper map, buying individual road snacks, and assembling custom playlists.
@EnableAutoConfiguration: You press a button on a personal assistant bot that checks your preferences, rents a car, maps the optimal route via GPS, and queues dynamic playlists based on who is in the car—setting up everything automatically based on available context.
Dependency Version Management via Starter Parent
Spring Boot projects inherit default configuration settings from spring-boot-starter-parent:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.0</version>
</parent>
Benefits:
- Configures default dependency version matrices to ensure all bundled libraries are compatible.
- Pre-configures Java source/target compilation versions (e.g., Java 17).
- Pre-configures resource filtering and plugin execution builds.
7. Building RESTful Web Services & Persistence
Creating a RESTful Service (Hands-On Execution)
The following example shows how to build an in-memory REST API using Spring Boot with GET and POST mappings.
1. Domain Model (Book.java)
package com.example.demo;
public class Book {
private Long id;
private String title;
private String author;
public Book() {}
public Book(Long id, String title, String author) {
this.id = id;
this.title = title;
this.author = author;
}
public Long getId() { return id; }
public void setId(Long id) { this.id = id; }
public String getTitle() { return title; }
public void setTitle(String title) { this.title = title; }
public String getAuthor() { return author; }
public void setAuthor(String author) { this.author = author; }
}
2. REST Controller (BookController.java)
package com.example.demo;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/books")
public class BookController {
private final List<Book> books = new ArrayList<>();
@GetMapping
public List<Book> getAllBooks() {
return books;
}
@PostMapping
public Book addBook(@RequestBody Book book) {
books.add(book);
return book;
}
}
HTTP Request Verification Flow (Postman / cURL)
POST Request Payload:
POST http://localhost:8080/books
{
"id": 1,
"title": "Before the Coffee Gets Cold",
"author": "Toshikazu Kawaguchi"
}
GET Request Response:
GET http://localhost:8080/books
[
{
"id": 1,
"title": "Before the Coffee Gets Cold",
"author": "Toshikazu Kawaguchi"
}
]
Database Persistence & @Entity
When working with databases using JPA, the @Entity annotation maps a Java class directly to a database table.
### Real-Life Analogy: Movie Poster
A movie poster is not the actual video stream, but a structured layout that details title metadata, release year, cast members, and runtime formatting. Similarly, an @Entity class defines database schema metadata (table name, column maps, primary keys) without serving as the literal database engine itself.
package com.example.demo;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
@Entity
public class BookEntity {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
private String author;
// Constructors, Getters, and Setters
}
8. Global Exception Handling Pattern
Rather than writing fragmented try-catch blocks across every controller, Spring Boot provides a unified, centralized exception handling strategy using @RestControllerAdvice and @ExceptionHandler.
Implementation Example
1. Custom Error Record Payload
package com.example.demo;
public record CustomErrorResponse(
String message,
String details,
boolean status
) {}
2. Global Exception Handler Controller Advice
package com.example.demo;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.WebRequest;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
public ResponseEntity<CustomErrorResponse> handleGlobalException(
Exception ex, WebRequest request) {
CustomErrorResponse errorDetails = new CustomErrorResponse(
"Something went wrong: " + ex.getMessage(),
request.getDescription(false), // Suppress credentials and sensitive data details
false
);
return new ResponseEntity<>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
9. Packaging, Deployment & Application Security Strategies
Packaging Strategies
Spring Boot supports multiple packaging strategies tailored to modern deployment requirements.
### Real-Life Analogy: Relocating to a New House
- Executable JAR (Suitcase): Packing lightweight personal items into a single suitcase when moving locally. Contains your compiled code and an embedded Tomcat server; run anywhere Java is installed via
java -jar app.jar. - Executable WAR (Moving Van): Hiring a large moving truck when relocating heavily furnished rooms to an external platform. Requires deploying your application to an external web application server (e.g., wildfly, standalone Tomcat).
- Docker Image (Freight Shipping Container): Placing your entire furnished apartment inside an isolated shipping container. Packages the application along with the OS layer, system dependencies, and Java runtime environment for consistent deployment across any cloud target.
- Native Image (Lightweight Backpack): Compiling Java code ahead-of-time (AOT) into binary machine code via GraalVM. Eliminates JVM startup overhead, acting like a lightweight run-and-go backpack built for extreme startup speed and low memory footprint.
Application Security Fundamentals
Securing enterprise Spring Boot applications requires a defensive, multi-layered approach:
- Authentication: Verifies user identity using
spring-boot-starter-securityforms, basic authentication, or OAuth2 log-in flows. - Authorization: Controls access based on user roles (e.g., ensuring standard users cannot access
/adminendpoints). - Data Protection: Enforces HTTPS connections and uses BCrypt hashing to encrypt passwords stored in databases.
- Session Management: Uses JSON Web Tokens (JWT) with configurable expiration windows to ensure session termination.
10. Spring Boot Testing Ecosystem
Spring Boot simplifies writing both isolated unit tests and end-to-end integration tests using JUnit and Mockito.
Testing Annotations Overview
package com.example.demo;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import static org.junit.jupiter.api.Assertions.assertNotNull;
@SpringBootTest
class DemoApplicationTests {
@Autowired
private HelloController controller;
@Test
void contextLoads() {
assertNotNull(controller, "The controller context should be loaded!");
}
}
Summary and Key Takeaways
- Spring Boot Philosophy: Spring Boot simplifies complex Java enterprise application setup by replacing manual boilerplate XML configurations with opinionated default setups, auto-configuration, and curated starter dependencies.
- Auto-Configuration Mechanic: Uses
@EnableAutoConfigurationto inspect class-path libraries and automatically register corresponding Spring beans without manual intervention. - Meta-Annotation Composition:
@SpringBootApplicationcombines@Configuration,@EnableAutoConfiguration, and@ComponentScaninto a single root entry point. - Starter Modules: Curated starter dependencies (e.g.,
spring-boot-starter-web,spring-boot-starter-data-jpa) eliminate dependency version conflicts by managing tested library matrices underspring-boot-starter-parent. - Embedded Servers: Applications compile with built-in application servers (Tomcat, Jetty, or Undertow), allowing them to run as standalone JAR files via
java -jar. - Externalized Configuration: Behavior, database credentials, and server ports can be modified dynamically via
application.propertiesor structuredapplication.ymlfiles, or injected directly using@Value. - Operational Visibility: Spring Boot Actuator exposes metrics and health check endpoints (
/actuator/health), enabling seamless monitoring via tools like Prometheus and Grafana. - Centralized Exception Handling: Real-world REST APIs use
@RestControllerAdviceand@ExceptionHandlerannotations to catch errors globally and return formatted JSON error payloads. - Deployment Options: Applications can be packaged as standalone JARs, enterprise WARs, containerized Docker images, or native GraalVM binaries based on performance and infrastructure needs.
- Testing Architecture: Supports automated testing using
@SpringBootTestfor integration tests,@DataJpaTestfor database operations, and@MockBeanfor isolating individual components.