PrepStack › Backend › Spring Boot

Spring Boot interview cheat sheet

IoC/DI, beans, auto-configuration, REST, AOP, transactions, Security, testing

Spring Boot rounds usually start with the container: IoC, dependency injection, bean scopes and lifecycle. Then they move to what Boot adds: auto-configuration, starters and externalized config. Then come the parts you use daily: REST controllers, validation, error handling, @Transactional and Security. Senior rounds dig into proxies (why self-invocation breaks @Transactional), circular dependencies, testing slices and what changed in Boot 3 and 4. Spring itself can't run on this page, so small plain-Java programs show how the machinery works inside. Read the 15-minute revision first, then use Quiz mode.

15-minute revision

  1. Spring Framework gives you the IoC container, DI, AOP, transactions and MVC. Spring Boot adds auto-configuration, starters, an embedded server and production features (Actuator) on top.
  2. IoC: the container creates objects and wires them; your code does not call new on its dependencies. DI is how it does that: constructor (preferred), setter or field injection.
  3. ApplicationContext is a BeanFactory plus events, i18n, resource loading, Environment and automatic post-processor registration. It creates singletons eagerly at startup.
  4. Scopes: singleton (default, one per container), prototype (new on each lookup, no destroy callback), and web scopes request, session, application, websocket.
  5. Lifecycle: constructor → inject → Aware callbacks → BeanPostProcessor before → @PostConstruct → afterPropertiesSet → init-method → BeanPostProcessor after (proxies made here) → … → @PreDestroy.
  6. @Service, @Repository, @Controller are all @Component. @Repository adds exception translation to DataAccessException; @RestController = @Controller + @ResponseBody.
  7. @Configuration classes are CGLIB-proxied, so calling one @Bean method from another returns the same singleton. proxyBeanMethods = false turns that off (lite mode).
  8. Two beans of one type → NoUniqueBeanDefinitionException. Fix with @Primary (default choice) or @Qualifier (exact choice at the injection point).
  9. Circular references are banned by default since Boot 2.6. Constructor cycles can never be solved; redesign, or as a last resort use @Lazy or setter injection.
  10. @SpringBootApplication = @SpringBootConfiguration + @EnableAutoConfiguration + @ComponentScan. Auto-config classes are listed in META-INF/spring/...AutoConfiguration.imports and guarded by @ConditionalOn....
  11. Auto-config backs off with @ConditionalOnMissingBean: define your own bean and Boot's default disappears. Run with --debug to see the conditions report.
  12. Config precedence (high → low): command-line args, Java system properties, OS env vars, profile-specific files, application.properties|yml. Bind groups with @ConfigurationProperties.
  13. Spring AOP is proxy-based: JDK dynamic proxy (interfaces) or CGLIB (subclass, Boot's default). A call to this.method() skips the proxy, so @Transactional, @Async and @Cacheable silently do nothing.
  14. @Transactional rolls back on unchecked exceptions and errors only by default. Default propagation is REQUIRED. REQUIRES_NEW suspends the outer transaction.
  15. Security: DelegatingFilterProxy → FilterChainProxy → first matching SecurityFilterChain bean. Use the lambda DSL (required in Security 7); JWT APIs use oauth2ResourceServer(o -> o.jwt(...)).
  16. Boot 3: Java 17, javax → jakarta, native images, ProblemDetail; 3.2 added virtual threads (spring.threads.virtual.enabled). Boot 4 (Nov 2025): Framework 7, Jakarta EE 11, Jackson 3, modular starters, @MockBean removed.

Core container: IoC, DI & beans

Spring vs Spring Boot & starters

Spring is the framework; Boot is an opinionated layer that configures Spring for you and runs it as a self-contained jar.

  • Spring Framework gives you the building blocks: the IoC container, AOP, transactions, data access, Spring MVC and WebFlux. You still choose and wire everything yourself.
  • Spring Boot adds auto-configuration (sensible beans based on the classpath), starters (curated dependency sets), an embedded server (Tomcat by default), externalized config and Actuator.
  • A Boot app is a plain main method that calls SpringApplication.run(...). You build an executable “fat” jar and run it with java -jar; no external app server is needed.
  • A starter is a dependency-only module, for example spring-boot-starter-data-jpa. It pulls in the libraries and the matching auto-configuration. Versions come from Boot's dependency management (BOM or parent POM), so you rarely write version numbers.
  • Boot 4 split Boot into smaller modules. spring-boot-starter-web became spring-boot-starter-webmvc (the old name is deprecated), and most technologies now have a matching -test starter.

Interview questions

  • What is the difference between Spring and Spring Boot?
  • What is a Spring Boot starter?
  • How does a Boot app run without an external Tomcat?

IoC & dependency injection (constructor vs setter vs field)

The container builds your objects and hands them their dependencies; prefer constructor injection.

  • Inversion of Control: objects do not create or look up their own dependencies. A container does it and passes them in. Your class only declares what it needs.
  • Dependency Injection is the main IoC technique. Spring supports constructor, setter and field injection.
  • Constructor injection is the recommended default. Dependencies can be final, the object is never half-built, required deps are obvious, and tests can just call new.
  • Since Spring 4.3, a class with a single constructor does not need @Autowired on it.
  • Setter injection fits optional or re-configurable dependencies. Field injection (@Autowired on a private field) is short but hides dependencies, blocks final and needs reflection or Spring in tests.

Interview questions

  • What is IoC and what is DI?
  • Why is constructor injection preferred over field injection?
  • When would you use setter injection?

ApplicationContext vs BeanFactory

BeanFactory is the basic DI container; ApplicationContext extends it with everything a real application needs.

  • BeanFactory is the root interface: getBean, bean definitions, scopes, DI. It creates beans lazily, on first request.
  • ApplicationContext extends BeanFactory and adds: event publishing (ApplicationEventPublisher), i18n (MessageSource), resource loading, the Environment (profiles and properties) and automatic registration of BeanPostProcessor and BeanFactoryPostProcessor beans.
  • An ApplicationContext pre-instantiates all non-lazy singletons at startup, so wiring errors fail fast at boot instead of on the first request.
  • Boot picks the implementation from the app type: AnnotationConfigServletWebServerApplicationContext for MVC, a reactive variant for WebFlux, and a plain annotation context for non-web apps.
  • In practice you always use ApplicationContext. Using a raw BeanFactory would mean annotations like @Autowired and @PostConstruct don't work unless you register their post-processors yourself.

Interview questions

  • Difference between BeanFactory and ApplicationContext?
  • How do you get the ApplicationContext inside a bean?
  • What are Spring application events used for?

Stereotypes, @Configuration & @Bean

Annotate your own classes with @Component and friends; use @Bean methods for third-party objects or custom construction logic.

  • @Component marks a class for component scanning. @Service, @Repository, @Controller and @RestController are specialisations that also document the layer.
  • @Repository adds persistence exception translation: vendor exceptions such as SQLException are turned into Spring's DataAccessException hierarchy.
  • @Controller makes a class a Spring MVC handler; @RestController adds @ResponseBody, so return values are written to the body (usually as JSON).
  • @Bean methods inside a @Configuration class create beans you can't annotate (library classes) or that need custom setup. The method name becomes the bean name.
  • Full mode: @Configuration classes are CGLIB-subclassed, so a @Bean method calling another @Bean method gets the existing singleton. Lite mode (proxyBeanMethods = false, or @Bean inside a @Component) makes those plain Java calls, which create new objects.

Interview questions

  • Difference between @Component, @Service, @Repository and @Controller?
  • Difference between @Component and @Bean?
  • Why is a @Configuration class proxied?

@Autowired, @Qualifier & @Primary

Spring injects by type; when several beans match, @Primary picks a default and @Qualifier picks exactly.

  • @Autowired resolves by type. No match → NoSuchBeanDefinitionException. More than one match → NoUniqueBeanDefinitionException.
  • @Primary marks the default candidate when several beans share a type. @Qualifier("name") at the injection point picks a specific bean and overrides @Primary.
  • If still ambiguous, Spring falls back to matching the parameter or field name against bean names.
  • Inject all implementations with List<PaymentGateway> (ordered by @Order) or Map<String, PaymentGateway> (keyed by bean name). This is the usual way to build a strategy pattern.
  • Optional dependencies: Optional<T>, @Autowired(required = false), or ObjectProvider<T> (lazy, also handles prototype lookups).

Interview questions

  • How does Spring resolve which bean to inject?
  • Difference between @Primary and @Qualifier?
  • How would you implement a strategy pattern with Spring?

Bean scopes

Singleton is the default: one shared instance per container. Choose another scope only when state must not be shared.

  • singleton (default): one instance per ApplicationContext, shared by every thread. It must be stateless or thread-safe.
  • prototype: a new instance on every injection or getBean. Spring creates and initialises it but does not manage destruction, so @PreDestroy is never called.
  • Web scopes: request (one per HTTP request), session (one per HTTP session), application (one per ServletContext), websocket.
  • Spring singleton ≠ GoF singleton: it is one instance per container per bean definition, not per class loader. Two @Bean methods can create two singletons of the same class.
  • Scoped-bean injection problem: a prototype or request-scoped bean injected into a singleton is resolved once. Use ObjectProvider<T>, @Lookup, or a scoped proxy (proxyMode = ScopedProxyMode.TARGET_CLASS).

Interview questions

  • Are singleton beans thread-safe?
  • What happens when you inject a prototype bean into a singleton?
  • Difference between a Spring singleton and the GoF Singleton pattern?

Bean lifecycle & @PostConstruct

Create → inject → aware → post-process → init → ready → destroy; proxies are created by a post-processor after init.

  • Order: instantiate (constructor) → populate (setter/field injection) → Aware callbacks (BeanNameAware, ApplicationContextAware) → BeanPostProcessor.postProcessBeforeInitialization → init → postProcessAfterInitialization.
  • Init callbacks run in this order: @PostConstruct → InitializingBean.afterPropertiesSet() → custom @Bean(initMethod = ...).
  • @PostConstruct runs after all dependencies are injected, so it's the place for setup that needs them: warming a cache, validating config. Doing that in the constructor fails with field injection because the fields are still null.
  • Destroy callbacks run on context close for singletons: @PreDestroy → DisposableBean.destroy() → destroyMethod.
  • postProcessAfterInitialization is where AOP proxies are created. The bean you get injected may be a proxy that wraps the raw object.
  • @PostConstruct and @PreDestroy come from jakarta.annotation (they were javax.annotation before Boot 3).

Interview questions

  • Describe the Spring bean lifecycle.
  • Why use @PostConstruct instead of the constructor?
  • What is a BeanPostProcessor? Give examples.
  • BeanPostProcessor vs BeanFactoryPostProcessor?

Circular dependencies

A → B → A. Boot refuses it by default; constructor cycles are impossible to resolve, so fix the design.

  • With constructor injection, A needs a finished B before it can be built, and B needs A. Spring detects this and fails with BeanCurrentlyInCreationException.
  • With field/setter injection, Spring can resolve a singleton cycle: it creates A, exposes an early reference to the half-built A, builds B with it, then finishes A.
  • Since Spring Boot 2.6, circular references are prohibited by default, even when they could be resolved. spring.main.allow-circular-references=true re-enables the old behaviour, but treat that as a temporary workaround.
  • Prototype-scoped cycles can never be resolved, because there is no cached instance to hand out early.
  • Real fixes: extract the shared logic into a third bean, use events instead of direct calls, or pass data as method arguments. A tactical fix is @Lazy on one constructor parameter, which injects a lazy proxy.

Interview questions

  • How does Spring handle circular dependencies?
  • How do you fix BeanCurrentlyInCreationException?
  • Why can't constructor-injection cycles be resolved?

Spring Boot essentials

Auto-configuration, @SpringBootApplication & conditions

Boot registers ready-made @Configuration classes guarded by conditions; your own beans make them back off.

  • @SpringBootApplication combines @SpringBootConfiguration (a @Configuration), @EnableAutoConfiguration and @ComponentScan (from the main class's package down).
  • @EnableAutoConfiguration loads candidate classes listed in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports in every jar. Before Boot 2.7 they were listed in spring.factories; Boot 3 dropped that for auto-config.
  • Each auto-config class is guarded by conditions: @ConditionalOnClass, @ConditionalOnMissingBean, @ConditionalOnProperty, @ConditionalOnBean, @ConditionalOnWebApplication, @ConditionalOnResource and others.
  • Your configuration is processed before auto-configuration. So a user-defined bean makes @ConditionalOnMissingBean fail and Boot's default backs off.
  • Debug it with --debug (or debug=true) for the condition evaluation report, or the Actuator /actuator/conditions endpoint. Exclude a class with @SpringBootApplication(exclude = ...) or spring.autoconfigure.exclude.

Interview questions

  • How does Spring Boot auto-configuration work?
  • What does @SpringBootApplication do?
  • Your app picked the wrong bean or didn't create one. How do you debug it?
  • How would you create a custom starter?

Profiles, externalized config & @ConfigurationProperties

One artifact, many environments: settings come from layered property sources and profiles switch blocks on and off.

  • Boot reads config from many property sources in a fixed order. Higher sources win: command-line args > Java system properties > OS environment variables > profile-specific files > application.properties|yml. Files outside the jar beat files inside it.
  • Profiles group config and beans per environment. Activate them with spring.profiles.active=prod (or SPRING_PROFILES_ACTIVE). Then application-prod.yml is loaded on top, and @Profile("prod") beans are registered.
  • Relaxed binding: app.retry-count, app.retryCount and env var APP_RETRYCOUNT all map to the same property, so env vars can override YAML in containers.
  • @Value("${app.timeout:30s}") injects one value with a default. @ConfigurationProperties(prefix = "app") binds a whole group to a typed class or record, with validation, IDE metadata and conversion (e.g. Duration).
  • Never commit secrets. Use env vars, a secret manager (Vault, AWS Secrets Manager), or spring.config.import to pull external config.

Interview questions

  • How does Spring Boot decide which property value to use?
  • What are profiles and how do you activate them?
  • @Value vs @ConfigurationProperties?

Building REST APIs

REST controllers, mappings & ResponseEntity

@RestController methods map HTTP requests to Java methods; Jackson turns objects into JSON and back.

  • Requests go through the DispatcherServlet (front controller). It finds the handler through HandlerMapping, resolves the arguments, calls your method and writes the result with an HttpMessageConverter.
  • Mappings: @RequestMapping on the class for a base path; @GetMapping, @PostMapping, @PutMapping, @PatchMapping, @DeleteMapping on methods.
  • @PathVariable reads a URI segment (/orders/{id}). @RequestParam reads the query string (?page=2). @RequestBody deserialises the JSON body. @RequestHeader reads a header.
  • Return a DTO for 200 OK. Use ResponseEntity<T> to control the status, headers and body, for example 201 Created with a Location header, or 204 No Content.
  • Return DTOs, not JPA entities. That avoids lazy-loading errors, leaking internal fields and infinite JSON recursion.

Interview questions

  • What happens when an HTTP request hits a Spring MVC app?
  • Difference between @PathVariable and @RequestParam?
  • Why use ResponseEntity?

Validation with @Valid & Bean Validation

Put constraints on DTOs, trigger them with @Valid, and turn failures into a clean 400 response.

  • Needs spring-boot-starter-validation (Hibernate Validator, the Jakarta Bean Validation reference implementation). Annotations live in jakarta.validation.constraints.
  • Common constraints: @NotNull, @NotBlank (strings), @NotEmpty (collections), @Size, @Min/@Max, @Positive, @Email, @Pattern, @Past/@Future.
  • @Valid @RequestBody Dto dto validates the body. On failure Spring throws MethodArgumentNotValidException, which becomes a 400.
  • Put @Valid on nested objects and collection elements (List<@Valid Item>) or they are skipped. Use validation groups when create and update need different rules.
  • Constraints directly on @RequestParam or @PathVariable parameters trigger method validation. Since Spring 6.1 MVC does this natively and throws HandlerMethodValidationException. In services, use @Validated on the class, which throws ConstraintViolationException.
  • Write custom constraints with an annotation plus a ConstraintValidator for rules like “end date after start date”.

Interview questions

  • How does @Valid work on a request body?
  • Difference between @Valid and @Validated?
  • @NotNull vs @NotEmpty vs @NotBlank?

Global exception handling & ProblemDetail

Map exceptions to HTTP responses in one @RestControllerAdvice, using the RFC 9457 ProblemDetail format.

  • @ExceptionHandler methods handle exceptions thrown by controller methods. Put them in a @ControllerAdvice or @RestControllerAdvice class to apply them to all controllers.
  • ProblemDetail (Spring 6 / Boot 3) is the standard error body from RFC 9457 (which replaced RFC 7807): type, title, status, detail, instance, plus custom properties. Content type is application/problem+json.
  • Extend ResponseEntityExceptionHandler to get ProblemDetail responses for Spring MVC's own exceptions (validation, 405, 415 and so on), or set spring.mvc.problemdetails.enabled=true.
  • Map exceptions to statuses: not found → 404, validation → 400, conflict/duplicate → 409, auth → 401/403, everything else → 500 with a generic message (log the details, don't return stack traces).
  • Alternatives: @ResponseStatus on a custom exception class, throwing ResponseStatusException, or extending ErrorResponseException.

Interview questions

  • How do you implement global exception handling in Spring Boot?
  • What is ProblemDetail?
  • Why doesn't my @ControllerAdvice catch a 401 from Spring Security?

WebFlux vs Spring MVC

MVC is servlet-based, thread-per-request and blocking; WebFlux is non-blocking and reactive on an event loop.

  • Spring MVC runs on the Servlet API (Tomcat). One thread handles one request from start to end, and blocking I/O holds that thread. Simple to write, debug and test.
  • Spring WebFlux runs on Reactor Netty (default) or other non-blocking servers. A few event-loop threads serve many connections. Handlers return Mono<T> (0..1) or Flux<T> (0..N), and data flows with backpressure.
  • WebFlux only helps if the whole chain is non-blocking: R2DBC instead of JDBC, WebClient, reactive drivers. One blocking call on an event-loop thread stalls every connection on it.
  • With virtual threads (Java 21 + Boot 3.2+), MVC can handle large numbers of concurrent blocking calls with plain imperative code. That removes the main reason many teams picked WebFlux.
  • Pick WebFlux for streaming (SSE, WebSockets), gateways and high-fan-out I/O with reactive libraries. Pick MVC (plus virtual threads) for typical CRUD services with JPA/JDBC.

Interview questions

  • Difference between Spring MVC and WebFlux?
  • When would you choose WebFlux?
  • What happens if you call blocking JDBC code in a WebFlux handler?
  • Do virtual threads make WebFlux obsolete?

Proxies, AOP & transactions

AOP & proxies (JDK vs CGLIB, self-invocation)

Spring adds cross-cutting behaviour by wrapping beans in proxies; only calls that go through the proxy are intercepted.

  • AOP moves cross-cutting concerns (transactions, security, caching, logging, metrics) out of business code. Terms: aspect (the module), advice (the code: @Before, @After, @AfterReturning, @AfterThrowing, @Around), pointcut (where it applies), join point (a method execution, in Spring AOP).
  • Spring AOP is proxy-based and runs at runtime. A BeanPostProcessor wraps matching beans in a proxy, and other beans get the proxy injected.
  • JDK dynamic proxy: implements the bean's interfaces, so you can only inject it by interface type. CGLIB: generates a subclass, so it works without interfaces but can't intercept final classes or final/private methods. Spring Boot uses CGLIB by default (spring.aop.proxy-target-class=true).
  • Self-invocation: inside the bean, this.audit() calls the raw object directly and skips the proxy. So @Transactional, @Async, @Cacheable and @PreAuthorize on the inner method have no effect.
  • Fixes for self-invocation: move the method to another bean (best), inject the bean's own proxy (@Lazy self-injection), or use AspectJ weaving (compile-time or load-time), which changes bytecode instead of using proxies.

Interview questions

  • How does Spring AOP work?
  • JDK dynamic proxy vs CGLIB?
  • Why doesn't @Transactional work when I call the method from the same class?
  • Spring AOP vs AspectJ?

@Transactional basics

A proxy opens a transaction before the method and commits or rolls back after it; know the defaults and the traps.

  • @Transactional on a class or public method makes the proxy call PlatformTransactionManager to begin a transaction, run the method, then commit, or roll back if an exception escapes.
  • Default rollback: on RuntimeException and Error only. Checked exceptions commit unless you add rollbackFor = Exception.class.
  • Default propagation is REQUIRED (join the existing transaction or start one). REQUIRES_NEW suspends the outer one and runs independently. Use it for audit logs that must survive a rollback.
  • readOnly = true is a hint. Hibernate skips dirty checking and flushing, and some drivers or databases route to replicas or optimise. Use it on query methods.
  • Traps: self-invocation, private/final methods (CGLIB proxies can't intercept them; protected and package-private methods work since Spring 6.0), catching the exception inside the method (nothing to roll back on), and slow remote calls inside a transaction (holds DB connections and locks).

Interview questions

  • How does @Transactional work?
  • Which exceptions cause a rollback?
  • REQUIRED vs REQUIRES_NEW?
  • List reasons @Transactional may silently not work.

Security, testing & production

Spring Security: filter chain & JWT resource server

Security is a chain of servlet filters in front of your app; you configure it with SecurityFilterChain beans.

  • The servlet container calls DelegatingFilterProxy, which hands off to the FilterChainProxy bean. That picks the first SecurityFilterChain whose matcher fits the request and runs its ordered filters.
  • Key filters: SecurityContextHolderFilter, CsrfFilter, the authentication filters (UsernamePasswordAuthenticationFilter, BearerTokenAuthenticationFilter, BasicAuthenticationFilter), ExceptionTranslationFilter (turns failures into 401/403) and AuthorizationFilter (last).
  • Authentication (who are you?) goes through AuthenticationManager → ProviderManager → AuthenticationProviders. The result is stored in the thread-local SecurityContextHolder. Authorization (what may you do?) is URL rules plus method security (@EnableMethodSecurity + @PreAuthorize).
  • Configure with a SecurityFilterChain @Bean and the lambda DSL. WebSecurityConfigurerAdapter was removed in Security 6, and Security 7 (Boot 4) removed the old .and() chaining style.
  • JWT resource server: add the OAuth2 resource-server starter, set spring.security.oauth2.resourceserver.jwt.issuer-uri, and call oauth2ResourceServer(o -> o.jwt(...)). Spring fetches the issuer's public keys (JWKS), checks the signature, exp and iss, and maps scope claims to SCOPE_xxx authorities.
  • For stateless token APIs: SessionCreationPolicy.STATELESS, and CSRF can be disabled because no cookies carry authentication. Store passwords with BCryptPasswordEncoder or DelegatingPasswordEncoder, never in plain text.

Interview questions

  • Explain the Spring Security architecture.
  • How does JWT authentication work with a Spring resource server?
  • Authentication vs authorization?
  • When is it safe to disable CSRF?

Testing: @SpringBootTest, slices, MockMvc & Testcontainers

Unit-test plain classes, use slices for one layer, and save the full context with real infrastructure for integration tests.

  • Unit tests need no Spring: with constructor injection you call new Service(mock) with Mockito. They are the fastest and should be the majority.
  • @SpringBootTest starts the full application context. Add webEnvironment = RANDOM_PORT for a real server. In Boot 4, add @AutoConfigureMockMvc (or @AutoConfigureRestTestClient) explicitly to get MockMvc or a test client.
  • Slices load only part of the app: @WebMvcTest (controllers, advice, filters, Jackson; no services, so mock them), @DataJpaTest (JPA repositories + TestEntityManager; transactional and rolled back after each test), @JsonTest, @RestClientTest, @WebFluxTest.
  • Replace a bean with a mock using @MockitoBean (Spring Framework 6.2+). @MockBean was deprecated in Boot 3.4 and removed in Boot 4.
  • Testcontainers runs a real database or broker in Docker. With @ServiceConnection (Boot 3.1+), Boot reads the container's URL and credentials automatically, so you don't need @DynamicPropertySource.
  • Spring caches contexts between test classes with the same configuration. Every different @MockitoBean set or set of properties creates a new context, which slows the suite.

Interview questions

  • @SpringBootTest vs @WebMvcTest?
  • Why use Testcontainers instead of H2?
  • @MockBean vs @MockitoBean?
  • Your test suite got slow. What do you check?

Actuator: health, metrics & production endpoints

Actuator adds HTTP/JMX endpoints for health, metrics, info and diagnostics; expose only what you need.

  • Add spring-boot-starter-actuator. Endpoints live under /actuator. Over HTTP, only health is exposed by default; expose others with management.endpoints.web.exposure.include.
  • Useful endpoints: health, info, metrics, prometheus (with micrometer-registry-prometheus), loggers (change log levels at runtime), env, beans, conditions, mappings, threaddump, heapdump.
  • Health combines HealthIndicators (DB, disk, Redis…) into UP/DOWN. Kubernetes probes use the liveness and readiness groups at /actuator/health/liveness and /readiness; Boot 4 enables these probe groups by default.
  • Metrics come from Micrometer, a vendor-neutral facade (Prometheus, Datadog, OTLP…). HTTP requests, JVM, pools and caches are instrumented automatically. Tracing uses Micrometer Tracing / OpenTelemetry (Boot 4 adds spring-boot-starter-opentelemetry).
  • Secure it: sensitive endpoints (env, heapdump, beans) leak secrets and internals. Put them behind auth or a separate management.server.port that isn't public.

Interview questions

  • What is Spring Boot Actuator?
  • How do liveness and readiness differ?
  • How do you add a custom metric?

Spring Boot 3.x & 4 changes (Jakarta, Java 17, virtual threads, native)

Boot 3 moved to Java 17 and Jakarta EE; 3.2 added virtual threads; Boot 4 brought Framework 7, Jackson 3 and modular jars.

  • Boot 3.0 (Nov 2022): Spring Framework 6, Java 17 baseline, Jakarta EE 9/10 (javax.* → jakarta.* for servlet, persistence, validation), GA GraalVM native image support with AOT processing, ProblemDetail, Micrometer Observation and Micrometer Tracing (replacing Spring Cloud Sleuth).
  • Boot 3.1: Testcontainers @ServiceConnection and Docker Compose support. Boot 3.2 (Nov 2023): virtual threads via spring.threads.virtual.enabled=true on Java 21, plus RestClient and JdbcClient.
  • Boot 4.0 (Nov 2025): Spring Framework 7, Jakarta EE 11 / Servlet 6.1, still Java 17 minimum (newest LTS recommended), Jackson 3 (tools.jackson packages), JSpecify null-safety annotations, API versioning, HTTP service client auto-config, and Spring Security 7.
  • Boot 4 also modularised Boot into smaller jars, renamed some starters (starter-web → starter-webmvc, starter-aop → starter-aspectj), dropped Undertow, removed APIs deprecated in 3.x (e.g. @MockBean), and needs GraalVM 25+ for native images.
  • Native images: AOT processing at build time plus GraalVM compile the app into a native executable. Startup is in milliseconds and memory is lower, but builds are slow, peak throughput can be lower than a warmed JIT, and reflection or dynamic proxies need hints.
  • Virtual threads: cheap JVM-managed threads. With the property on, Tomcat and @Async executors use them, so blocking I/O no longer ties up a scarce platform thread. Watch for pinning (mostly fixed in Java 24 for synchronized) and for overloading downstream pools such as DB connections.

Interview questions

  • What were the major changes in Spring Boot 3?
  • What's new in Spring Boot 4?
  • How do virtual threads help a Spring MVC app?
  • Pros and cons of a Spring Boot native image?