Skip to content
Spring Boot Deep Dive: 9 Core Internals from Startup to Auto-Configuration for Interview Mastery

Spring Boot Deep Dive: 9 Core Internals from Startup to Auto-Configuration for Interview Mastery

This comprehensive technical guide dissects Spring Boot internals including startup flow, auto-configuration principles, Starter mechanism, configuration formats, Profile multi-environment setup, Actuator monitoring, global exception handling, Spring Boot 3.x features (Jakarta EE, Java 17, GraalVM native images), and Spring vs Spring Boot differences with source-code-level analysis and interview-focused insights.

Rain's Path to Java Mastery
Rain's Path to Java Mastery
Rain's Path to Java Mastery

Spring Boot Startup Process

The startup is essentially one main method + two core phases : environment preparation and container refresh. The SpringApplication.run() method executes a sequence:

SpringApplication.run()
    │
    ▼
┌─────────────────┐
│ 1. Infer app type │ → Servlet? Reactive? Standalone?
└────────┬────────┘
         ▼
┌─────────────────┐
│ 2. Load initializers & listeners │ → ApplicationContextInitializer, ApplicationListener
└────────┬────────┘
         ▼
┌─────────────────┐
│ 3. Prepare environment │ → Environment (config, profiles)
└────────┬────────┘
         ▼
┌─────────────────┐
│ 4. Create container │ → AnnotationConfigServletWebServerApplicationContext etc.
└────────┬────────┘
         ▼
┌─────────────────┐
│ 5. Prepare container │ → setEnvironment, applyInitializers
└────────┬────────┘
         ▼
┌─────────────────┐
│ 6. Refresh container 🔥 │ → AbstractApplicationContext.refresh() (the soul)
└────────┬────────┘
         ▼
┌─────────────────┐
│ 7. Start WebServer │ → Tomcat/Jetty/Undertow embedded start
└────────┬────────┘
         ▼
         [App started ✅]

Phase 1: SpringApplication Constructor

Infer application type : Checks classpath for DispatcherServlet (Servlet web), DispatcherHandler without DispatcherServlet (Reactive web), or neither (standalone). This determines which ApplicationContext to create.

Load initializers : Via SpringFactoriesLoader from META-INF/spring.factories for ApplicationContextInitializer.

Load listeners : Same mechanism for ApplicationListener.

Deduce main class : Uses stack trace to find the class containing main.

Phase 2: run() Method Execution

Start timing : StopWatch for startup duration.

Configure headless mode : Sets java.awt.headless=true for server environments.

Get run listeners : Loads SpringApplicationRunListener for event publishing.

Prepare environment : Loads application.yml, system properties, environment variables.

Print Banner : The Spring Boot ASCII logo.

Create ApplicationContext : Based on inferred app type.

Prepare container : Injects environment, listeners, initializers.

Execute refresh() : Core step — bean scanning, parsing, instantiation, initialization.

Execute hook methods : Calls CommandLineRunner and ApplicationRunner.

Publish ready event : Signals full startup success.

refresh() Internal Steps

refresh()
├─ prepareRefresh()              // Prepare context (record start time, validate required props)
├─ obtainFreshBeanFactory()      // Parse config classes, scan packages, load all bean definitions
├─ prepareBeanFactory()          // Register special beans (environment, systemProperties)
├─ invokeBeanFactoryPostProcessors() // 💥 Execute BeanFactoryPostProcessors (incl. ConfigurationClassPostProcessor)
├─ registerBeanPostProcessors()  // Register BeanPostProcessors (AOP, auto-proxy hooks)
├─ initMessageSource()           // Internationalization
├─ initApplicationEventMulticaster() // Event broadcaster
├─ onRefresh()                   // 👉 Hook for subclasses: embedded web container created here
├─ registerListeners()           // Register listeners
├─ finishBeanFactoryInitialization() // 💥 Singleton pool init (all non-lazy singletons created)
└─ finishRefresh()               // Clear caches, start WebServer, publish ContextRefreshedEvent

Key points: ConfigurationClassPostProcessor parses @Configuration, @ComponentScan, @Bean etc., registering all bean definitions. onRefresh() in ServletWebServerApplicationContext creates the web server factory, started at the end. finishBeanFactoryInitialization() is a high-frequency interview area — all business singleton beans' dependency injection and initialization happen here (via getBean() triggering three-level cache for circular dependencies).

Spring Boot Auto-Configuration Principle

Auto-configuration is the core feature enabling "convention over configuration" . Entry point is @SpringBootApplication, a composite annotation:

