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
- 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.
- IoC: the container creates objects and wires them; your code does not call
newon its dependencies. DI is how it does that: constructor (preferred), setter or field injection. ApplicationContextis aBeanFactoryplus events, i18n, resource loading,Environmentand automatic post-processor registration. It creates singletons eagerly at startup.- Scopes:
singleton(default, one per container),prototype(new on each lookup, no destroy callback), and web scopesrequest,session,application,websocket. - Lifecycle: constructor → inject →
Awarecallbacks →BeanPostProcessorbefore →@PostConstruct→afterPropertiesSet→ init-method →BeanPostProcessorafter (proxies made here) → … →@PreDestroy. @Service,@Repository,@Controllerare all@Component.@Repositoryadds exception translation toDataAccessException;@RestController=@Controller+@ResponseBody.@Configurationclasses are CGLIB-proxied, so calling one@Beanmethod from another returns the same singleton.proxyBeanMethods = falseturns that off (lite mode).- Two beans of one type →
NoUniqueBeanDefinitionException. Fix with@Primary(default choice) or@Qualifier(exact choice at the injection point). - Circular references are banned by default since Boot 2.6. Constructor cycles can never be solved; redesign, or as a last resort use
@Lazyor setter injection. @SpringBootApplication=@SpringBootConfiguration+@EnableAutoConfiguration+@ComponentScan. Auto-config classes are listed inMETA-INF/spring/...AutoConfiguration.importsand guarded by@ConditionalOn....- Auto-config backs off with
@ConditionalOnMissingBean: define your own bean and Boot's default disappears. Run with--debugto see the conditions report. - Config precedence (high → low): command-line args, Java system properties, OS env vars, profile-specific files,
application.properties|yml. Bind groups with@ConfigurationProperties. - 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,@Asyncand@Cacheablesilently do nothing. @Transactionalrolls back on unchecked exceptions and errors only by default. Default propagation isREQUIRED.REQUIRES_NEWsuspends the outer transaction.- Security:
DelegatingFilterProxy→FilterChainProxy→ first matchingSecurityFilterChainbean. Use the lambda DSL (required in Security 7); JWT APIs useoauth2ResourceServer(o -> o.jwt(...)). - 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,@MockBeanremoved.
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
mainmethod that callsSpringApplication.run(...). You build an executable “fat” jar and run it withjava -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-webbecamespring-boot-starter-webmvc(the old name is deprecated), and most technologies now have a matching-teststarter.
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 callnew. - Since Spring 4.3, a class with a single constructor does not need
@Autowiredon it. - Setter injection fits optional or re-configurable dependencies. Field injection (
@Autowiredon a private field) is short but hides dependencies, blocksfinaland 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.
BeanFactoryis the root interface:getBean, bean definitions, scopes, DI. It creates beans lazily, on first request.ApplicationContextextendsBeanFactoryand adds: event publishing (ApplicationEventPublisher), i18n (MessageSource), resource loading, theEnvironment(profiles and properties) and automatic registration ofBeanPostProcessorandBeanFactoryPostProcessorbeans.- An
ApplicationContextpre-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:
AnnotationConfigServletWebServerApplicationContextfor MVC, a reactive variant for WebFlux, and a plain annotation context for non-web apps. - In practice you always use
ApplicationContext. Using a rawBeanFactorywould mean annotations like@Autowiredand@PostConstructdon't work unless you register their post-processors yourself.
Interview questions
- Difference between
BeanFactoryandApplicationContext? - How do you get the
ApplicationContextinside 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.
@Componentmarks a class for component scanning.@Service,@Repository,@Controllerand@RestControllerare specialisations that also document the layer.@Repositoryadds persistence exception translation: vendor exceptions such asSQLExceptionare turned into Spring'sDataAccessExceptionhierarchy.@Controllermakes a class a Spring MVC handler;@RestControlleradds@ResponseBody, so return values are written to the body (usually as JSON).@Beanmethods inside a@Configurationclass create beans you can't annotate (library classes) or that need custom setup. The method name becomes the bean name.- Full mode:
@Configurationclasses are CGLIB-subclassed, so a@Beanmethod calling another@Beanmethod gets the existing singleton. Lite mode (proxyBeanMethods = false, or@Beaninside a@Component) makes those plain Java calls, which create new objects.
Interview questions
- Difference between
@Component,@Service,@Repositoryand@Controller? - Difference between
@Componentand@Bean? - Why is a
@Configurationclass proxied?
@Autowired, @Qualifier & @Primary
Spring injects by type; when several beans match, @Primary picks a default and @Qualifier picks exactly.
@Autowiredresolves by type. No match →NoSuchBeanDefinitionException. More than one match →NoUniqueBeanDefinitionException.@Primarymarks 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) orMap<String, PaymentGateway>(keyed by bean name). This is the usual way to build a strategy pattern. - Optional dependencies:
Optional<T>,@Autowired(required = false), orObjectProvider<T>(lazy, also handles prototype lookups).
Interview questions
- How does Spring resolve which bean to inject?
- Difference between
@Primaryand@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@PreDestroyis 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
@Beanmethods 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) →
Awarecallbacks (BeanNameAware,ApplicationContextAware) →BeanPostProcessor.postProcessBeforeInitialization→ init →postProcessAfterInitialization. - Init callbacks run in this order:
@PostConstruct→InitializingBean.afterPropertiesSet()→ custom@Bean(initMethod = ...). @PostConstructruns 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. postProcessAfterInitializationis where AOP proxies are created. The bean you get injected may be a proxy that wraps the raw object.@PostConstructand@PreDestroycome fromjakarta.annotation(they werejavax.annotationbefore Boot 3).
Interview questions
- Describe the Spring bean lifecycle.
- Why use
@PostConstructinstead of the constructor? - What is a
BeanPostProcessor? Give examples. BeanPostProcessorvsBeanFactoryPostProcessor?
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=truere-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
@Lazyon 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.
@SpringBootApplicationcombines@SpringBootConfiguration(a@Configuration),@EnableAutoConfigurationand@ComponentScan(from the main class's package down).@EnableAutoConfigurationloads candidate classes listed inMETA-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.importsin every jar. Before Boot 2.7 they were listed inspring.factories; Boot 3 dropped that for auto-config.- Each auto-config class is guarded by conditions:
@ConditionalOnClass,@ConditionalOnMissingBean,@ConditionalOnProperty,@ConditionalOnBean,@ConditionalOnWebApplication,@ConditionalOnResourceand others. - Your configuration is processed before auto-configuration. So a user-defined bean makes
@ConditionalOnMissingBeanfail and Boot's default backs off. - Debug it with
--debug(ordebug=true) for the condition evaluation report, or the Actuator/actuator/conditionsendpoint. Exclude a class with@SpringBootApplication(exclude = ...)orspring.autoconfigure.exclude.
Interview questions
- How does Spring Boot auto-configuration work?
- What does
@SpringBootApplicationdo? - 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(orSPRING_PROFILES_ACTIVE). Thenapplication-prod.ymlis loaded on top, and@Profile("prod")beans are registered. - Relaxed binding:
app.retry-count,app.retryCountand env varAPP_RETRYCOUNTall 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.importto pull external config.
Interview questions
- How does Spring Boot decide which property value to use?
- What are profiles and how do you activate them?
@Valuevs@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 throughHandlerMapping, resolves the arguments, calls your method and writes the result with anHttpMessageConverter. - Mappings:
@RequestMappingon the class for a base path;@GetMapping,@PostMapping,@PutMapping,@PatchMapping,@DeleteMappingon methods. @PathVariablereads a URI segment (/orders/{id}).@RequestParamreads the query string (?page=2).@RequestBodydeserialises the JSON body.@RequestHeaderreads a header.- Return a DTO for
200 OK. UseResponseEntity<T>to control the status, headers and body, for example201 Createdwith aLocationheader, or204 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
@PathVariableand@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 injakarta.validation.constraints. - Common constraints:
@NotNull,@NotBlank(strings),@NotEmpty(collections),@Size,@Min/@Max,@Positive,@Email,@Pattern,@Past/@Future. @Valid @RequestBody Dto dtovalidates the body. On failure Spring throwsMethodArgumentNotValidException, which becomes a 400.- Put
@Validon 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
@RequestParamor@PathVariableparameters trigger method validation. Since Spring 6.1 MVC does this natively and throwsHandlerMethodValidationException. In services, use@Validatedon the class, which throwsConstraintViolationException. - Write custom constraints with an annotation plus a
ConstraintValidatorfor rules like “end date after start date”.
Interview questions
- How does
@Validwork on a request body? - Difference between
@Validand@Validated? @NotNullvs@NotEmptyvs@NotBlank?
Global exception handling & ProblemDetail
Map exceptions to HTTP responses in one @RestControllerAdvice, using the RFC 9457 ProblemDetail format.
@ExceptionHandlermethods handle exceptions thrown by controller methods. Put them in a@ControllerAdviceor@RestControllerAdviceclass 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 isapplication/problem+json.- Extend
ResponseEntityExceptionHandlerto get ProblemDetail responses for Spring MVC's own exceptions (validation, 405, 415 and so on), or setspring.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:
@ResponseStatuson a custom exception class, throwingResponseStatusException, or extendingErrorResponseException.
Interview questions
- How do you implement global exception handling in Spring Boot?
- What is
ProblemDetail? - Why doesn't my
@ControllerAdvicecatch 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) orFlux<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
BeanPostProcessorwraps 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
finalclasses orfinal/privatemethods. 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,@Cacheableand@PreAuthorizeon the inner method have no effect. - Fixes for self-invocation: move the method to another bean (best), inject the bean's own proxy (
@Lazyself-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
@Transactionalwork 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.
@Transactionalon a class or public method makes the proxy callPlatformTransactionManagerto begin a transaction, run the method, then commit, or roll back if an exception escapes.- Default rollback: on
RuntimeExceptionandErroronly. Checked exceptions commit unless you addrollbackFor = Exception.class. - Default propagation is
REQUIRED(join the existing transaction or start one).REQUIRES_NEWsuspends the outer one and runs independently. Use it for audit logs that must survive a rollback. readOnly = trueis 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/finalmethods (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
@Transactionalwork? - Which exceptions cause a rollback?
REQUIREDvsREQUIRES_NEW?- List reasons
@Transactionalmay 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 theFilterChainProxybean. That picks the firstSecurityFilterChainwhose 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) andAuthorizationFilter(last). - Authentication (who are you?) goes through
AuthenticationManager→ProviderManager→AuthenticationProviders. The result is stored in the thread-localSecurityContextHolder. Authorization (what may you do?) is URL rules plus method security (@EnableMethodSecurity+@PreAuthorize). - Configure with a
SecurityFilterChain@Bean and the lambda DSL.WebSecurityConfigurerAdapterwas 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 calloauth2ResourceServer(o -> o.jwt(...)). Spring fetches the issuer's public keys (JWKS), checks the signature,expandiss, and mapsscopeclaims toSCOPE_xxxauthorities. - For stateless token APIs:
SessionCreationPolicy.STATELESS, and CSRF can be disabled because no cookies carry authentication. Store passwords withBCryptPasswordEncoderorDelegatingPasswordEncoder, 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. @SpringBootTeststarts the full application context. AddwebEnvironment = RANDOM_PORTfor a real server. In Boot 4, add@AutoConfigureMockMvc(or@AutoConfigureRestTestClient) explicitly to getMockMvcor 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+).@MockBeanwas 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
@MockitoBeanset or set of properties creates a new context, which slows the suite.
Interview questions
@SpringBootTestvs@WebMvcTest?- Why use Testcontainers instead of H2?
@MockBeanvs@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, onlyhealthis exposed by default; expose others withmanagement.endpoints.web.exposure.include. - Useful endpoints:
health,info,metrics,prometheus(withmicrometer-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/livenessand/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 separatemanagement.server.portthat 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
@ServiceConnectionand Docker Compose support. Boot 3.2 (Nov 2023): virtual threads viaspring.threads.virtual.enabled=trueon Java 21, plusRestClientandJdbcClient. - Boot 4.0 (Nov 2025): Spring Framework 7, Jakarta EE 11 / Servlet 6.1, still Java 17 minimum (newest LTS recommended), Jackson 3 (
tools.jacksonpackages), 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
@Asyncexecutors use them, so blocking I/O no longer ties up a scarce platform thread. Watch for pinning (mostly fixed in Java 24 forsynchronized) 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?