@SpringBootConfiguration // essentially @Configuration
@EnableAutoConfiguration // 🚀 auto-configuration switch
@ComponentScan           // component scanning
@EnableAutoConfiguration

uses @Import(AutoConfigurationImportSelector.class) to bring in the "dispatcher" class.

Auto-Configuration Flow

Load candidate configurations : AutoConfigurationImportSelector uses SpringFactoriesLoader to read all META-INF/spring.factories (or AutoConfiguration.imports in 3.x) under key

org.springframework.boot.autoconfigure.EnableAutoConfiguration

. Hundreds of XXXAutoConfiguration classes from spring-boot-autoconfigure jar.

Conditional filtering ⚖️: Candidates are not all activated. Spring Boot uses conditional annotations: @ConditionalOnClass — class present on classpath (e.g., HikariCP for DataSource) @ConditionalOnMissingBean — bean absent in container (user-defined wins) @ConditionalOnProperty — property exists in config @ConditionalOnWebApplication — is a web app

Auto-register beans : Remaining config classes treated as regular @Configuration; their @Bean methods execute, registering components (DataSource, RabbitTemplate, RedisTemplate).

Real Example: DataSourceAutoConfiguration

Annotated with

@ConditionalOnClass({ DataSource.class, EmbeddedDatabaseType.class })

— requires these classes on classpath.

Internally checks connection pool type; creates HikariDataSource if HikariCP present.

Uses @ConditionalOnMissingBean so user-defined DataSource takes precedence.

Extending/Disabling Auto-Configuration

Exclude specific:

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class)

Full control: set spring.autoconfigure.exclude property list.

Custom starter: write own META-INF/spring.factories (or AutoConfiguration.imports) with conditional annotations.

Three Core Components

Conditional Annotations — Decide which config classes load. Key: @ConditionalOnClass, @ConditionalOnMissingBean, @ConditionalOnProperty.

SPI Mechanism — Scan all jars for auto-config classes. Key file:

META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports

.

Configuration Binding — Bind application.yml props to JavaBeans. Key: @ConfigurationProperties, @EnableConfigurationProperties.

Interview Bonus Points

Auto-config load order: @AutoConfigureBefore, @AutoConfigureAfter, @AutoConfigureOrder.

Exclude auto-config: @SpringBootApplication(exclude=...).

Debug report: start with --debug to see which auto-configs matched/excluded.

Spring Boot 3.x change: SPI file moved from spring.factories to AutoConfiguration.imports (one class per line, better performance).

Spring Boot Starter Mechanism

Starter = "one dependency import + auto-configuration" module packaging. Solves traditional Spring's "dependency hell" and "verbose configuration".

Core Mechanism: Dependency Management + Auto-Configuration + Conditional Assembly

When starter jar is on classpath, Spring Boot loads auto-config classes via spring.factories (2.x) or AutoConfiguration.imports (3.x), evaluates @Conditional annotations, and injects default beans if conditions met.

Key Annotations

@SpringBootApplication

— Bootstrap annotation combining @Configuration + @EnableAutoConfiguration + @ComponentScan. @EnableAutoConfiguration — Enable auto-config. Core! Loads all auto-config classes via SpringFactoriesLoader. @Conditional series — Conditional assembly. Only create bean when specific conditions satisfied.

Most Used Conditionals

@ConditionalOnClass

: class present on classpath @ConditionalOnMissingBean: bean absent in container @ConditionalOnProperty: property exists in config @ConditionalOnWebApplication: web environment

Dependency Mediation & Version Arbitration

Each starter is often an empty jar; its pom.xml pulls related dependencies, versions managed by Spring Boot's parent POM to avoid conflicts.

Auto-Configuration Loading Entry

Legacy (2.x) : META-INF/spring.factories key

org.springframework.boot.autoconfigure.EnableAutoConfiguration

.

Modern (2.7+, 3.0 default) :

META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports

— one fully-qualified class name per line. @EnableAutoConfiguration triggers AutoConfigurationImportSelector to read these files, yielding candidate config classes.

Conditional Assembly (@Conditional Series) ⭐

Ensures "supply what's missing, don't conflict if present": @ConditionalOnClass: type present (e.g., DataSource on classpath → configure datasource) @ConditionalOnMissingBean: user hasn't defined bean → use default @ConditionalOnProperty: config property present → activate @ConditionalOnBean: specific bean exists → assemble

Configuration Properties Binding

@ConfigurationProperties

maps application.yml prefixed properties to a bean, activated by @EnableConfigurationProperties.

Custom Starter Standard Structure

xxx-spring-boot-starter (launcher, empty jar, dependency management only)
└── pom.xml (depends on xxx-spring-boot-autoconfigure)

xxx-spring-boot-autoconfigure (auto-config core)
├── src/main/java
│   └── com/xxx/autoconfigure
│       ├── XxxAutoConfiguration.java (auto-config class)
│       └── XxxProperties.java (config properties binding)
└── src/main/resources
    └── META-INF
        └── spring.factories (register auto-config class)

Best practice: separate auto-config and starter modules so others can depend on auto-config directly for extension.

Official Common Starters Cheat Sheet

Web : spring-boot-starter-web (Tomcat + Spring MVC), spring-boot-starter-webflux (Reactive, Netty)

Data : spring-boot-starter-data-jpa (JPA+Hibernate), spring-boot-starter-jdbc (JDBC+HikariCP), spring-boot-starter-data-redis (Redis, Lettuce), spring-boot-starter-data-mongodb (MongoDB)

Messaging : spring-boot-starter-amqp (RabbitMQ), spring-boot-starter-kafka (Kafka)

Security : spring-boot-starter-security Test : spring-boot-starter-test Monitoring : spring-boot-starter-actuator Template : spring-boot-starter-thymeleaf Utility : spring-boot-starter-validation (Bean Validation), spring-boot-starter-mail, spring-boot-starter-cache (Caffeine/Redis)

High-Frequency Interview Follow-ups

Starter vs AutoConfiguration?

Starter = dependency descriptor, only pulls jars.

AutoConfiguration = auto-config logic, creates beans.

One starter can contain multiple AutoConfigurations.

How does Spring Boot resolve auto-config conflicts?

@ConditionalOnMissingBean

ensures user beans win. @AutoConfigureBefore / After control order. exclude property to disable unwanted auto-configs.

Spring Boot 3.x Starter Changes?

Deprecated spring.factories.

Uses

META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports

.

One config class per line, better performance.

Spring Boot Configuration: application.properties vs application.yml

Core Syntax Comparison

Syntax : properties = flat key=value, dot-separated; yml = YAML indentation, tree structure.

Example : properties: server.port=8080; yml:

server:
  port: 8080

Readability : properties poor for deep hierarchies; yml excellent.

Comments : both support # single-line only.

Whitespace sensitive : properties no; yml yes (must use 2 spaces, no tabs).

Colon spacing : properties not required; yml required ( key: value).

Deep Differences

Collections & Complex Structures

Properties simulates lists with indices, hard to read:

my.servers[0]=dev.example.com
my.servers[1]=prod.example.com

YAML natively supports lists and nesting:

my:
  servers:
    - dev.example.com
    - prod.example.com

Multi-Document Merge

Spring Boot merges application.yml and application-{profile}.yml. A single YAML can use --- to separate multiple document blocks with spring.profiles:

server:
  port: 8080
---
spring:
  config:
    activate:
      on-profile: dev
  datasource:
    url: jdbc:mysql://localhost:3306/dev_db
---
spring:
  config:
    activate:
      on-profile: prod
  datasource:
    url: jdbc:mysql://prod-server:3306/prod_db

Loading Order & Priority

When both exist, properties has higher priority than yml and overrides same keys. Teams should agree on one format.

YAML Exclusive Advantages

Native list support (properties' fatal weakness).

Complex object nesting.

Multi-document blocks in one file.

Properties Advantages

Simple syntax, zero learning curve.

Mature IDE support (autocomplete, hints).

No formatting pitfalls (indentation errors).

Slightly higher load priority.

Priority & Execution Order

Low priority
  ↓
default (application.yml)
  ↓
profile-specific (application-{profile}.yml)
  ↓
Command-line args
  ↓
OS environment variables
High priority

Mnemonic: Command-line > Env vars > Profile files > Default file .

Common Pitfalls

YAML Pitfalls

Indentation hell : Must use 2 spaces, no tabs.

Special chars : Values containing :, #, & must be quoted.

Numeric auto-conversion : 0123 parsed as octal 83.

Boolean traps : on/off/yes/no auto-converted to true/false.

Properties Pitfalls

No list support: comma-separated strings, manual parsing in code.

Repeated prefixes for complex configs.

Hierarchy unclear beyond 3 levels.

Enterprise Best Practices

Use YAML as primary config: clear structure, powerful features.

Properties for simple cases: quick prototypes, temporary debugging.

Environment isolation: application.yml (common) + application-dev.yml / prod.yml (diffs only, minimal override).

Secrets: never hardcode; use env vars or config center.

Format standard: 2-space indent, colon + space.

Spring Boot Profile Multi-Environment Config & Activation

Core Purpose

Profile = environment isolation mechanism solving "one codebase, different configs for dev/test/prod". Three pillars: how to split config, how to activate, priority.

Configuration Methods

1. Multi-File (Most Common)

Naming:

application-{profile}.yml/properties
application.yml

— Main config, common across all envs. application-dev.yml — Development, local DB, debug logs. application-test.yml — Test, test server DB. application-prod.yml — Production, prod DB, info logs.

Structure:

src/main/resources
├── application.yml
├── application-dev.yml
├── application-prod.yml
└── application-test.yml

Key: application.yml holds common items; each profile file only contains differences, minimal override .

2. Single-File Multi-Document (YAML Only)

Use --- to separate envs in one application.yml:

# Common
spring:
  application:
    name: demo-app
---
# Dev
spring:
  config:
    activate:
      on-profile: dev
  datasource:
    url: jdbc:mysql://localhost:3306/dev_db
---
# Prod
spring:
  config:
    activate:
      on-profile: prod
  datasource:
    url: jdbc:mysql://prod-server:3306/prod_db

3. Annotation-Based (Per Bean)

@Configuration
@Profile("dev") // Only loaded in dev
public class DevConfig {
    // Dev-only beans
}

Activation Methods (Low → High Priority)

Config file (lowest): spring.profiles.active=dev in application.yml.

JVM system property : java -Dspring.profiles.active=test -jar app.jar.

Command-line arg (most common): java -jar app.jar --spring.profiles.active=prod.

OS environment variable : export SPRING_PROFILES_ACTIVE=prod (Linux/Mac) or set SPRING_PROFILES_ACTIVE=prod (Windows).

Maven build-time : Define profile in pom.xml with spring.profiles.active property, then mvn clean package -Pprod.

Example: application.yml port=8080, application-prod.yml port=8443, launch with --spring.profiles.active=prod --server.port=9090 → final port 9090 (command-line wins).

Advanced: @Profile + Grouping

Annotation controls bean loading: Different envs inject different implementations, cleaner than if-else.

Profile Groups (Spring Boot 2.4+): Activate multiple profiles at once, e.g., prod pulls cloud and mysql:

spring:
  profiles:
    group:
      prod: cloud, mysql
      dev: local, h2

Activating prod auto-activates cloud, mysql — one group activates multiple facets .

Advanced Features & Notes

Activate multiple: comma-separated --spring.profiles.active=dev,mysql.

Default profile: default if none specified.

Override rules: main config overridden by profile-specific; higher-priority activation overrides lower.

Production best practices: never hardcode spring.profiles.active in code; use command-line or env vars; keep secrets out of config files (use external config center).

Interview Summary

"Name defines config, param defines activation, annotation controls loading, grouping boosts efficiency."

📛 Split: application-{profile}.yml 🚀 Activate: spring.profiles.active (cmd, env, config)

🧩 Annotate: @Profile for conditional bean wiring

📦 Group: spring.profiles.group for multi-profile activation

Spring Boot Actuator Monitoring Endpoints

Core Role

Actuator provides production-grade monitoring and management via HTTP endpoints exposing internal runtime state — essential for microservice observability. Three layers: core endpoints, secure exposure, production patterns.

Endpoint Categories & Top 10

Native endpoints split into: Application Config (12), Metrics (18), Operations (5). /actuator/health (GET) — Health check, extensible via HealthIndicator. Enabled by default. ⚕️ "Is this service breathing?" /actuator/info (GET) — App info (custom), driven by info.* config. Enabled by default. ℹ️ "Which version, who wrote it?" /actuator/metrics (GET) — List all metrics (e.g., jvm.memory.used). Disabled by default. 📈 "CPU, memory, request counts all here" /actuator/metrics/{name} (GET) — Specific metric detail. Disabled by default. /actuator/env (GET) — View env vars & config. Disabled by default. 🌍 "Which profiles, what's the DB URL?" /actuator/beans (GET) — All Spring container beans. Disabled by default. 🫘 "What beans are in Spring?" /actuator/loggers (GET) — View all log levels. Disabled by default. 🪓 "No logs in prod?" /actuator/loggers/{name} (POST) — Dynamically change log level. Disabled by default. 🪓 "Prod too quiet? POST debug" /actuator/shutdown (POST) — Graceful shutdown. Disabled by default. /actuator/threaddump (GET) — Thread dump snapshot. Disabled by default. 🧵 "Stuck? Grab thread snapshot"

Core Configuration

Maven Dependency

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Key application.yml Config

management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics,loggers  # Expose these
        exclude: shutdown,env,beans           # Hide these
        base-path: /actuator                  # Base path
  endpoint:
    health:
      show-details: always                    # Show health details
    shutdown:
      enabled: true                           # Enable graceful shutdown

Security Control

Production must-dos:

Combine with Spring Security for endpoint authorization.

Expose only necessary endpoints; disable sensitive ones.

Change default /actuator base path.

Configure separate management port.

management:
  server:
    port: 9090  # Separate management port, isolated from business port

Exposure & Security — The 90% Overlook

Default rule: only health and info are exposed. All others return 404 unless explicitly included.

management:
  endpoints:
    web:
      exposure:
        include: "health,info"  # Default: only these two "harmless" endpoints

Common patterns: * expose all web endpoints ( production caution ). health,metrics,loggers on-demand.

Must combine with Spring Security for role protection, e.g.:

management:
  endpoint:
    health:
      show-details: when-authorized

Secure /actuator/** to ACTUATOR_ADMIN role only. Lesson learned: exposing env publicly leaks passwords/keys.

Production "Three-Piece Suite"

⚕️ Health Check Deep Customization

@Component
public class DatabaseHealthIndicator implements HealthIndicator {
    @Override
    public Health health() {
        boolean dbUp = checkDatabase();
        if (dbUp) {
            return Health.up().withDetail("latency", "10ms").build();
        }
        return Health.down().withDetail("error", "connection timeout").build();
    }
}

Accessing health shows custom details; integrates with K8s livenessProbe for Pod life/death decisions.

📈 Prometheus + Micrometer Metrics

Spring Boot 2.x+ bundles Micrometer. Add:

<dependency>
  <groupId>io.micrometer</groupId>
  <artifactId>micrometer-registry-prometheus</artifactId>
</dependency>

Expose /actuator/prometheus; Prometheus scrapes, Grafana dashboards ready .

🪓 Dynamic Log Rescue

Prod service logging too much, disk near full — one-second level change :

curl -X POST 'http://service/actuator/loggers/com.xxx' \
  -H 'Content-Type: application/json' \
  -d '{"configuredLevel":"ERROR"}'

No restart, no redeploy.

Custom Endpoints

When native endpoints insufficient:

@Component
@Endpoint(id = "custom")
public class CustomEndpoint {
    @ReadOperation
    public Map<String, Object> getCustomInfo() {
        Map<String, Object> result = new HashMap<>();
        result.put("appName", "My App");
        result.put("version", "1.0.0");
        result.put("timestamp", System.currentTimeMillis());
        return result;
    }
}

Access at /actuator/custom; add @WriteOperation for dynamic interventions.

Interview Bonus Points

Health check depth: custom HealthIndicator for fine-grained checks (DB, Redis, MQ).

Metrics integration: Actuator metrics → Prometheus+Grafana stack.

Distributed tracing: combine Sleuth + Zipkin for full-chain tracing.

Alerting: thresholds on health/metrics → alerts (email, DingTalk, WeCom).

"Actuator is the service's physical exam report, but you don't paste it on the front door for everyone to see."

Spring Boot Unified Exception Handling: @ControllerAdvice + @ExceptionHandler

Core Positioning

Solves "exceptions everywhere, inconsistent response formats" — global interception, unified handling, unified response. Business code stays clean; exception logic centralized.

Core Principle

@ControllerAdvice

: Essentially a Spring AOP global enhancer intercepting all Controller requests and exceptions. @ExceptionHandler: Method-level annotation declaring which exception type this method handles . @RestControllerAdvice: @ControllerAdvice + @ResponseBody combo; use directly for front-end separated projects.

Complete Flow

DispatcherServlet

(the "dispatcher") catches Controller-thrown exceptions, asks @ControllerAdvice for a matching handler method.

Standard Implementation (3 Steps)

1. Define Unified Response Class (Required)

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Result<T> {
    private int code;
    private String message;
    private T data;
    public static <T> Result<T> success(T data) {
        return new Result<>(200, "Success", data);
    }
    public static <T> Result<T> error(int code, String message) {
        return new Result<>(code, message, null);
    }
}

2. Define Global Exception Handler (Core)

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    // Custom business exception
    @ExceptionHandler(BusinessException.class)
    public Result<Void> handleBusinessException(BusinessException e) {
        log.error("Business exception: {}", e.getMessage(), e);
        return Result.error(e.getCode(), e.getMessage());
    }
    // Validation exception
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Void> handleValidException(MethodArgumentNotValidException e) {
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return Result.error(400, message);
    }
    // Catch-all for all other exceptions
    @ExceptionHandler(Exception.class)
    public Result<Void> handleException(Exception e) {
        log.error("System exception: ", e);
        return Result.error(500, "Internal server error, contact admin");
    }
}

3. Custom Business Exception (Strongly Recommended)

@Data
public class BusinessException extends RuntimeException {
    private int code;
    public BusinessException(int code, String message) {
        super(message);
        this.code = code;
    }
}

4. Controller Left with Clean Business Logic

@GetMapping("/order/{id}")
public ApiResult<Order> getOrder(@PathVariable Long id) {
    Order order = service.findById(id);
    if (order == null) {
        throw new BizException(404, "Order not found");
    }
    return ApiResult.success(order);
}

Advanced Usage (Interview Bonus)

Exception handler priority : Exact match > parent match; local @ExceptionHandler > global @ExceptionHandler.

Handle 404/405 container-level exceptions : Configure in application.yml:

spring:
  mvc:
    throw-exception-if-no-handler-found: true
  web:
    resources:
      add-mappings: false

Specify HTTP status : Add @ResponseStatus(HttpStatus.BAD_REQUEST) on handler method.

Log level differentiation : Business exceptions → warn; system exceptions → error + stack trace.

Hide stack traces in prod : Control via config whether detailed exception info returned.

Common Pitfalls

Interceptor/Filter exceptions not caught : @ControllerAdvice only intercepts Controller-layer exceptions. Solution: catch manually in filter & return JSON, or use ErrorController fallback.

404 never intercepted : Spring delegates static resources & 404 to container by default. Solution: configure the two YAML params above.

Exception matching chaos : Multiple handlers with inheritance relationships. Solution: follow "exact match first" — child exceptions before parents.

Transaction rollback fails : Exception caught by global handler, transaction doesn't auto-rollback. Solution: ensure business exception is RuntimeException or specify rollbackFor in @Transactional.

Comparison with Other Approaches

@ControllerAdvice + @ExceptionHandler

: Simple, elegant, flexible. Only handles Controller-layer exceptions. Best for most front-end separated projects. ErrorController: Handles all container-level exceptions. Verbose, less flexible. Fallback for 404/500. HandlerExceptionResolver: Lowest level, most flexible. Complex config, invasive. Custom exception frameworks.

High-Level Interview Details

Multiple @ControllerAdvice Order?

Ordered by @Order or Ordered interface; lower value = higher priority. Unannotated ones last. Within same class, handlers matched by inheritance depth (child first).

Microservice Response Format?

Wrap with ApiResult + status code; frontend intercepts by code (e.g., 401 → redirect to login).

Limit to Specific Package?

@RestControllerAdvice(basePackages = "com.xxx.order")

Precisely "suppress" order module exceptions without collateral damage.

Ultimate Interview Answer

Pain: try-catch everywhere → Fix: throw only custom exceptions.

Pain: inconsistent response formats → Fix: unified ApiResult.

Pain: missed exceptions → 500 → Fix: Exception.class catch-all.

Pain: validation handling bloated → Fix: MethodArgumentNotValidException unified.

"Unified exception handling puts messy errors into a pretty box and ships them back."

In practice, split exceptions into Business Exceptions (param errors, permission denied) and System Exceptions (DB connection failure). Business exceptions return clear messages to frontend; system exceptions return generic message with detailed logging. Also integrate Sentry for automatic system exception reporting for rapid debugging.

Spring Boot 3.x New Features: Jakarta EE 9 Migration, Java 17+ Baseline, Native Image Support

Java 17+ Baseline

Spring Boot 3.x drops Java 8/11, mandates minimum Java 17 , recommends Java 21 LTS.

Core Benefits

Language Features : Records, Pattern Matching, Sealed Classes, Text Blocks → 30%+ less boilerplate, better readability/maintainability.

JVM Performance : ZGC/Shenandoah low-latency GC, AOT Compilation, Vector API → large-heap pauses from seconds to milliseconds; compute-intensive tasks 20-50% faster.

Security : Stronger module system, insecure algorithms disabled by default → bottom-up security improvement, reduced vulnerability risk.

Java 17 is Oracle LTS (support until 2029) vs Java 11 (until 2026) — upgrading is inevitable for next 5 years.

Features You'll Use Daily in Spring Boot 3

Record 😎 : DTO with tons of @Data / @Getter → record UserDto(String name, int age) {} — auto equals / hashCode; @ConfigurationProperties works with Records.

Text Block 📜 : Concatenating SQL/JSON with + → """ ... """ multi-line strings; @Query("""select ...""") readability explosion.

Sealed Class 🔒 : State pattern enforced only by comments → sealed interface Result permits Success, Failure — compile-time extension control; security policies configurable.

Pattern Matching 🧩 : instanceof then cast → if (obj instanceof String s && s.length()>5) — direct variable binding.

GC & Performance ⚡ : CMS retired, G1 default, ZGC improved → auto enjoy ZGC/Shenandoah low-latency; container-aware memory more accurate.

Compatibility Firewall

Groovy, Kotlin, Lombok versions must align with Java 17 class files.

Bytecode manipulation libs (ASM, CGLIB) must upgrade or class enhancement crashes.

Spring Boot 3 requires Java 17 minimum — hard constraint ; Java 8/11 fails at startup.

Jakarta EE 9 Full Migration

Most breaking change: all javax. packages renamed to jakarta. — result of Java EE donation to Eclipse Foundation.

Key Impacts

Dependency upgrades : All Java EE-based third-party libs must upgrade to Jakarta EE 9+ compatible versions (MyBatis 3.5.10+, Druid 1.2.16+).

Code changes : Global replace import javax.* → import jakarta.* (IDE one-click).

Compatibility issues : Some legacy libs (old EJB, JAX-RS impls) unsupported; need alternatives.

Pitfall: Heavy third-party deps? Check Jakarta EE compatibility first or ClassNotFoundException at runtime.

Interview highlight: "We used OpenRewrite's javax-to-jakarta recipe to auto-migrate the whole project — 5000+ files, integration tests passed in one go."

Native Image Support (Spring Native)

Standout feature: GraalVM integration for Ahead-Of-Time (AOT) compilation , producing native executables.

AOT + GraalVM Essence

No longer experimental Spring Native; Spring Boot 3 ships AOT processing engine that pre-compiles runtime reflection, proxies, serialization into static config, fed to GraalVM for native binary generation.

Traditional JVM vs Native Image

Traditional JVM startup:
JAR → JVM load → Class scan → Condition eval → Proxy gen → Startup done
Time: 2-3 seconds 😴

Native Image startup:
AOT compile-time → Fixed bean defs, proxy classes, reflection config
→ Native executable → Direct run
Time: 0.05-0.1 seconds 🏎️💨

Core Advantages

Instant startup : Seconds → milliseconds, perfect for Serverless & microservices.

Ultra-low memory : 80%+ reduction, huge cloud cost savings.

No JVM dependency : Native binary runs directly on OS.

Limitations

Long compile time : Large projects take minutes to build native image.

Dynamic features restricted : Reflection, dynamic proxies, resource loading need explicit config.

Debugging harder : Native image debug experience inferior to JVM.

Best for: Stateless microservices, scheduled tasks, CLI tools . Complex apps with heavy dynamic features — evaluate first.

How to Play

Add GraalVM Native Build Tools, run mvn -Pnative native:compile.

Register dynamic behaviors with Hints ( @RegisterReflectionForBinding, RuntimeHintsRegistrar).

Fallback to regular JVM for things that can't go native (e.g., runtime dynamic scripting engines).

Cloud-native sweet spot: K8s Pod Ready in blink, scale-out elasticity crushes JVM mode .

Interview highlight: "Our microservice cold start was 3s causing K8s probe timeouts; native image compressed to 80ms, service registration instant, gray-release risk drastically reduced."

Spring Boot vs Spring Core Differences

One-Sentence Summary

Spring is a comprehensive Java enterprise framework providing IoC, AOP; Spring Boot is a "rapid dev scaffold" on top of Spring — not a replacement, but makes Spring simpler and more efficient.

Analogy

Spring = "Unfinished house", Spring Boot = "Fully furnished apartment" 🏠

Spring gives infinite possibilities but you build walls, plumbing; Spring Boot has hard/soft decoration done — you move in, focus on business furniture.

Core Comparison Table

Core Philosophy : Spring = full enterprise dev solution; Spring Boot = Convention over Configuration.

Configuration : Spring = heavy XML/Java config, manual bean wiring; Spring Boot = auto-configuration, defaults cover 80% cases.

Dependency Management : Spring = manual all deps, version conflicts likely; Spring Boot = starters auto-manage versions, "one-click import".

Deployment : Spring = WAR to external Tomcat etc.; Spring Boot = embedded Tomcat/Jetty/Undertow, run JAR directly.

Dev Efficiency : Spring = boilerplate heavy, steep learning curve; Spring Boot = zero-config start, minutes to running project.

Ecosystem Integration : Spring = manual third-party integration, complex config; Spring Boot = 100+ official starters, out-of-the-box.

Monitoring : Spring = no built-in, extra integration needed; Spring Boot = Actuator provides health, metrics, ready-to-use.

Version Arbitration : Spring = dev resolves conflicts, frequent "JAR hell" 😈; Spring Boot = spring-boot-dependencies BOM manages versions.

Interview soundbite: Spring Boot's starter is a pre-packaged descriptor (pom) bundling all deps for a scenario, avoiding version conflicts, massively boosting efficiency.

Config: From "Ancient Scrolls" to "Smart Forms"

Spring : Classic applicationContext.xml, dispatcher-servlet.xml … piles of XML, bean-by-bean, AOP/tx config tedious 😓

Spring Boot : Convention over configuration! Defaults cover 80%; override via application.yml or properties changing a few keys; even auto-config ( @EnableAutoConfiguration) conditionally assembles beans.

# Spring Boot MySQL example
spring:
  datasource:
    url: jdbc:mysql://localhost:3306/mydb
    username: root
    password: 123456
  jpa:
    hibernate:
      ddl-auto: update

Used to take reams of XML; now three lines of YAML 🔥

Interview soundbite: @SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan — auto-scans and configures.

Deployment: From "Hotel Hunting" to "Capsule Hotel"

Spring : Build WAR, external Tomcat/Jetty, configure server params.

Spring Boot : Embedded Tomcat/Jetty/Undertow, single executable fat JAR, java -jar runs. Microservice & container-friendly 💯

# Spring Boot startup this simple
java -jar myapp.jar

Used to install Tomcat; now server comes built-in like a portable capsule hotel 🚅

Production-Ready: From "Naked" to "Wearing Health Band"

Health Check : Spring = DIY integration or custom endpoints; Spring Boot = spring-boot-actuator exposes /health, /info instantly.

Metrics : Spring = manual Micrometer etc. integration; Spring Boot = Actuator auto-integrates, Prometheus easy.

External Config : Spring = @Value works but clunky overall; Spring Boot = perfect multi-env profile support, config center ready.

If interviewer asks "How do you monitor production services?" , reply: "We use Spring Boot Actuator to expose health checks and metrics, integrated with Prometheus + Grafana for dashboards." Instant credibility 👍

Under-the-Hood Principles (Bonus Points)

Spring Core : IoC container (BeanFactory/ApplicationContext) + AOP — foundation for bean management, DI, AOP.

Spring Boot Magic : @Conditional conditional assembly. E.g., @ConditionalOnClass (activate if class present), @ConditionalOnMissingBean (auto-config only if you didn't declare bean). Via

spring.factories
EnableAutoConfiguration

entries, loads all auto-config classes, activates on demand.

In short, Spring Boot pre-writes a pile of "if…then…" auto-config classes; whichever starter you import triggers corresponding conditions, saving manual work 🧙✨

Most Intuitive Dev Flow Comparison

(Diagram referenced in source)

Final Cheat Sheet

📋 Spring vs Spring Boot Core Diff Snapshot
┌──────────────────┬──────────────────────────────┬──────────────────────────────┐
│ Dimension        │ Spring Framework             │ Spring Boot                  │
├──────────────────┼──────────────────────────────┼──────────────────────────────┤
│ Design Goal      │ "Lego bricks" for enterprise │ Build standalone, production │
│                  │ apps                         │ Spring apps fast             │
│ Dependency Mgmt  │ Manual, conflict-prone       │ Starters + BOM unified       │
│ Config Style     │ XML/Annotations, heavy work  │ Convention>Config, YAML/prop │
│ Deployment       │ Needs external Servlet cont. │ Embedded container, run JAR  │
│ Ops Monitoring   │ Manual integration           │ Actuator out-of-the-box      │
│ Learning Curve   │ Steep, deep internals needed │ Smooth, newbie half-day OK   │
│ Best Fit         │ Highly flexible large apps   │ Microservices, cloud-native, │
│                  │                              │ rapid iteration              │
└──────────────────┴──────────────────────────────┴──────────────────────────────┘

Top 3 Interview Key Points

Auto-config principle : @EnableAutoConfiguration scans META-INF/spring.factories auto-config classes, uses conditionals ( @ConditionalOnClass, @ConditionalOnMissingBean) to assemble beans — Spring Boot's soul.

Starter essence : Not magic — just a "dependency descriptor" bundling all deps for a feature with guaranteed version compatibility. E.g., spring-boot-starter-web includes Spring MVC, Tomcat, Jackson.

Relationship : Spring Boot rewrites zero Spring core functionality; it's a layer of encapsulation and automation on top. Everything Spring does, Spring Boot does simpler.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Exception HandlingSpring BootInterview PreparationGraalVMAuto-ConfigurationJava 17ActuatorProfileStarterSpring Boot 3.x
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.