Spring Boot builds on the Spring Framework to simplify application setup through auto-configuration, dependency management, and operational features. For backend developers, the important questions go beyond starting a server: what was configured, which objects handle a request, where security is enforced, and how database work behaves when an operation fails.
This guide to 100+ Spring Boot Interview Questions and Answers contains 120 questions across beginner, intermediate, and experienced levels. It covers Java-based application structure, dependency injection, configuration, REST APIs, validation, security, data access, transactions, testing, observability, and production design for Spring Boot developer roles.
How can recruiters detect AI-assisted cheating, deepfakes, and impersonation during Spring Boot interviews?
Spring Boot interviews often pair a Java or REST endpoint exercise with questions about bean lifecycles, security filters, transaction boundaries, and test behavior. A candidate may need to explain why an auto-configuration did not apply or why a method call did not start the expected transaction. Unauthorized real-time help can obscure whether the candidate understands the framework behavior behind the annotations.
Sherlock AI helps recruiters detect potential AI-assisted cheating, deepfakes, candidate impersonation, and unauthorized real-time assistance during Spring Boot developer interviews.
Pair interview-integrity checks with a small service scenario and follow-up questions about validation, authorization, rollback, and dependency failures. Ask candidates to trace execution and identify which tests or diagnostics would verify their explanation. Review suspicious activity in context rather than treating a signal as proof of misconduct.
Spring Boot Interview Questions
Use this question bank to select topics for the role's API, persistence, integration, and operational responsibilities. Start with application setup and dependency injection, then add security, transaction, and failure scenarios. Confirm the Spring Boot release, Java version, and application stack before discussing behavior that depends on them.
Spring Boot Interview Questions for Beginners
These beginner questions cover Spring Boot's role, starters, auto-configuration, beans, dependency injection, configuration properties, and basic web endpoints. They establish what happens at startup and how application components participate in handling a request.
What does Spring Boot add to the Spring Framework, and which responsibilities remain with Spring itself?
How would you choose a Java version, build tool, and dependencies when generating a Spring Boot project?
How do Spring Boot starters differ from the dependency versions managed by its BOM?
Which capabilities does @SpringBootApplication combine, and why is it normally placed on the main application class?
What happens when the main method calls SpringApplication.run()?
What does auto-configuration inspect before creating a bean?
Why is constructor injection useful for required dependencies in a Spring Boot service?
How do @Component, @Service, and @Repository express different roles in an application?
When would you declare a @Bean method instead of annotating a class with @Component?
Why can moving a controller or repository outside the main package make it disappear from the application?
How do @Primary and @Qualifier resolve a dependency when several beans implement the same interface?
What does singleton scope mean in Spring, and does it make a service automatically thread-safe?
What can you configure in application.properties or application.yaml, and why should environment-specific values stay outside Java code?
How can an environment variable or command-line argument override a packaged configuration value?
What are Spring profiles, and when would you use profile-specific configuration?
When is @ConfigurationProperties preferable to several @Value fields?
How does an executable Spring Boot JAR use an embedded web server?
How does @RestController differ from @Controller in a Spring MVC application?
How do @GetMapping and @PostMapping connect HTTP requests to controller methods?
When should a controller use @PathVariable, @RequestParam, or @RequestBody?
Why return ResponseEntity when a controller needs to control status codes and headers?
How do Jakarta Bean Validation constraints and @Valid help reject invalid request data?
What problem do @ExceptionHandler and @RestControllerAdvice solve?
Why might an API expose request and response DTOs rather than JPA entities directly?
What does Spring Data JPA provide on top of JPA and a database driver?
How do JPA, Hibernate, an entity, and a repository fit together in a typical Spring Boot application?
How can a repository derive a query from a method name without a handwritten implementation?
Which connection details does a Spring Boot application need to connect to an external SQL database?
Why place a transaction around a business operation that changes more than one database record?
What is the difference between authentication and authorization in Spring Security?
What is a SecurityFilterChain, and how does it participate in handling a servlet request?
Why must stored passwords use a suitable PasswordEncoder instead of plaintext or reversible encryption?
How do CORS and CSRF address different browser-security problems?
How do a unit test, a slice test, and a full Spring Boot integration test differ?
What can MockMvc verify without starting a real HTTP server?
What does Spring Boot Actuator add, and why should management endpoints not all be public?
How should application logs help diagnose a failure without exposing passwords, tokens, or personal data?
What do Spring Boot DevTools provide during development, and why are they not a production requirement?
Why do current Spring Boot applications use jakarta.validation and jakarta.persistence rather than the old Java EE namespaces?
Does using Spring Boot require a microservices architecture, or can it support a modular monolith?
Spring Boot Interview Questions for Intermediate
These intermediate questions examine conditional configuration, REST contracts, Spring Security, persistence, transactions, outbound calls, and testing. They focus on predictable behavior at component boundaries and on diagnosing failures without relying on annotation names alone.
An expected auto-configured bean is missing. How would you use the condition evaluation report to find the reason?
How can you replace one auto-configured bean without disabling an entire feature unnecessarily?
The same property is defined in a profile file, an imported file, and an environment variable. How would you determine the effective value?
How would you bind and validate a typed configuration object so an invalid timeout fails at startup?
Two services depend on each other through their constructors. How would you remove the cycle rather than hide it with field injection?
What changes when a @Configuration class uses proxyBeanMethods = false, and how should its @Bean methods receive dependencies?
How can a singleton service obtain a new prototype-scoped object for each operation?
When should startup work use ApplicationRunner or CommandLineRunner rather than a bean constructor?
How would you return a consistent ProblemDetail response for validation failures, missing resources, and conflicts?
How would you validate nested request objects and distinguish field validation from controller-method validation?
How would you implement bounded, consistently sorted pagination, and when would Slice avoid an unnecessary count query?
How would you detect an N+1 query problem and choose between a fetch join, an entity graph, and a projection?
Why can accessing a lazy relationship fail after a service returns, and how would you shape the transaction and DTO mapping?
When would you choose a derived query, a JPQL @Query, a native query, or a projection?
Why can a bulk @Modifying query leave already-loaded entities stale in the persistence context?
What rollback behavior should you expect when a transactional method throws a checked exception, and how can it be changed explicitly?
Why might @Transactional have no effect when one method calls another method on the same object?
How do REQUIRED and REQUIRES_NEW propagation differ, including their effects on database connections?
How would optimistic locking help detect two clients updating the same record?
Why should production schema changes use controlled migrations instead of relying on Hibernate ddl-auto=update?
How do securityMatcher and authorization requestMatchers differ when defining multiple SecurityFilterChain beans?
How would you combine request authorization with method-level authorization, and avoid confusing roles with authorities?
What must a resource server validate before trusting a JWT, beyond merely decoding its payload?
How would you decide whether a browser-facing API needs CSRF protection based on how credentials are sent?
Why can a browser preflight request fail before authentication, and how should CORS be integrated with Spring Security?
How would you test successful access, forbidden access, unauthenticated access, and CSRF failures for a secured endpoint?
How would you use @WebMvcTest and @MockitoBean to test a controller while keeping unrelated services out of the context?
How can Testcontainers and @ServiceConnection make a database integration test more representative than an in-memory substitute?
Why does a test annotated @Transactional not automatically roll back server-side work in a RANDOM_PORT test?
How do @Cacheable, @CachePut, and @CacheEvict differ, and how would you choose a safe cache key?
What should you configure and test before moving service work to @Async?
What do fixedRate, fixedDelay, and cron mean for @Scheduled work, and what happens when several application instances run it?
When would you choose RestClient, WebClient, or an HTTP service interface for an outbound integration?
How would you set outbound timeouts and translate downstream HTTP failures without leaking an internal exception to clients?
How would you expose only the Actuator endpoints required by operators while protecting sensitive details?
How do liveness and readiness probes differ, and why should a database outage not necessarily fail liveness?
How do metrics, logs, and traces complement each other when investigating a slow request?
How does graceful shutdown interact with request completion and the platform termination timeout?
What are the trade-offs between building a container image with a Dockerfile and using Spring Boot buildpacks?
Which starter, import, testing, and JSON changes would you check before moving a Boot 3.5 application to Boot 4?
Spring Boot Interview Questions for Experienced
These experienced-level questions address architecture, concurrency, resilience, performance, security, observability, deployment, and recovery. They test how an engineer validates a design under load and partial failure while keeping service boundaries and data consistency understandable.
How would you design and test a reusable auto-configuration module that activates only when its dependencies exist and backs off for user-defined beans?
How would you organize a growing Spring Boot codebase into business modules without making every module a separate service?
How would you upgrade the Boot BOM and related Spring Cloud dependencies without accidentally mixing incompatible framework versions?
Startup time has doubled after a release. How would you investigate bean initialization and decide whether lazy initialization or AOT actually helps?
When is a native image a good deployment choice, and which reflection, resource, build-time, and runtime constraints would you validate first?
How would you evaluate virtual threads for a blocking Spring MVC workload without overwhelming database or downstream connection limits?
How would you choose between Spring MVC and WebFlux for a service that depends on blocking database access?
An API's p99 latency rises while average latency stays acceptable. How would you investigate with request metrics, traces, and resource saturation signals?
How would you diagnose connection-pool exhaustion and distinguish a leak, long transaction, slow query, and excessive concurrency?
How would you design retries so a transient failure does not multiply a non-idempotent business operation or reuse a failed transaction?
How do timeouts, retries, circuit breakers, and bulkheads address different failure modes, and how would you order and test them?
A client retries a payment-creation request after a timeout. How would you make the API's database-side effects idempotent under concurrent duplicates?
How would you prevent a database commit and a message publication from diverging, and why is an after-commit listener not itself a durable outbox?
What happens to transaction and security context when work crosses an asynchronous thread boundary, and how would you make the intended behavior explicit?
How would you choose transaction isolation or locking for a reservation workflow whose invariant spans several rows?
How would you roll out an incompatible database change while old and new application instances run at the same time?
How would you prevent mass assignment and accidental data disclosure when accepting updates to a rich persistence model?
How would you enforce tenant isolation consistently across repositories, authorization checks, and caches?
How would you secure an application that serves both session-authenticated browser pages and bearer-token APIs without leaving unmatched routes unprotected?
How do OAuth2 login, an OAuth2 resource server, and an authorization server differ, and which responsibilities belong in a typical business API?
How would you plan for JWT signing-key rotation, issuer outages, and authorization changes while avoiding acceptance of untrusted tokens?
How would you rotate database credentials or other secrets without assuming that changing a property source automatically reconfigures every bean?
An internal management endpoint has become publicly reachable. How would you contain exposure and verify the resulting Actuator security policy?
Why can tagging a metric with user IDs or raw request paths cause operational problems, and how would you preserve useful diagnostics?
How would you keep trace context across outbound HTTP calls and asynchronous work, and verify that custom client construction has not bypassed instrumentation?
How would you separate security audit records from diagnostic logs while keeping sensitive values out of both?
How would you handle cache invalidation, tenant-aware keys, and a sudden cache miss surge without returning another user's data?
A scheduled export must survive restarts and run only once per logical job across replicas. What guarantees are missing from @Scheduled and @Async alone?
What testing strategy would give confidence in controller contracts, database behavior, authorization, and downstream failures without loading the full application for every test?
How would you diagnose a slow or flaky Spring test suite caused by context-cache misses, shared state, or external-service timing?
How would you verify a Boot 4 Jackson migration preserves public JSON contracts instead of assuming that successful compilation proves compatibility?
How would you configure a Spring Boot application behind a reverse proxy without trusting attacker-supplied forwarding headers?
How would you coordinate readiness removal, in-flight HTTP requests, background executors, and database work during a rolling shutdown?
How would you design dependency health checks so a shared downstream outage does not trigger restart loops or remove all replicas unnecessarily?
How would you make an application rollback safe when a release changes code, configuration, dependencies, and database schema together?
How would you investigate a production-only 500 error using correlation IDs and targeted diagnostics without exposing customer payloads or enabling unrestricted debug access?
How would you load-test a Spring Boot service to verify concurrency limits, error budgets, and correctness rather than reporting throughput alone?
How would you ensure business authorization still applies when the same operation is invoked by an HTTP controller, a scheduled task, and another bean?
A vulnerability affects a transitive dependency managed by Spring Boot. How would you select, verify, and roll out a fix without assuming an arbitrary version override is compatible?
How would you explain an UnexpectedRollbackException after an inner transactional operation failed and its exception was caught, and redesign the business flow?
Spring Boot Interview Questions and Answers
The answers follow the same order as the question bank. They explain the mechanism first, then use code or a scenario to show its effect. Read examples with their stated dependencies, bean configuration, persistence provider, and servlet or reactive execution context in mind.
Spring Boot Interview Questions and Answers for Beginners
The beginner answers connect annotations and configuration to concrete application behavior. They distinguish Spring Framework features from Boot's setup support, explain how dependencies are supplied, and trace basic request binding, validation, and response handling.
1. What does Spring Boot add to the Spring Framework, and which responsibilities remain with Spring itself?
Spring Boot reduces the setup needed to run a Spring application. It supplies conditional auto-configuration, dependency starters, coordinated dependency versions, executable packaging, and operational integrations such as Actuator. Those features help a team start with a working application and replace defaults deliberately as requirements emerge.
The Spring Framework still supplies the application container, dependency injection, bean lifecycle, transaction abstraction, and Spring MVC. Spring Security and Spring Data are separate Spring projects that Boot can configure; their capabilities do not originate in Boot. In an order-management application, Boot can prepare the web server and database infrastructure, while application services define ordering rules. Boot does not choose business boundaries, validate domain invariants, or make an application production-ready without engineering work.
2. How would you choose a Java version, build tool, and dependencies when generating a Spring Boot project?
Start with the deployment runtime and the supported Spring Boot release, then generate the project with Spring Initializr. This guide uses Boot 4.1.2, which requires Java 17 or later. Choose a supported Java release that development, CI, and production can all run, and pin it with the build toolchain. The documented build minimums are Maven 3.6.3 or Gradle 8.14 in the 8.x line; Gradle 9.x is also supported.
For a servlet-based order API, select Spring Web MVC and add validation, persistence, and security only when required. Boot 4 uses spring-boot-starter-webmvc; Boot 3 projects commonly use spring-boot-starter-web. Keep generated dependency management, commit the build wrapper, and add the database driver explicitly. An existing organization’s supported build tool is usually preferable to introducing another tool without a concrete benefit.
3. How do Spring Boot starters differ from the dependency versions managed by its BOM?
A starter adds dependencies for a capability; a BOM supplies compatible versions for dependencies that the project actually uses. Adding spring-boot-starter-data-jpa, for example, brings the persistence-related libraries into an order service. Importing spring-boot-dependencies alone does not add JPA, a web server, or every managed library to the application.
Maven’s Boot parent includes dependency management and useful build defaults. A project that cannot inherit that parent can import the BOM, but must arrange its build plugins separately. Gradle likewise needs dependency-management integration or a BOM platform. The Boot build plugin handles executable packaging; a BOM does not. Normally, omit explicit versions for managed dependencies and investigate compatibility before overriding one library independently.
4. Which capabilities does @SpringBootApplication combine, and why is it normally placed on the main application class?
@SpringBootApplication combines @SpringBootConfiguration, @EnableAutoConfiguration, and @ComponentScan. These let the class contribute configuration, activate Boot’s conditional configuration, and discover application components. @SpringBootConfiguration also gives Boot tests a recognizable primary configuration.
Place the application class in a named root package above the project’s controllers and services. In the example, components under com.example.orders are within the default scan. The package also helps establish the default search area used by several auto-configured persistence features. Putting this class in a deeply nested package can leave sibling packages undiscovered; placing it in the unnamed default package can scan far too broadly.
Java example
5. What happens when the main method calls SpringApplication.run()?
SpringApplication.run() bootstraps a Spring application and returns its configurable application context. It prepares configuration properties and profiles, selects an appropriate application-context type, loads bean definitions, and refreshes the context. During refresh, Spring creates and wires the required beans and Boot applies matching auto-configuration.
For a servlet web application with the necessary dependencies, this process also starts the embedded server. A command-line application does not need a server. Boot runs registered ApplicationRunner and CommandLineRunner beans before reporting the application ready. In an order service, a missing required database configuration or an unresolved constructor dependency can stop startup. Successful startup establishes that initialization completed; it does not prove every business operation or downstream dependency will work.
6. What does auto-configuration inspect before creating a bean?
Auto-configuration evaluates conditions rather than creating every possible bean. Conditions can check whether a class is available, whether a property is set, what kind of application is running, and whether suitable beans already exist. Different auto-configurations use different combinations; there is no single universal checklist that every bean follows.
For an order service, JDBC-related classes and database settings may make database auto-configuration eligible. A user-defined DataSource commonly causes the corresponding default bean configuration to back off. That is conditional replacement, not permission to register conflicting beans with identical names. When a default appears unexpectedly or is missing, inspect the condition evaluation report with --debug. Check the relevant conditions before adding exclusions or duplicating configuration.
7. Why is constructor injection useful for required dependencies in a Spring Boot service?
Constructor injection makes required collaborators explicit and allows a service to be created in a usable state. Dependencies can be stored in final fields, and a unit test can construct the service directly with a stub or mock. A missing required bean usually becomes a startup failure rather than a null-field surprise during a request.
For a scanned Spring component with one constructor, @Autowired is unnecessary. In this order-project fragment, PaymentGateway is an application-defined interface with an available Spring bean. The constructor says that checkout cannot exist without it. Final references do not make a mutable collaborator thread-safe, and a constructor with many dependencies may indicate that the service has too many responsibilities.
Java example
8. How do @Component, @Service, and @Repository express different roles in an application?
All three annotations mark classes that component scanning can register as Spring beans. @Component is the general-purpose stereotype. @Service communicates that a class implements application or business operations. @Repository identifies a persistence-facing component and makes it eligible for Spring’s persistence-exception translation when that infrastructure is configured.
In an inventory application, an identifier generator might be a component, stock reservation logic a service, and a custom JDBC data-access class a repository. @Service does not automatically add a transaction, and @Repository does not create a database table or implement arbitrary methods. A Spring Data repository interface is a separate case: repository infrastructure generates its implementation. These names improve architectural readability, but package design and tests must enforce the intended boundaries.
9. When would you declare a @Bean method instead of annotating a class with @Component?
Use a @Bean method when the application should explicitly construct or configure an object, particularly a third-party class that cannot be annotated. The returned object becomes container-managed and can be injected like a scanned component. Method parameters can receive other beans, keeping object construction separate from business code.
For an order service, providing a Clock avoids hard-coding calls to the system clock throughout expiry logic. Tests can substitute a fixed clock. The example belongs in a configuration class within the application’s scan. @Component is usually simpler for an application-owned class with ordinary constructor dependencies; adding both mechanisms for the same object can accidentally create two beans.
Java example
10. Why can moving a controller or repository outside the main package make it disappear from the application?
Spring discovers classes within configured search boundaries, not every package on the classpath. By default, component scanning starts at the package containing @SpringBootApplication and includes its descendants. Moving a controller to a sibling package can therefore remove its bean and its HTTP mappings.
Entity and Spring Data repository discovery are related but distinct mechanisms. Changing scanBasePackages on @SpringBootApplication adjusts component scanning; it does not automatically redefine JPA entity and repository scanning. For an order application, prefer a root such as com.example.orders above all application modules. If a shared persistence module must live elsewhere, configure its entity and repository packages explicitly using the appropriate scanning annotations. A controller annotation alone cannot compensate for an excluded package.
11. How do @Primary and @Qualifier resolve a dependency when several beans implement the same interface?
Spring first considers beans compatible with the requested type. @Primary gives one candidate preference for a single-valued injection when multiple eligible candidates remain. @Qualifier narrows the candidates at a particular injection point, so the caller can request a specific implementation or category. A qualifier can match a bean name, but its broader role is filtering type-compatible candidates.
For an invoicing application with email and SMS implementations of NotificationSender, mark the usual sender primary and qualify the exceptional use. In this constructor fragment, a bean named or qualified smsSender must exist. A primary bean is not an instruction to discard other implementations from an injected collection.
Java example
This fragment belongs in ReminderService, which declares a NotificationSender sender field.
12. What does singleton scope mean in Spring, and does it make a service automatically thread-safe?
Singleton is Spring’s default bean scope: the container keeps one instance for a given bean definition in that application context. It does not mean one instance per Java class across the entire JVM. Two definitions of the same class can produce two instances, and separate application contexts can have separate singletons.
A singleton service is normally shared by concurrent web requests, so scope does not make its fields thread-safe. An order service should keep request-specific values in method variables rather than fields such as currentCustomer. Stateless services with immutable dependencies are easier to reason about. Shared counters, caches, and mutable collections require an appropriate concurrency design. Changing the scope is not a substitute for understanding how that state is accessed.
13. What can you configure in application.properties or application.yaml, and why should environment-specific values stay outside Java code?
These files can hold Boot configuration, such as server settings and logging levels, plus application-specific values such as reservation durations. Keeping deployment choices outside Java lets the same built artifact run in different environments without a source change. A property does not create a feature by itself: the matching dependency and configuration must be present, and custom properties need code that reads or binds them.
For an order service, the following YAML supplies a non-secret default. Production can override it through an external property source. Database credentials and tokens should come from an approved secret-delivery mechanism, not a committed configuration file. Use one configuration format consistently to make overrides easier to trace.
YAML example
14. How can an environment variable or command-line argument override a packaged configuration value?
Boot combines property sources with a defined precedence. In a normal application launch, operating-system environment variables override packaged configuration, and command-line option properties override both. For example, SERVER_PORT maps to server.port; an explicit --server.port argument wins in the launch below. Test property sources and deliberately customized startup settings can change the wider picture.
In a container deployment, this lets one order-service image listen on an environment-selected port without rebuilding. When an override seems ignored, check the effective property name and the sources supplying it rather than editing several files. Avoid passing secrets on a command line, where process listings or shell history may expose them.
Bash example
With ordinary Boot command-line property handling enabled, this process listens on port 9091.
15. What are Spring profiles, and when would you use profile-specific configuration?
Profiles select named groups of configuration and can conditionally register beans through @Profile. A deployment can activate prod and load application-prod.yaml alongside common configuration. Profiles are useful when environments genuinely need different settings or implementations, such as a local mail stub versus the deployed mail integration.
For an order service, keep common defaults in the main configuration and activate the deployment profile externally. Do not treat a profile as a security boundary or place production secrets in a committed profile file. Multiple profiles may be active, so conflicting values need a deliberate ordering. Put spring.profiles.active in a non-profile-specific source, rather than inside the file that requires that profile to be active.
Bash example
16. When is @ConfigurationProperties preferable to several @Value fields?
@ConfigurationProperties is preferable when several values describe one feature. It binds a prefix to a typed object and supports structured values such as durations and nested configuration. Compared with scattered @Value expressions, this makes an order service’s settings easier to discover, inject, and test. A single unrelated value can still be a reasonable use of @Value.
The record below binds orders.reservation-timeout. Register it with @EnableConfigurationProperties(OrderProperties.class) on a configuration class, or enable configuration-properties scanning. Do not also make a constructor-bound record a regular @Component. Constraints and @Validated, with a validation provider available, can reject invalid settings during startup; binding alone does not enforce business limits or supply a missing default.
Java example
17. How does an executable Spring Boot JAR use an embedded web server?
A repackaged executable Boot JAR contains application classes, runtime dependencies, and Boot launcher metadata. When started with java -jar, the application creates its Spring context and, for a configured web application, starts an embedded server inside the same process. Operations teams do not need to install a separate application server for that deployment style.
In Boot 4, the MVC starter normally supplies Tomcat; a supported alternative can be selected through dependencies. An order service still needs configuration, secrets, network access, and an appropriate Java runtime. Packaging alone does not create a web server if the application has no web stack. Boot can also support traditional WAR deployments and non-web programs, so executable JAR packaging is a deployment choice rather than a mandatory architecture.
18. How does @RestController differ from @Controller in a Spring MVC application?
@Controller identifies an MVC controller whose return values are interpreted according to their type and annotations. A returned string commonly names a view for server-side rendering. @RestController combines @Controller with @ResponseBody, so mapped methods normally write their return values to the HTTP response through message converters instead of resolving views.
For an order API, returning an OrderResponse from a REST controller can produce JSON when an appropriate converter and media-type negotiation are available. A @RestController returning a plain string does not automatically produce a JSON object. A regular controller can also return a response body by annotating individual methods or by returning ResponseEntity. Neither annotation supplies authentication, authorization, or input validation on its own.
19. How do @GetMapping and @PostMapping connect HTTP requests to controller methods?
@GetMapping and @PostMapping are composed request-mapping annotations that constrain both the URL pattern and the HTTP method. A class-level @RequestMapping("/orders") supplies a shared prefix, while method mappings identify operations beneath it. Spring MVC selects a matching handler and then binds its arguments.
In an order API, GET /orders/{id} retrieves a representation, while POST /orders can submit a new order. A mapping can also constrain accepted content types and produced response types. The annotation does not enforce correct HTTP semantics: application code must keep GET operations safe rather than making them delete or purchase something. Mapping two handlers to indistinguishable requests creates ambiguity, so route, method, and media-type decisions should be tested together.
20. When should a controller use @PathVariable, @RequestParam, or @RequestBody?
Use @PathVariable for values embedded in a route, such as the order identifier in /orders/42. Use @RequestParam for query or form parameters, such as a status filter or page size. Use @RequestBody when a message converter should deserialize the request payload into a DTO, such as a JSON order-creation request.
In a controller method, @PathVariable("id") Long id explicitly binds the route variable, while @RequestParam(defaultValue = "20") int size supplies a query-parameter default. A body parameter can be @Valid @RequestBody CreateOrderRequest request. Binding and type conversion do not establish authorization or domain validity. Bound identifiers must still be checked against the caller’s access, and client-supplied page sizes need sensible upper limits.
21. Why return ResponseEntity when a controller needs to control status codes and headers?
ResponseEntity lets a controller return a body together with an explicit HTTP status and headers. It is useful when a result should be 201 Created with a Location header, 204 No Content, or another response that cannot be expressed clearly by returning a DTO alone. Ordinary DTO returns are fine when the default successful status is sufficient.
For an order-creation handler, the following return statement assumes saved is an application response DTO whose id() supplies the newly created identifier, and java.net.URI is imported. It belongs after successful creation, not before the database operation completes. Error responses should follow the API’s error contract rather than disguising failures as successful status codes.
Java example
The controller imports org.springframework.http.ResponseEntity.
22. How do Jakarta Bean Validation constraints and @Valid help reject invalid request data?
Jakarta Bean Validation declares constraints such as @NotBlank and @Positive on request data. With a validation provider available, Spring MVC can validate a DTO parameter annotated @Valid @RequestBody before the controller’s business logic proceeds. For Boot projects, add spring-boot-starter-validation explicitly rather than assuming the web starter includes it.
In an order API, the request below rejects a blank product code or a nonpositive quantity. @Valid triggers validation of the object; it is not itself a not-null constraint. Validation failures normally become client-error responses, which the application can format consistently. These checks do not prove that a product exists, stock is available, or the caller may purchase it; those are service-level business and authorization checks.
Java example
23. What problem do @ExceptionHandler and @RestControllerAdvice solve?
@ExceptionHandler maps an exception to an HTTP response, and @RestControllerAdvice shares such handling across relevant controllers. This avoids repeating try-catch blocks in every endpoint and helps an API maintain consistent status codes and safe error bodies. An order service might map its domain-specific missing-order exception to 404 and an invalid transition to 409.
Spring’s ProblemDetail can represent a structured error response. Keep client-facing details deliberate; exception messages can expose SQL, file paths, or private identifiers. Validation and other framework exceptions also need a consistent policy. Controller advice operates through MVC exception handling, so it is not a universal handler for every failure in servlet filters, background jobs, or security processing. Test those boundaries separately.
24. Why might an API expose request and response DTOs rather than JPA entities directly?
DTOs separate the public API contract from the persistence model. A request DTO lists fields clients may submit, and a response DTO lists fields clients may see. That separation reduces accidental disclosure and mass assignment when an entity contains internal state such as an approval flag, cost price, or another tenant’s identifier.
For an order API, a creation DTO might contain product codes and quantities, while the response includes an order number and calculated total. The service supplies ownership and pricing from trusted context rather than accepting them blindly. DTOs also avoid exposing lazy relationships or bidirectional entity graphs during serialization. Mapping adds code and must be tested, but it allows database changes and API evolution to proceed with clearer boundaries.
25. What does Spring Data JPA provide on top of JPA and a database driver?
Spring Data JPA provides repository abstractions that reduce repetitive persistence code. A repository interface can inherit CRUD, paging, and sorting operations from JpaRepository, and declare derived queries or explicitly defined queries. Spring creates the repository implementation and integrates it with the configured persistence infrastructure.
JPA defines the persistence API and mapping model; a provider such as Hibernate implements it. The database driver supplies JDBC connectivity. Spring Data JPA does not replace either one. In an order application, a repository can load orders, while a service coordinates business rules and transactions involving several repositories. Repository convenience does not guarantee efficient SQL, suitable indexes, correct locking, or tenant isolation. Those concerns still require explicit design and database-level testing.
26. How do JPA, Hibernate, an entity, and a repository fit together in a typical Spring Boot application?
JPA, now Jakarta Persistence, is the specification for mapping and managing persistent Java objects. Hibernate is a commonly used implementation. An entity is an application class mapped to database state, with an identifier and persistence lifecycle. A Spring Data repository gives application code an interface for accessing those entities without manually writing each routine data-access operation.
In an inventory service, a Product entity maps product state, Hibernate translates persistence operations into SQL, and a ProductRepository exposes operations such as finding by identifier. Boot assembles the infrastructure when the required libraries and database settings are available. The repository is not the entity, and Hibernate is not the database. Relationships, transaction boundaries, and migrations remain application responsibilities even when startup configuration is automatic.
27. How can a repository derive a query from a method name without a handwritten implementation?
Spring Data parses supported parts of a repository method name and resolves them against the entity’s properties. It then creates the query implementation for the repository proxy. In the example, Order is a mapped entity with a String status property and a Long identifier, and repository scanning includes this interface.
The method retrieves matching orders; it does not need a handwritten implementation. A misspelled property usually causes repository initialization to fail rather than silently searching an unrelated column. Derived names become hard to maintain for complex predicates, so use an explicit query or another query abstraction when clearer. Also consider pagination instead of returning an unbounded list from a public API.
Java example
28. Which connection details does a Spring Boot application need to connect to an external SQL database?
A typical external JDBC database needs a connection URL, an appropriate JDBC driver on the runtime classpath, and credentials or another supported authentication mechanism. The URL identifies the database vendor and target. Boot can usually infer the driver class from that URL, so driver-class-name is not always necessary.
For a deployed order service, supply these values through the deployment’s approved configuration and secret mechanism. The placeholders below have no embedded password fallback. Network routes, certificates, database permissions, and connection-pool limits must also be correct; properties alone cannot establish connectivity. Use a least-privileged application account and a verified encrypted connection configuration appropriate to the driver. Manage schema changes with migrations rather than relying on destructive automatic schema recreation.
YAML example
29. Why place a transaction around a business operation that changes more than one database record?
A transaction makes related database changes commit or roll back as one unit. If order creation inserts an order and reserves stock, committing only the first change can leave inconsistent state. Place the transaction around the service-level business operation, using a transaction manager that covers the participating database work.
Spring’s @Transactional commonly applies through a proxy, so the caller must reach the transactional method through that proxy; a same-object method call does not normally start the annotated transaction. By default, unchecked exceptions and errors cause rollback, while checked exceptions need appropriate rollback configuration. A transaction also needs suitable isolation or locking for concurrent changes. It does not automatically roll back an email, a remote payment, or a message sent outside that database transaction.
30. What is the difference between authentication and authorization in Spring Security?
Authentication establishes who is making a request, using evidence such as a session established at login or a validated bearer token. Authorization decides whether that identity may perform the requested action. Spring Security represents the authenticated principal and authorities, and applies access rules through its authorization infrastructure.
In an order API, being logged in does not automatically permit reading every order. The application must check ownership, tenant scope, or an appropriate administrative permission. Request-level rules can restrict endpoints, while service-level rules can protect business operations reached from multiple callers. Missing or invalid authentication commonly produces an authentication challenge or login redirect; a recognized user without permission commonly receives 403. The exact response depends on the configured security mechanism.
31. What is a SecurityFilterChain, and how does it participate in handling a servlet request?
A SecurityFilterChain defines the security filters that apply to matching servlet requests. Spring Security’s FilterChainProxy selects a matching chain and runs its filters before the request reaches the MVC controller. Filters can establish the security context, authenticate credentials, enforce CSRF protection, and authorize access.
For a session-authenticated order application, the bean below allows the sign-in route and requires authentication elsewhere. It uses the current lambda-style HttpSecurity configuration and leaves CSRF protection enabled. Place it in a scanned @Configuration class and provide the project’s real authentication setup. With multiple chains, the first matching chain is selected; a missing catch-all can leave unmatched requests outside security protection.
Java example
Imports are org.springframework.context.annotation.Bean, org.springframework.security.web.SecurityFilterChain, org.springframework.security.config.annotation.web.builders.HttpSecurity, and org.springframework.security.config.Customizer.
32. Why must stored passwords use a suitable PasswordEncoder instead of plaintext or reversible encryption?
A password store should let the application verify a supplied password without recovering the original. Plaintext exposes every password immediately after a data breach, while reversible encryption introduces a decryption key that can expose them all. Suitable adaptive password hashing uses salts and a deliberately expensive verification process to make guessing more costly.
In a customer-login service, use a PasswordEncoder such as an appropriately configured Argon2 or bcrypt encoder, and call matches(rawPassword, storedHash) for verification. Do not compare two newly generated salted hashes for equality. Spring’s DelegatingPasswordEncoder supports identifying stored formats and migrating algorithms over time. Tune cost against the deployment’s capacity, protect login against abuse, and never log raw passwords. A fast general-purpose hash alone is not a suitable password-storage policy.
33. How do CORS and CSRF address different browser-security problems?
CORS controls whether browser JavaScript from one origin may read responses from another origin under the server’s cross-origin policy. It is not authentication, and it does not stop non-browser clients from calling an API. Configure the actual trusted frontend origins rather than reflecting arbitrary origins, particularly when credentials are involved.
CSRF addresses a different risk: a browser may automatically attach credentials, such as session cookies, to an unwanted state-changing request. A session-based order application therefore needs CSRF protection even when its CORS policy is strict. Spring Security enables CSRF protection for unsafe methods by default. A genuinely bearer-token-only API may have a different CSRF threat model, but disabling protection requires checking how credentials are carried. CORS preflight handling must also occur before authentication rejects unauthenticated preflight requests.
34. How do a unit test, a slice test, and a full Spring Boot integration test differ?
A unit test exercises a small object directly, usually without starting Spring. It is appropriate for an order-pricing rule with stubbed collaborators. A slice test starts a focused Spring context: @WebMvcTest checks selected MVC infrastructure, while @DataJpaTest checks persistence behavior. A full @SpringBootTest loads the broader application configuration to test how components integrate.
Choose the narrowest test that can detect the failure. A full-context test is not automatically a real-server test: the default web environment is mock-based; RANDOM_PORT starts a server. Boot 4 moves MVC slice annotations into org.springframework.boot.webmvc.test.autoconfigure and provides technology-specific test starters. Boot 3 uses older slice package locations. For mock bean replacement in current code, use Spring Framework’s @MockitoBean rather than copying old @MockBean examples.
35. What can MockMvc verify without starting a real HTTP server?
MockMvc exercises Spring MVC request processing using mock servlet requests and responses, without opening a network port. It can verify mappings, input conversion, validation, status codes, headers, JSON bodies, and controller-advice behavior. Security filters can participate when included in the test setup. It does not test actual socket handling, TLS, reverse proxies, or the embedded server’s network configuration.
For an order-controller test using Boot 4’s spring-boot-starter-webmvc-test, the following assertion belongs in a test method with an injected MockMvc. The configured security permits this request, and the test arranges an order with identifier 42. A standalone MockMvc setup needs its infrastructure configured explicitly; it should not be assumed equivalent to the production application context.
Java example
Use static imports from org.springframework.test.web.servlet.request.MockMvcRequestBuilders and org.springframework.test.web.servlet.result.MockMvcResultMatchers.
36. What does Spring Boot Actuator add, and why should management endpoints not all be public?
Actuator adds operational features such as health information, metrics integration, and diagnostic endpoints. For an order service, these help operators see whether the application is healthy and investigate behavior without adding ad hoc management controllers. An endpoint being available internally and being exposed over HTTP are separate concerns.
Boot exposes only health by default over HTTP and JMX. Broad exposure can reveal configuration, mappings, thread state, or other sensitive operational details; some endpoints can change application behavior. Expose only what operations requires, apply network restrictions and authorization, and control health-detail visibility. The properties below explicitly retain a narrow HTTP exposure. They are not a complete security policy and do not replace testing access from an untrusted client.
Properties example
37. How should application logs help diagnose a failure without exposing passwords, tokens, or personal data?
Useful logs describe the failed operation, its outcome, and enough safe context to correlate it with related events. In an order service, that can include an internal error code, a correlation identifier, and the dependency involved. Record an exception with its stack trace at the responsible boundary instead of repeating the same failure at every layer.
Passwords, bearer tokens, session cookies, payment data, and unnecessary personal data should not enter logs. Avoid dumping entire request bodies or HTTP headers; structured allowlisted fields are easier to review. Parameterized logging helps formatting but does not automatically redact secrets or neutralize every untrusted value. Restrict log access and retention, and enable additional diagnostic logging narrowly and temporarily so investigation does not create a second incident.
38. What do Spring Boot DevTools provide during development, and why are they not a production requirement?
DevTools improve the local development cycle with features such as automatic application restart after classpath changes, development-oriented property defaults, and LiveReload integration. Restart uses separate classloaders for changing application code and relatively stable libraries; it is not a guarantee that every edit can be applied without rebuilding or restarting.
For a multi-module order application, an IDE must actually update the classpath for changes to be noticed, and classloader boundaries can occasionally need adjustment. DevTools are not required to serve production requests. Use Maven’s optional dependency treatment or Gradle’s developmentOnly configuration, and retain the packaging defaults that exclude DevTools from repackaged archives. Do not force development restart features on in production; their convenience settings and remote-development capabilities are unsuitable for an exposed production runtime.
39. Why do current Spring Boot applications use jakarta.validation and jakarta.persistence rather than the old Java EE namespaces?
Spring Boot 3 moved its Jakarta EE integrations to the newer jakarta.* APIs, and Boot 4 continues that direction. Current validation constraints therefore come from jakarta.validation.constraints, and persistence annotations come from jakarta.persistence. They are different types from the older Java EE javax.validation and javax.persistence annotations, even when their short names are identical.
In a migrated order application, update imports and compatible dependencies together, including third-party integrations. Adding both old and new API JARs is not a reliable compatibility fix. Also avoid blindly replacing every javax import: Java SE APIs such as javax.sql.DataSource retain their existing namespace. Boot 3 and Boot 4 both use Jakarta for these features, but that does not make every library version or Boot-specific package interchangeable.
40. Does using Spring Boot require a microservices architecture, or can it support a modular monolith?
Spring Boot supports both monoliths and microservices. A Boot application can be one deployable system with clear modules, a small independently deployed service, a batch process, or a command-line tool. Auto-configuration and executable packaging do not require distribution across multiple processes.
For an order-management product, a modular monolith may keep ordering, inventory, and billing behind explicit Java interfaces while sharing one deployment. That can simplify local calls, transactions, debugging, and operations. Separate services become useful when independent ownership, scaling, deployment, or isolation justifies their additional network and consistency costs. Package boundaries alone do not guarantee modularity, so enforce dependency rules and avoid direct access to another module’s internals. Architecture should follow the product’s needs rather than the framework’s name.
Spring Boot Interview Questions and Answers for Intermediate
The intermediate answers explain implementation choices and the conditions that make them work. Examples identify proxy boundaries, transaction ownership, and test setup where relevant, while diagnostic discussions separate application logic from framework and database behavior.
41. An expected auto-configured bean is missing. How would you use the condition evaluation report to find the reason?
Start the application with --debug in a controlled environment and search the condition evaluation report for the relevant auto-configuration and its nested configurations. A negative match normally identifies a missing class, an absent or unexpected property, an existing bean, or an incompatible application type. A positive class-level match does not guarantee that every bean method matched.
Check the runtime dependency tree, active profiles, exclusions, and application-defined beans against those conditions. If the configuration never appears, confirm that its module is present and eligible for discovery. The Actuator conditions endpoint can provide similar evidence on a running application, but it should remain restricted to operators. Fix the unmet prerequisite and add a focused context test; do not solve the problem by importing an auto-configuration's internal bean methods.
42. How can you replace one auto-configured bean without disabling an entire feature unnecessarily?
First check whether the feature exposes a property or a supported customizer; those often preserve more of Boot's useful defaults than replacing a bean. If replacement is necessary, declare an application @Bean of the type or name checked by the auto-configuration's missing-bean condition. Many configurations then back off only for that component.
For example, providing a DataSource can replace connection creation while leaving other eligible JDBC or JPA support available. This is conditional behavior, not a universal rule that every user bean overrides every default. Verify the exact condition and the resulting bean graph. @Primary chooses between candidates; it does not remove an unwanted bean. Avoid enabling same-name bean-definition overriding merely to silence a conflict, and exclude a whole auto-configuration only when taking responsibility for that entire feature.
43. The same property is defined in a profile file, an imported file, and an environment variable. How would you determine the effective value?
Among those three sources, a correctly named environment variable ordinarily overrides file-based config data. Establish which profiles are active, which file contains spring.config.import, and the order and locations of loaded documents before comparing the two files. Imported values override the document that imports them, but other profile and location ordering rules still matter; “imported always wins” is too broad.
Check the canonical property name and environment-variable binding rules, then inspect the effective Environment value and, where applicable, the bound configuration object. Restricted Actuator env and configprops diagnostics can help locate the source without publishing secrets. Also check higher-priority command-line, system, and test properties. Reproduce the actual launch configuration in a small binding test rather than inferring precedence from the order of files in the repository.
44. How would you bind and validate a typed configuration object so an invalid timeout fails at startup?
Use a registered @ConfigurationProperties type with @Validated and a Jakarta Bean Validation provider, normally supplied by the validation starter. Constraints then validate the bound object during startup instead of letting an invalid value fail during the first outbound request.
This record deliberately expresses the timeout in milliseconds and limits it to one minute:
Java example
Register it with @EnableConfigurationProperties(CatalogClientProperties.class) on a configuration class, or use configuration-properties scanning. Bind catalog.client.timeout-millis; an omitted primitive value becomes zero and fails this constraint. If using Duration instead, choose a validator that supports Duration rather than assuming numeric constraints do. Test missing, negative, excessive, and valid values through an application context.
45. Two services depend on each other through their constructors. How would you remove the cycle rather than hide it with field injection?
Constructor cycles mean the container cannot fully construct either service without first constructing the other. Treat that as a design signal: identify the operation that requires both services and move its orchestration into a third component. Each original service can then depend on a smaller, one-directional capability rather than on its peer.
For example, CheckoutCoordinator can call InventoryService and PaymentService; payment no longer needs to call back into checkout. Another option is extracting genuinely shared calculations into a stateless policy object. Use an event only if its timing, failure handling, and consistency semantics suit the business process, not just to conceal the cycle. Field injection, lazy proxies, and allowing circular references can postpone the symptom while preserving confusing responsibilities. Verify the revised dependency graph and transaction ownership.
46. What changes when a @Configuration class uses proxyBeanMethods = false, and how should its @Bean methods receive dependencies?
With proxyBeanMethods = false, Spring still discovers @Bean definitions, but it does not subclass the configuration class to intercept calls between its factory methods. Calling a @Bean method directly is therefore an ordinary Java call and can construct another object outside the intended managed-bean lookup.
Receive dependencies as method parameters instead. Spring resolves those parameters from its container:
Java example
Here ReportService is the application's class with a Clock constructor. The second factory does not call clock() itself. This arrangement makes dependencies explicit and avoids requiring configuration-method interception. It does not disable other Spring proxies, such as transactional proxies on service beans.
47. How can a singleton service obtain a new prototype-scoped object for each operation?
Inject an ObjectProvider for the prototype type and request an instance inside each operation. Directly injecting a prototype into a singleton resolves it when the singleton is created; it does not automatically create a fresh object on every later method call.
In this service excerpt, WorkBuffer must already be registered as a prototype-scoped bean:
Java example
Keep that reference local if it represents one operation. Spring creates and initializes prototypes but does not automatically run their destruction callbacks; the consuming code must release resources they own. For simple non-managed temporary state, constructing a plain local object can be clearer than introducing prototype scope.
48. When should startup work use ApplicationRunner or CommandLineRunner rather than a bean constructor?
Use a runner for startup work that needs the assembled application context: loading a small reference dataset, checking an essential prerequisite, or processing startup arguments. Constructors should establish valid object state, not perform slow network calls or start business workflows while dependencies and proxies are still being assembled.
ApplicationRunner receives parsed ApplicationArguments; CommandLineRunner receives the raw argument array. Both run after context refresh and before application readiness is announced. Their exceptions can fail startup, and their ordering can be specified when there is a genuine dependency between steps.
Keep required work bounded and observable. Large imports or indefinitely retrying tasks belong in a separately managed job rather than delaying every replica's startup. Make initialization idempotent and consider multi-instance races. Database schema evolution should use the migration mechanism, not ad hoc runner logic.
49. How would you return a consistent ProblemDetail response for validation failures, missing resources, and conflicts?
Define an API-wide error contract around ProblemDetail, with stable problem categories, safe descriptions, and optional extensions such as an application error code and correlation ID. Map invalid input to 400, a missing resource to 404, and a genuine state conflict to 409; do not map every database exception to “conflict.”
Use @RestControllerAdvice, commonly extending ResponseEntityExceptionHandler, to customize built-in MVC errors and add handlers for domain exceptions. Handle both MethodArgumentNotValidException and HandlerMethodValidationException, preserving appropriate status differences such as return-value validation being a server error. Field-error extensions should identify invalid fields without echoing sensitive rejected values.
For a domain error, create the body with ProblemDetail.forStatusAndDetail(...) and add a stable code using setProperty. Verify status, application/problem+json, and response shape in controller tests. Keep stack traces, SQL, and downstream response bodies out of the public detail.
50. How would you validate nested request objects and distinguish field validation from controller-method validation?
Put constraints on request fields and use @Valid to cascade into nested values. Cascade validation alone does not reject null objects; use @NotNull where absence is invalid. Container-element constraints can validate every item:
Java example
A controller's @Valid @RequestBody CreateOrder normally invokes argument validation and can raise MethodArgumentNotValidException. Constraints directly on controller parameters, such as @Min(1) on a request parameter, require MVC method validation, which also covers cascaded constraints and can raise HandlerMethodValidationException. In current Spring MVC, avoid a class-level @Validated when intending to use built-in controller method validation; that annotation instead selects proxy-based method validation. Service-layer method validation is a separate concern.
51. How would you implement bounded, consistently sorted pagination, and when would Slice avoid an unnecessary count query?
Validate the requested page number and cap page size before constructing PageRequest. Allowlist sortable properties rather than exposing every persistence attribute. Add a unique tie-breaker, such as the primary key, so records sharing a timestamp have a deterministic order.
For a fixed newest-first listing, the service can build:
Java example
This excerpt assumes nonnegative requestedPage and positive requestedSize have already been validated. A repository return type of Page supplies total counts and may require a count query. Slice only indicates whether another slice exists, commonly by fetching one extra row. Neither guarantees a consistent snapshot across concurrent changes; large or frequently changing datasets may benefit from cursor/keyset pagination.
52. How would you detect an N+1 query problem and choose between a fetch join, an entity graph, and a projection?
Detect N+1 behavior by measuring query count for a representative operation, then inspecting SQL and tracing which relationship access triggers repeated selects. A test that returns one parent can hide it; compare one parent with a larger batch. Avoid logging sensitive bind values in production diagnostics.
Choose a fetch join when a specific query must load a known relationship, an entity graph when the fetch plan should be attached to a repository method, or a projection when only selected response fields are needed. A projection changes the result shape; it is not simply another global fetch setting.
Do not make every relationship eager. Multiple collections can multiply rows, and collection fetch joins interact badly with pagination. For those cases, page parent identifiers first and fetch the required data separately, or use an appropriately shaped projection. Verify query count, returned rows, and memory usage after the change.
53. Why can accessing a lazy relationship fail after a service returns, and how would you shape the transaction and DTO mapping?
A lazy relationship may still be represented by an uninitialized Hibernate proxy or collection when the service returns. If its persistence context is then closed, accessing it cannot issue the required query and can raise a lazy-initialization exception. An open-session-in-view setting may mask this boundary by allowing queries during rendering, but it does not provide a good fetch plan.
Put the read use case in a transaction, fetch the relationships needed for that response, and map to an independent DTO before leaving the service. Alternatively, query directly into a projection. A @Transactional(readOnly = true) service method must be reached through the managed proxy; merely adding the annotation to an internally called helper does not establish a new boundary.
Consider disabling spring.jpa.open-in-view for explicit API-layer boundaries, then test response serialization after the service has returned. DTOs should not retain lazy entity references.
54. When would you choose a derived query, a JPQL @Query, a native query, or a projection?
Use a derived method for a simple predicate whose name stays readable, such as finding active accounts by tenant and email. Choose JPQL @Query for more explicit joins, aggregate logic, or predicates expressed in entity and property terms. A native query is appropriate for database-specific SQL, but it increases coupling to that database and needs representative integration tests.
A projection is a result-shaping decision that can be combined with these query mechanisms: return only the fields needed by the use case rather than materializing full entities. Check constructor or alias requirements for the selected projection style.
Bind values as parameters instead of concatenating input. Review pagination and count behavior, execution plans, indexes, null handling, and tenant filters. If a derived name becomes difficult to understand, making the query explicit is usually better than extending the name further.
55. Why can a bulk @Modifying query leave already-loaded entities stale in the persistence context?
A bulk JPQL update executes against database rows without applying the change to every managed entity instance. Objects already loaded into the persistence context can therefore retain old values, and normal per-entity callbacks or optimistic-version handling may not apply as they would during dirty checking.
A repository method can explicitly flush before the update and clear afterward:
Java example
This repository-method excerpt assumes a matching Account entity and a repository interface containing the declaration. Invoke it inside a non-read-only transaction. Clearing detaches all managed entities; retaining references afterward does not make them current. Without a prior flush, clearing can discard pending changes. Choose an isolated transaction or deliberate refresh/clear strategy, and inspect the affected-row count.
56. What rollback behavior should you expect when a transactional method throws a checked exception, and how can it be changed explicitly?
With Spring's usual declarative rollback defaults, an unchecked RuntimeException or Error triggers rollback, while a checked exception does not automatically do so. A checked failure can therefore escape while database changes commit unless the configured rules say otherwise.
Declare the intended exception type explicitly:
Java example
This service excerpt assumes SettlementException is checked and the call crosses the transaction proxy. Spring Framework 6.2 and later also allow a global ALL_EXCEPTIONS default through transaction-management configuration, so inspect the application's actual policy rather than assuming the historical default. An exception caught inside the method does not automatically reach the interceptor; use an explicit failure design instead of swallowing it. Verify rollback by reading the database outside the failed transaction.
57. Why might @Transactional have no effect when one method calls another method on the same object?
In the usual proxy-based transaction mode, the interceptor runs when a caller invokes the Spring-managed proxy. A call such as this.saveBatch() stays inside the target object and bypasses that proxy, so the inner method's @Transactional settings are not applied.
If the outer method already has a transaction, the inner work may still participate in it. The important point is that the inner annotation cannot independently change propagation, isolation, or rollback rules on that self-call. If there is no outer transaction, its annotation does not create one.
Move the transactional operation to another injected service and call its managed bean, or use TransactionTemplate when explicit programmatic boundaries fit better. Avoid treating self-injection as the default design fix. Also check proxyability, bean management, and method visibility; private methods cannot be intercepted by ordinary Spring AOP. AspectJ weaving has different invocation semantics.
58. How do REQUIRED and REQUIRES_NEW propagation differ, including their effects on database connections?
REQUIRED joins an existing transaction or starts one when none exists. Nested service calls typically share one physical database transaction and connection. An inner failure that marks it rollback-only can prevent the outer caller from committing even if that caller catches the exception.
REQUIRES_NEW suspends the outer transaction and starts an independent physical transaction. The inner commit or rollback is independent; with a typical JDBC transaction manager it needs another connection while the outer connection remains held. Under concurrency, an undersized pool can stall when every caller waits for that additional connection.
Use the independent boundary only when the business semantics require it, such as an audit record that must survive a failed outer operation. Do not use it to hide consistency problems: the inner transaction may not see uncommitted outer changes and can contend for outer locks. Calls still need to cross the proxy boundary.
59. How would optimistic locking help detect two clients updating the same record?
Add a JPA @Version property to the entity so updates compare the version originally read with the current database version. If two transactions read version 7, the first successful update advances it; the second stale update fails instead of silently overwriting the first.
Entity-field excerpt:
Java example
The failure may surface during flush or commit, often translated by Spring into an optimistic-locking exception. Return a defined conflict response and let the client refresh or resolve changes; do not blindly retry a user edit with stale assumptions.
For clients editing over separate requests, carry an expected version or an HTTP precondition and compare it when applying the command. Reloading the latest entity without checking the client's version can still accept a stale edit. Bulk update queries need explicit version-aware treatment because they bypass ordinary entity updates.
60. Why should production schema changes use controlled migrations instead of relying on Hibernate ddl-auto=update?
A migration tool makes schema changes explicit, ordered, reviewable, and reproducible. Hibernate's ddl-auto=update infers changes from mappings at startup; it is not a substitute for planning data backfills, destructive changes, lock duration, compatibility, or rollback across multiple application versions.
Use Flyway or Liquibase as the schema owner and avoid running competing initialization mechanisms. A common production arrangement is:
YAML example
This configuration assumes the chosen migration integration is installed and enabled, or migrations run through a controlled deployment step. Validation checks mapping compatibility but does not prove all operational aspects of a migration are safe. Test against a production-like database, estimate locking and runtime, protect backups, and plan forward recovery. For rolling releases, prefer additive changes before removing structures still used by older instances.
61. How do securityMatcher and authorization requestMatchers differ when defining multiple SecurityFilterChain beans?
securityMatcher selects whether a whole SecurityFilterChain applies to a request. When multiple chains exist, Spring Security uses the first matching chain in order; it does not merge authorization rules from every matching chain. Within that selected chain, authorization requestMatchers select the rule for a particular request.
For example, a higher-priority chain can match /api/**, with separate read and write authorization rules inside it. A lower-priority chain without a restrictive securityMatcher should provide intentional fallback coverage for the rest of the application. An anyRequest() rule only covers requests inside its own chain, not routes excluded by that chain's matcher.
Check that login, logout, and other filter-provided endpoints also fall within the appropriate chain. Test representative paths, unmatched paths, and HTTP methods. A request matching no security chain is not protected by Spring Security merely because another chain exists.
62. How would you combine request authorization with method-level authorization, and avoid confusing roles with authorities?
Use request authorization for coarse HTTP policy, such as requiring authentication for /orders/**, and method authorization for business permissions and resource ownership. Enable the latter with @EnableMethodSecurity; adding the security starter alone does not enable it.
A service-method excerpt can require an exact authority:
Java example
Here the application policy must also verify ownership or tenant access for the supplied order. By default, hasRole("ADMIN") checks ROLE_ADMIN, whereas hasAuthority("orders:approve") checks that exact string. JWT scopes commonly become SCOPE_... authorities unless conversion is customized. Keep naming consistent across identity mapping and tests. Method security uses interception, so self-invocation can bypass an annotated helper; place the enforceable operation on a managed service boundary and test it independently of HTTP routing.
63. What must a resource server validate before trusting a JWT, beyond merely decoding its payload?
A resource server must verify the JWT signature using trusted keys and permitted algorithms, validate the expected issuer, enforce time constraints such as expiration and not-before, and require an audience appropriate to this API. Decoding Base64 JSON establishes none of those facts.
Use Spring Security's resource-server support rather than a hand-written token parser. With Boot, configure the issuer and audience explicitly:
YAML example
These are illustrative public identifiers, not credentials. The corresponding issuer must actually publish trusted metadata and keys, and the security chain must enable JWT resource-server authentication. Successful authentication still requires authorization for the requested operation; map only intended claims to authorities. Test wrong issuer, wrong audience, expired or future tokens, invalid signatures, and insufficient scope. If supplying a custom decoder, confirm that it preserves all required validators and key-rotation behavior.
64. How would you decide whether a browser-facing API needs CSRF protection based on how credentials are sent?
Base the decision on whether a browser automatically attaches authentication credentials, not on whether the endpoint is called “REST” or the server is stateless. Session cookies, an authentication token stored in a cookie, and browser-managed Basic credentials can expose state-changing requests to CSRF. Keep CSRF protection for those flows and have the browser submit the required token.
A genuinely bearer-only API can have a different threat model when JavaScript explicitly adds an Authorization header and no ambient cookie or other automatic credential authenticates the request. Any CSRF exemption should be narrowly scoped to that verified surface, not applied indiscriminately to the whole application.
CORS and SameSite settings are useful but are not interchangeable with CSRF validation. Keep safe HTTP methods free of state-changing behavior, and test login, logout, refresh, and other browser credential flows as well as ordinary API writes.
65. Why can a browser preflight request fail before authentication, and how should CORS be integrated with Spring Security?
A CORS preflight is an OPTIONS request asking whether a later cross-origin request is permitted. It normally arrives without the user's authentication cookies, so an authentication-first policy can reject it before the browser is allowed to send the real request.
Integrate CORS with the relevant SecurityFilterChain, for example through http.cors(...), and provide an intentional CorsConfigurationSource or compatible MVC CORS configuration. Specify trusted origins, required methods, and required headers; enable credentialed requests only for a deliberate cookie-based flow. Do not combine credentialed access with an unrestricted origin policy.
Permitting every OPTIONS request alone does not create the required CORS response headers or validate origins. Test both allowed and rejected preflights, then the actual authenticated request. The actual endpoint still needs authorization, and enabling CORS does not remove its CSRF requirements.
66. How would you test successful access, forbidden access, unauthenticated access, and CSRF failures for a secured endpoint?
Use Boot 4's spring-boot-starter-security-test alongside the appropriate MVC test setup. Run requests through the intended security filters and vary authentication and CSRF independently, so one failure does not hide another. For a session-authenticated write endpoint with an API-style 401 entry point, cover this matrix:
Authentication | CSRF token | Expected result |
|---|---|---|
Required authority | Valid | Endpoint's success status |
Wrong authority | Valid | 403 |
None | Valid | 401 |
Required authority | Missing or invalid | 403 |
Form-login applications may redirect unauthenticated users instead of returning 401; assert the configured contract. MockMvc's csrf() supplies a valid token and csrf().useInvalidToken() exercises rejection. For forbidden requests, also verify that the mocked business service was not called. Test method authorization separately, and remember that jwt() or a mock user does not exercise real JWT signature validation. Add decoder or integration tests for that boundary.
67. How would you use @WebMvcTest and @MockitoBean to test a controller while keeping unrelated services out of the context?
Use @WebMvcTest with the target controller and supply its service dependencies using Framework's @MockitoBean. The slice loads MVC infrastructure rather than the full business and persistence graph. In Boot 4, use the current MVC test module, commonly through spring-boot-starter-webmvc-test, and the moved annotation import:
Java example
This scaffold assumes the application's controller, service, and security configuration exist. Stub service responses and assert status, headers, JSON, validation errors, and service calls. Provide any additional security dependencies the imported configuration needs and authenticate test requests appropriately. Do not disable filters simply to obtain green tests. A mocked service proves controller behavior, not repository correctness or transaction semantics.
68. How can Testcontainers and @ServiceConnection make a database integration test more representative than an in-memory substitute?
Testcontainers runs the actual database engine in a disposable container, exposing SQL dialect, constraint, transaction, and migration behavior that an in-memory substitute may not reproduce. @ServiceConnection lets Boot derive supported connection details from that container rather than requiring fixed ports or hand-built connection properties.
For Boot 4 with Testcontainers 2, this test-configuration excerpt uses the current PostgreSQL package:
Java example
Import this configuration into the integration test. Include Boot Testcontainers support, the PostgreSQL Testcontainers module, the JDBC driver, and a working container runtime. Match the image to the production database and pin it appropriately in CI. Run migrations and isolate test data; a real engine alone does not reproduce production scale, permissions, extensions, or network failures.
69. Why does a test annotated @Transactional not automatically roll back server-side work in a RANDOM_PORT test?
A test-managed transaction is associated with the test's thread. In a RANDOM_PORT test, the HTTP client sends a real request to an embedded server, whose handler executes on another thread. A service transaction started there belongs to that server-side execution and can commit independently of the test transaction.
Rolling back the test method therefore does not undo those committed rows. Test setup writes inside an uncommitted test transaction may also be invisible to the server, producing confusing failures before cleanup is even considered.
Use explicitly committed setup and reliable cleanup, isolated schemas or databases, or disposable fixtures with a clearly controlled lifecycle. Take parallel execution into account so one test does not delete another's data. For repository transaction tests, a test-managed rollback can still be useful; for real HTTP tests, verify externally observable state and do not assume a test annotation spans the network boundary.
70. How do @Cacheable, @CachePut, and @CacheEvict differ, and how would you choose a safe cache key?
@Cacheable can return a cached value without invoking the method. @CachePut always invokes the method and writes its result to the cache. @CacheEvict removes entries, normally after successful method execution unless configured otherwise. Enable caching with @EnableCaching and select a provider whose expiration and consistency behavior match the use case.
A safe key contains every input that changes the result, including tenant or authorization scope where relevant. For an authorized service receiving trusted tenant context, a composite key avoids ambiguous string concatenation:
Java example
This excerpt assumes parameter-name metadata and a configured cache manager. Never treat a caller-supplied tenant ID as proof of authorization. Plan update invalidation, transaction timing, and cross-replica behavior. Proxy self-invocation can bypass caching advice, and a cache hit does not independently re-run authorization inside the skipped method body.
71. What should you configure and test before moving service work to @Async?
Enable async interception, choose the intended executor, and call the annotated method through another managed bean. A same-object call normally bypasses @Async. Configure concurrency limits, queue capacity or admission control, rejection behavior, and shutdown policy so background work cannot consume unlimited memory or overwhelm the database.
Define how completion and failure reach the caller: a CompletableFuture can expose failures, while a void method needs appropriate uncaught-exception handling. Do not mistake submitting work for completing it.
Transactions do not automatically cross the new thread boundary. Start the required transaction in the worker, pass stable identifiers rather than managed entities, and propagate security and observation context only through suitable explicit mechanisms. Test executor saturation, worker failures, context handling, shutdown, and duplicate execution. An in-process async task is not a durable job; if work must survive a crash, use a persistent queue or job mechanism.
72. What do fixedRate, fixedDelay, and cron mean for @Scheduled work, and what happens when several application instances run it?
fixedRate schedules according to a target interval between starts, while fixedDelay waits for an invocation to finish before measuring the delay to the next one. A Spring cron expression selects calendar times and includes a seconds field; specify its time zone when business meaning depends on local time.
For a bean registered with @EnableScheduling active, this annotation runs at 02:15 UTC daily:
Java example
Execution overlap and lateness depend on the scheduler and invocation design; a fixed rate does not guarantee arbitrary parallel execution of one task. Each application instance normally schedules its own copy, so three replicas can run the job three times. Use idempotency plus an appropriate distributed coordination or durable scheduling mechanism when only one logical execution is allowed. Plan for failures, missed runs, and clock or daylight-saving effects.
73. When would you choose RestClient, WebClient, or an HTTP service interface for an outbound integration?
Choose RestClient for a synchronous, fluent HTTP client that fits a blocking service flow. Choose WebClient when non-blocking composition, reactive streaming, or a reactive application model provides a concrete benefit. Calling block() in an event-loop path defeats that benefit and can harm capacity.
An HTTP service interface declares the remote contract with annotations such as @HttpExchange; Spring creates a proxy backed by an appropriate client adapter. It reduces repetitive request construction but does not replace connection management, authentication, timeouts, error mapping, or resilience policy.
Prefer Boot's configured builders when relying on its customizations and instrumentation. In Framework 7, RestTemplate is deprecated in favor of RestClient, not removed. Select based on the application's execution model and integration requirements rather than rewriting working code merely because one API is newer. Test actual wire requests and failure behavior.
74. How would you set outbound timeouts and translate downstream HTTP failures without leaking an internal exception to clients?
Configure timeouts on the actual HTTP transport, including connection establishment and response waiting; pooled clients may also need a connection-acquisition timeout. Fit these limits within the caller's total deadline, including any retries.
For a synchronous JDK-backed client, a configuration-method excerpt is:
Java example
Here builder is an injected Boot-configured RestClient.Builder; the numbers are illustrative, not universal targets. Translate downstream statuses and transport failures into meaningful application exceptions, then a sanitized API error contract. A downstream 404 does not always mean this API's resource is missing. Do not expose response bodies or credentials. Test slow responses, connection failures, malformed bodies, and retryable versus non-retryable outcomes.
75. How would you expose only the Actuator endpoints required by operators while protecting sensitive details?
Separate three controls: whether an endpoint is available, whether it is exposed through HTTP or JMX, and who may call it. Keep a small operator-defined allowlist rather than exposing every endpoint.
For example, this HTTP exposure is deliberately limited:
YAML example
This is an exposure policy, not authentication. Protect management routes with explicit Spring Security rules and appropriate network access controls; restrict JMX separately if enabled. When defining custom security chains, verify management coverage because Boot's default security can back off. A separate management port is not itself a security boundary.
Avoid routinely exposing environment, heap-dump, or configuration details, and review even info content for unintended disclosure. Test unauthenticated and unauthorized access from outside the trusted network, plus the exact permissions operators and probe systems require.
76. How do liveness and readiness probes differ, and why should a database outage not necessarily fail liveness?
Liveness asks whether restarting this process is likely to repair its inability to operate. Readiness asks whether the instance should currently receive traffic. A process can be alive but not ready during initialization, draining, or a temporary inability to serve its workload.
A shared database outage normally should not fail liveness: restarting every application replica cannot repair the database and may amplify load through reconnect storms. Whether it should fail readiness is a deliberate availability decision. If every replica depends on the same unavailable database, removing all of them may produce different client behavior from keeping a controlled failure or degraded service available.
Use Boot's availability health groups, configure startup timing, and test transitions rather than checking only the happy path. Probe the main serving path where practical; a separate management server can respond while the application's HTTP server is saturated or broken.
77. How do metrics, logs, and traces complement each other when investigating a slow request?
Metrics show the scope and timing of a slowdown: request latency distribution, error rate, throughput, executor saturation, and connection-pool pressure. Logs describe discrete events and decisions, ideally with structured fields and a correlation identifier. Traces connect spans across components so one slow request can be attributed to database, downstream, queueing, or application work.
Start with aggregate signals to identify the affected endpoint and interval, inspect representative traces, and use correlated logs to explain the relevant failure or branch. Confirm whether instrumentation covers the dependency before interpreting an absent span as proof that no call happened.
Keep metric labels bounded, using route templates rather than raw URLs or user IDs. Configure sampling and retention intentionally, and redact sensitive values from every signal. Boot's Micrometer integrations help collect evidence, but custom clients and asynchronous execution still need verified instrumentation and context propagation.
78. How does graceful shutdown interact with request completion and the platform termination timeout?
Graceful shutdown stops admitting new work while allowing in-flight HTTP requests a bounded opportunity to complete. In the current Boot baseline it is enabled by default for supported embedded servers, but it still depends on the application receiving a proper shutdown signal and the platform allowing enough time.
An application grace period can be configured with:
YAML example
This is a per-phase timeout, not a promise that the whole process always terminates in exactly 25 seconds. The platform termination window must account for traffic-draining delays, relevant lifecycle phases, and a safety margin. A forced kill bypasses orderly completion.
Test a rolling shutdown with long requests and real load-balancer behavior, including persistent connections. Coordinate background executors separately; HTTP draining does not automatically guarantee completion of arbitrary async jobs. Clients should still tolerate interrupted requests and retry only operations with safe retry semantics.
79. What are the trade-offs between building a container image with a Dockerfile and using Spring Boot buildpacks?
A Dockerfile gives direct control over the base image, operating-system packages, user, filesystem layout, and build steps. That flexibility also makes the team responsible for secure defaults, patching, reproducibility, and efficient layering. A naive image that copies one large executable JAR can waste build-cache and distribution benefits.
Spring Boot's buildpack integration delegates image construction to a compatible builder and buildpacks, applying conventions for Java runtimes, layers, and launch behavior without maintaining a Dockerfile. It is convenient, but the selected builder, build environment, runtime choices, and update policy still need review.
Compare both approaches against required native dependencies, network restrictions, build cache, non-root execution, software inventory, image scanning, and operational debugging. Pin important build inputs and rebuild for security fixes. Test the resulting image's startup, memory limits, signals, and health behavior; a successful image build does not establish production readiness.
80. Which starter, import, testing, and JSON changes would you check before moving a Boot 3.5 application to Boot 4?
First reach the latest suitable Boot 3.5 maintenance release, remove deprecated usage, and establish contract tests. Then review Boot 4's dependency alignment and system requirements, including Framework 7, Security 7, and the Servlet 6.1 baseline; Boot 3 already used Jakarta namespaces.
Check four areas explicitly:
Starters: modularization introduces focused choices such as
spring-boot-starter-webmvcand technology-specific test starters. Do not assume an old umbrella dependency supplies every former integration.Imports: Boot packages moved; update against current API documentation rather than broad search-and-replace.
Tests: replace removed Boot
@MockBean/@SpyBeanwith Framework@MockitoBean/@MockitoSpyBean, checking their behavioral differences and moved slice annotations.JSON: Boot prefers Jackson 3, with many classes under
tools.jackson; Jackson annotations retaincom.fasterxml.jackson.annotation.
Test serialized contracts, custom modules, security behavior, validation, persistence, and deployment. Review unmanaged integrations for compatible versions, and remove temporary migration aids once changes are verified.
Spring Boot Interview Questions and Answers for Experienced
The experienced answers weigh reliability, maintainability, and operational cost alongside performance. They explain the evidence needed to locate a bottleneck, manage retries safely, and coordinate application changes with database, infrastructure, and dependency constraints.
81. How would you design and test a reusable auto-configuration module that activates only when its dependencies exist and backs off for user-defined beans?
Make the auto-configuration an optional, well-scoped integration rather than a second application configuration. Register its @AutoConfiguration class in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports; do not rely on component scanning. Use @ConditionalOnClass for optional dependencies, a namespaced @ConfigurationProperties type for settings, and @ConditionalOnMissingBean on defaults that applications may replace. Isolate optional-library types behind an appropriately conditioned configuration class so missing classes cannot break unrelated startup.
Test the module with ApplicationContextRunner. Cover a supported classpath, a missing dependency using FilteredClassLoader, disabled configuration, invalid properties, and an application-supplied replacement bean. Assert both the expected bean and the absence of competing defaults. Check ordering only where another auto-configuration genuinely supplies a prerequisite. Finally, build a small consuming application with the starter to verify packaged imports and dependency metadata; context-runner tests alone cannot prove the published artifact is assembled correctly.
82. How would you organize a growing Spring Boot codebase into business modules without making every module a separate service?
Organize around business capabilities such as orders, billing, and inventory, keeping each capability's controllers, services, and persistence internals together. Expose a small application API from each module and prevent callers from reaching directly into another module's repositories or entity graph. Package visibility, dependency rules, and architectural tests make these boundaries enforceable rather than merely conventional.
Keep synchronous calls where the business operation requires an immediate result or a shared local transaction. Use explicit events for independently handled consequences, documenting whether delivery is synchronous, asynchronous, or durable. An in-process event is not automatically a reliable message queue.
Give each module clear ownership of tables and migration changes, even when all modules share one database. Split build modules when dependency enforcement or build isolation warrants it. Extract a separate service only when independent scaling, deployment, or ownership justifies network failures and distributed consistency costs.
83. How would you upgrade the Boot BOM and related Spring Cloud dependencies without accidentally mixing incompatible framework versions?
Treat the Boot BOM as a tested dependency set, not a menu of unrelated version numbers. Select the target Boot release, then check the Spring Cloud compatibility matrix for a supported release train before changing either BOM. Avoid separately overriding Framework, Security, or Spring Data merely to match the latest individual release.
For a Boot 3-to-4 migration, first stabilize on the latest suitable 3.5 release and address deprecations. Review Boot 4's starter/module changes, Jakarta baseline, Jackson 3 migration, and testing changes explicitly. An apparently clean compilation does not establish runtime compatibility.
Compare resolved dependency trees before and after the change, including runtime and test configurations, and inspect exclusions and direct version pins. Run contract, database, authentication, and packaged-startup tests against the intended JDK. Release through a canary with a reproducible artifact and configuration manifest; retain the known-good dependency set for rollback.
84. Startup time has doubled after a release. How would you investigate bean initialization and decide whether lazy initialization or AOT actually helps?
Compare the slow and previous builds under equivalent CPU limits, classpath, configuration, and dependency availability. Separate process launch, Spring context creation, migrations, remote initialization, application runners, and readiness time. Enable BufferingApplicationStartup for Spring startup steps and use Java Flight Recorder when class loading, allocation, or CPU contention needs correlation. Keep any diagnostic Actuator endpoint private.
Look for an unexpectedly eager bean, repeated scanning, an initialization-time network call, or a migration that dominates elapsed time. Fix the specific cause before changing the initialization model.
Lazy initialization can move bean creation into the first request; it may improve the startup number while worsening first-use latency and delaying configuration failures. Spring AOT can reduce runtime setup, but cannot remove time spent waiting for a remote service or database. Compare cold start, first-request latency, steady-state performance, and failure visibility before choosing either optimization.
85. When is a native image a good deployment choice, and which reflection, resource, build-time, and runtime constraints would you validate first?
Choose a native image when cold starts, frequent scale-to-zero transitions, or memory density materially affect the deployment. Do not assume it will improve peak throughput or total engineering cost. Benchmark the representative workload against a tuned JVM deployment, including startup, resident memory, latency, build duration, and operational diagnostics.
Validate reflection, serialization, dynamic proxies, classpath resources, JNI, and third-party library support. Exercise rarely used error handlers and serializers: static reachability can miss behavior that compilation alone does not reveal. Supply targeted runtime hints where required rather than registering everything indiscriminately.
Spring AOT fixes the bean arrangement at build time, so runtime properties cannot freely switch conditional beans or profiles as in a regular JVM application. Ordinary runtime values still need secure injection. For the Boot 4.1.2 baseline, verify the documented GraalVM 25-or-later toolchain and target platform. Test the actual native executable, not only JVM-based unit tests.
86. How would you evaluate virtual threads for a blocking Spring MVC workload without overwhelming database or downstream connection limits?
Virtual threads can reduce the cost of waiting in a blocking MVC workload; they do not create database capacity or make CPU-bound work faster. Compare the same application with and without them under a representative mix of slow queries and outbound calls. Boot requires Java 21 or later for this feature, with newer supported JDKs offering relevant implementation improvements.
YAML example
Keep database and HTTP connection pools bounded. Add explicit admission limits, queue deadlines, and rejection behavior around scarce downstream resources instead of relying on a small request-thread pool to provide accidental backpressure. Account for the sum across replicas.
Measure acquisition waits, timeouts, heap use, p99 latency, and completed work, not thread counts alone. Inspect JFR for contention or pinning appropriate to the chosen JDK. Virtual-thread executor settings and daemon-thread lifecycle also require review.
87. How would you choose between Spring MVC and WebFlux for a service that depends on blocking database access?
For a service dominated by blocking JDBC or JPA work, Spring MVC is usually the simpler starting point. Its execution model matches blocking operations directly, and virtual threads can be evaluated separately when waiting-thread overhead matters. This is a workload decision, not a claim that one framework is universally faster.
Choose WebFlux when streaming, nonblocking composition, or large numbers of concurrent I/O operations provide a concrete benefit and the important dependencies support that model. Calling JDBC from a reactive handler still blocks; wrapping the result in Mono does not make the database driver nonblocking. If a blocking integration must remain, offload it to a deliberately bounded scheduler or configured blocking executor and measure saturation.
MVC can use WebClient without converting the whole server to WebFlux. Compare end-to-end throughput, cancellation behavior, debugging complexity, and downstream limits before accepting the operational cost of mixed execution models.
88. An API's p99 latency rises while average latency stays acceptable. How would you investigate with request metrics, traces, and resource saturation signals?
Start by identifying which route templates, status classes, instances, and time windows contribute to the tail. Use a histogram suitable for the latency objective; averaging instance-level p99 values does not produce a meaningful fleet p99. Compare client-observed latency with server timing because proxy queues and connection acquisition may lie outside the measured handler interval.
Inspect representative slow traces for database waits, downstream fan-out, retries, cache misses, and serialization. Correlate them with CPU throttling, GC pauses, executor queues, database-pool waits, and connection limits. A small fraction of requests hitting a slow dependency can leave the average almost unchanged.
Check deployment timing and traffic shape before attributing the regression to code. Avoid user IDs or raw URLs as metric tags. Reproduce the suspected bottleneck under controlled load, change one constraint, and verify tail latency and error rate together so faster failures are not mistaken for improvement.
89. How would you diagnose connection-pool exhaustion and distinguish a leak, long transaction, slow query, and excessive concurrency?
Compare active, idle, pending, and maximum pool connections with acquisition latency and timeout counts. Then inspect database sessions, transaction age, query duration, lock waits, and application thread stacks for the same interval. Pool saturation alone does not identify the cause.
A leak leaves borrowed connections unavailable after useful work finishes; review manual JDBC cleanup and treat leak-detection warnings as leads, since legitimate long operations can also trigger them. A long transaction may hold a connection while waiting on an HTTP call or processing a large batch. Slow SQL shows sustained execution or locking in the database. Excessive concurrency produces demand beyond capacity even when individual operations are healthy.
Shorten transaction scopes, close resources reliably, optimize the identified queries, or bound admission according to the evidence. Increasing pool size can worsen database contention. Budget connections across every replica and reserve capacity for migrations, operations, and other clients.
90. How would you design retries so a transient failure does not multiply a non-idempotent business operation or reuse a failed transaction?
Retry only failures that are plausibly transient and only operations whose effects can be repeated safely. A timeout is an uncertain outcome, not proof that the first attempt did nothing. Protect commands with a durable idempotency key, and avoid retrying validation failures, authorization failures, or arbitrary business exceptions.
Place the retry boundary outside a complete transaction so each failed attempt rolls back before the next begins. Separate beans or an explicit transaction template make that boundary clear; an existing outer REQUIRED transaction can otherwise defeat the intended fresh transaction. Framework 7 uses org.springframework.resilience.annotation.Retryable with @EnableResilientMethods; maxRetries=2 permits three total attempts. These are not the older Spring Retry APIs.
Use bounded attempts, backoff with jitter, and an overall deadline. Test a failure before commit, an uncertain response after commit, and exhausted retries. Verify database state and external side effects, not merely invocation counts.
91. How do timeouts, retries, circuit breakers, and bulkheads address different failure modes, and how would you order and test them?
Timeouts bound waiting; retries repeat selected failed attempts; circuit breakers stop calls to a dependency judged unhealthy; bulkheads cap the resources one dependency can consume. None makes a non-idempotent operation safe to repeat.
Define an overall request deadline first. One reasonable arrangement is a bounded retry policy whose individual attempts pass through a circuit breaker, a concurrency bulkhead, and a transport operation with acquisition, connection, and response timeouts. This makes the breaker observe attempts rather than only the final logical result. Other ordering can be valid, but its accounting and resource ownership must be explicit. Do not retry breaker-open or bulkhead-rejection exceptions indiscriminately.
Keep delays outside scarce permits where practical. Test slow responses, connection failures, saturation, recovery, and cancellation. A timeout wrapper may stop waiting without stopping the underlying operation. Measure actual downstream concurrency and side effects to verify that the composed policy really protects the dependency.
92. A client retries a payment-creation request after a timeout. How would you make the API's database-side effects idempotent under concurrent duplicates?
Require a client-supplied idempotency key scoped to the authenticated tenant and operation. Store a canonical request fingerprint and the committed response or business result alongside that key. Make all three key columns NOT NULL and enforce uniqueness in the database, not with a check-then-insert application sequence.
SQL example
Within one local transaction, claim the key, create the payment record, and store the result. A concurrent duplicate must wait, return a defined in-progress response, or read the committed result; it must not execute the business mutation again. Reject reuse with a different fingerprint. With PostgreSQL, a deliberately designed ON CONFLICT path avoids treating a uniqueness exception as recoverable inside an already-failed transaction.
Define retention and replay authorization. External charging needs its own provider idempotency key and reconciliation workflow: a local database transaction cannot atomically roll back an HTTP payment request.
93. How would you prevent a database commit and a message publication from diverging, and why is an after-commit listener not itself a durable outbox?
Write the business change and an outbox record in the same database transaction. The outbox contains a stable event ID, aggregate identity, schema version, and the minimum payload needed by consumers. A relay or change-data-capture process publishes committed records and records progress durably.
Publication and marking a record delivered can still fail between steps. Therefore, assume at-least-once delivery and make consumers deduplicate or apply idempotent state transitions. Define ordering where required, retry limits, poison-message handling, retention, and monitoring of the oldest unpublished event.
An AFTER_COMMIT listener executes only after a successful commit, but its pending work is not inherently durable. A process crash between commit and listener execution can lose the message; a listener failure cannot undo the committed business change. It can wake an outbox worker, but should not replace the durable record. Test crashes at each boundary rather than claiming end-to-end exactly-once delivery.
94. What happens to transaction and security context when work crosses an asynchronous thread boundary, and how would you make the intended behavior explicit?
A conventional imperative Spring transaction is associated with the executing thread; submitting work to an executor does not transfer that transaction. Start a new transaction in the worker through an explicitly proxied service or transaction template. Pass immutable identifiers or DTOs, not managed entities that depend on the caller's persistence context. If the worker requires committed data, schedule through a commit-aware durable mechanism rather than racing the caller's commit.
Spring Security's usual thread-local context also needs deliberate handling. A DelegatingSecurityContextAsyncTaskExecutor can propagate a caller context for suitable short-lived work and clear it afterward. Durable jobs should record an authorized actor or service identity and re-evaluate relevant permissions when executed instead of preserving a stale request token indefinitely.
Trace and logging context are separate concerns. Configure their propagation independently, test reused worker threads for context leakage, and define how asynchronous failures reach operational monitoring.
95. How would you choose transaction isolation or locking for a reservation workflow whose invariant spans several rows?
State the invariant first: for example, confirmed reservations for a flight must never exceed its capacity. Locking only the reservation rows already returned by a query may not protect against another transaction inserting a new row. Likewise, optimistic versions on separate reservations do not automatically protect a shared capacity invariant.
A practical design locks a stable flight-inventory row, checks remaining capacity, and records the reservation in the same short transaction. All writers must follow that protocol. Alternatively, maintain an atomic counter with a conditional update and check the affected-row count. Here :flight_id is a bound NamedParameterJdbcTemplate parameter, not raw psql syntax.
SQL example
Serializable isolation is another option, but database semantics and whole-transaction retries matter. Keep remote calls outside the lock window, order multiple locks consistently, and test concurrent requests against the production database engine, including deadlocks and aborted transactions.
96. How would you roll out an incompatible database change while old and new application instances run at the same time?
Use an expand-and-contract sequence rather than renaming or dropping a field while old instances still depend on it. First add a compatible column or table and deploy code that tolerates both representations. Backfill existing data in bounded, restartable batches while accounting for concurrent writes; a one-time copy without a consistency strategy can immediately become stale.
For a required field replacement, choose a clear source of truth during the transition and maintain the other representation transactionally where possible. Compare both representations, then switch reads after coverage and correctness checks. Keep the old representation through the rollback window and until no old application, batch job, or consumer relies on it.
Apply versioned Flyway or Liquibase migrations with deliberate ownership and locking expectations. Large indexes or constraints require engine-specific rollout planning. Remove obsolete schema only in a later release, after compatibility evidence—not merely after the new pods appear healthy.
97. How would you prevent mass assignment and accidental data disclosure when accepting updates to a rich persistence model?
Use purpose-specific request DTOs rather than binding client JSON directly onto a persistence entity. A profile-edit request should expose editable fields, not tenantId, ownerId, administrative roles, or billing status. Validate syntax and size at the boundary, then apply business authorization and state-transition rules in the service.
Java example
Load the target through an authorized, tenant-scoped query and copy only permitted fields. Do not use a generic property copier to merge arbitrary input. For partial updates, distinguish omitted values from explicit nulls and consider optimistic version checks to prevent lost updates.
Return a separate response DTO or projection with an explicit disclosure policy. Excluding a password field alone is not sufficient if nested relationships expose personal or internal data. Test prohibited input fields and forbidden output fields as part of the API contract.
98. How would you enforce tenant isolation consistently across repositories, authorization checks, and caches?
Establish tenant identity from a verified principal and validated tenant membership, not from an untrusted header alone. Carry that identity explicitly through service and repository boundaries. Every read, update, delete, and bulk operation must constrain the tenant; a globally unique object ID is not authorization.
Use repository operations shaped like findByTenantIdAndId, and test native queries and administrative paths that may bypass normal filters. Database constraints should prevent cross-tenant relationships; row-level security can add defense in depth when configured and tested correctly.
Cache keys must include tenant identity and any additional user or permission scope that changes the response. Authorize every access before returning cached data; a cache hit must not bypass an authorization check inside the skipped method body. Ensure asynchronous jobs carry trusted tenant context and clear it afterward. Run negative tests using identical resource identifiers and cache-warming sequences across two tenants.
99. How would you secure an application that serves both session-authenticated browser pages and bearer-token APIs without leaving unmatched routes unprotected?
Use ordered SecurityFilterChain beans with explicit responsibility. A higher-priority chain can match /api/**, validate bearer tokens as a resource server, and avoid session-based authentication. A final chain without a restrictive securityMatcher must cover every remaining request, applying browser login rules and denying routes not intentionally exposed. Authorization rules inside one chain do not protect requests that never match that chain.
Keep CSRF protection for browser flows using session cookies or other automatically attached credentials. Exempting a bearer-only API requires verifying that it cannot authenticate through cookies or another ambient credential; STATELESS by itself is not a CSRF argument. Configure CORS separately with an explicit origin policy.
Test anonymous requests, expired tokens, insufficient scopes, browser form submissions, missing CSRF tokens, and unknown paths. Also verify login, callback, error, and management routes because chain selection can accidentally leave them uncovered or unreachable.
100. How do OAuth2 login, an OAuth2 resource server, and an authorization server differ, and which responsibilities belong in a typical business API?
OAuth2 login makes an application an OAuth2 client: it redirects a person to an identity provider and processes the authorization response, commonly establishing a browser session. OpenID Connect adds the identity layer typically used for user login. The resulting session is not the same as validating an API bearer token.
A resource server accepts access tokens intended for its protected API. It verifies the token according to the chosen JWT or opaque-token arrangement and enforces scopes, roles, tenant membership, and object-level permissions. Authentication does not replace business authorization.
An authorization server issues tokens, manages client registrations and grants, and controls signing keys and token lifecycle. A typical business API should be a resource server and delegate issuance to a dedicated identity platform rather than inventing its own token protocol. It may also be an OAuth2 client when calling another protected service, but those responsibilities need distinct configuration and credentials.
101. How would you plan for JWT signing-key rotation, issuer outages, and authorization changes while avoiding acceptance of untrusted tokens?
Trust a configured issuer and key source, not URLs supplied in an untrusted token. Validate signature, allowed algorithms, issuer, audience, expiry, and not-before time. Plan overlapping signing keys: publish the new key before issuance changes and retain the old verification key for the permitted token lifetime and clock skew.
Spring Security 7.1.2's default issuer-based setup defers discovery until the first JWT-bearing request, so application startup can succeed while that first authentication fails during an issuer outage. Test the actual decoder, cache behavior, refresh timeouts, unknown key IDs, and cold-start behavior. Cached trusted keys may permit validation during an outage; inability to validate must never become permission to accept the token.
Self-contained tokens can retain outdated permissions until expiry. Use suitably short lifetimes and, where required, explicit revocation or current authorization checks for sensitive operations. Key rotation alone does not implement immediate user revocation.
102. How would you rotate database credentials or other secrets without assuming that changing a property source automatically reconfigures every bean?
Treat secret rotation as a resource lifecycle change, not merely a new configuration value. Identify how each consumer reads credentials: once during construction, on each new connection, or through a provider that supports refresh. Updating an external property source does not guarantee that an existing DataSource, HTTP client, or singleton has rebound itself.
A predictable approach is overlapping credentials followed by a rolling restart: provision the replacement with equivalent least privileges, deploy it through the approved secret mechanism, verify new connections, drain old instances, then revoke the previous credential. Keep the overlap short and auditable. If live rotation is required, use the specific pool or provider's supported mechanism and test connection replacement rather than assuming it.
Validate failure handling, expiry alarms, rollback permissions, and long-lived connections. Avoid logging the secret, placing it in command-line arguments, or exposing it through diagnostics. Monitor authentication failures without recording credential values.
103. An internal management endpoint has become publicly reachable. How would you contain exposure and verify the resulting Actuator security policy?
Contain the exposure at the ingress or network boundary immediately, then reduce the exposed endpoint set. Preserve access evidence and determine which endpoint, methods, response fields, and time window were reachable. A publicly accessible heap dump or configuration endpoint may justify credential rotation and wider incident handling; merely closing the route does not undo disclosure.
Separate endpoint availability, HTTP exposure, and authentication/authorization. A management port is not a security boundary unless routing and network policy enforce it. When application-defined security chains replace Boot defaults, explicitly secure Actuator and all unmatched application routes.
Verify from both an external client and the authorized monitoring path. Test anonymous, insufficiently privileged, and authorized requests, including alternate base paths and management ports. Keep health details minimal for public checks. Add automated policy tests and deployment checks so a future wildcard exposure setting or ingress rule cannot silently restore the problem.
104. Why can tagging a metric with user IDs or raw request paths cause operational problems, and how would you preserve useful diagnostics?
Each distinct combination of metric tags creates another time series. User IDs, order IDs, query strings, and raw paths such as /orders/123 can therefore cause unbounded cardinality, increasing application memory, ingestion cost, and query latency. They may also disclose personal information.
Use bounded dimensions such as route template /orders/{id}, HTTP method, status class, dependency name, and a controlled error category. Review the product of tag cardinalities, not just each tag independently. Limit or reject unexpected tag values with registry filters where appropriate, while fixing the instrumentation that produced them.
Put request-level correlation in access-controlled, sampled traces or structured logs rather than metric labels. High-cardinality trace attributes still need retention and privacy controls; they are not a safe place for secrets. Preserve useful aggregate measurements and connect a slow metric bucket to representative traces through exemplars when the telemetry stack supports them.
105. How would you keep trace context across outbound HTTP calls and asynchronous work, and verify that custom client construction has not bypassed instrumentation?
Build outbound clients from Boot's injected RestClient.Builder or WebClient.Builder so observation customizers are retained. Creating a client directly can bypass the configured observation registry and propagation setup. Also verify that the chosen tracing bridge and exporter are present; adding a trace ID to a log line alone does not establish distributed tracing.
This configuration must be included in component scanning.
Java example
For Boot 4.1's auto-configured asynchronous executor, opt into observation context propagation with spring.task.execution.propagate-context=true. For custom executors, apply the appropriate context-propagating task decorator explicitly. Reactor context and security context require their own deliberate configuration.
Use an integration test with a stub downstream to inspect propagation headers and parent-child relationships. Cover asynchronous success, failure, and thread reuse. Ensure custom interceptors do not overwrite headers or leak baggage containing sensitive data; sampling may omit export without justifying broken context propagation.
106. How would you separate security audit records from diagnostic logs while keeping sensitive values out of both?
Security audit records answer who attempted which protected action, against what resource, when, and with what outcome. Diagnostic logs explain implementation behavior and failures. Give them separate schemas, retention policies, access controls, and operational ownership, even if they share transport infrastructure.
An audit event might contain an internal actor identifier, tenant, action, target identifier, decision, timestamp, and correlation ID. Never record passwords, bearer tokens, session cookies, or unrestricted request bodies. Apply allowlists to structured fields and sanitize attacker-controlled strings to prevent log injection. Resource identifiers themselves may require privacy controls.
For business changes that must have an audit trail, persist the successful-change audit record atomically with the change or use a durable outbox. Rejected attempts need an independent path because the business transaction may roll back. Protect audit integrity and alert on delivery failures. Actuator's audit-event endpoint is an access surface, not a substitute for a durable audit system.
107. How would you handle cache invalidation, tenant-aware keys, and a sudden cache miss surge without returning another user's data?
Define what makes a response interchangeable before designing the key. Include tenant and resource identity, plus user or permission scope when output differs by caller. Perform authorization outside the cache-skipped method body so a hit cannot return data before current access checks run. Cache immutable response data rather than shared mutable persistence entities.
Invalidate or update entries after a successful database commit. For cross-instance invalidation, use reliable messaging or bounded staleness, and account for races where an older in-flight read repopulates the cache after eviction. Versioned keys or version checks can address stronger consistency requirements; TTL alone cannot guarantee immediate correctness.
For miss surges, combine bounded load concurrency, randomized expiry, and request coalescing supported by the provider. @Cacheable(sync = true) is not a universal cross-replica lock. Test cold starts, cache outages, authorization changes, and two tenants requesting identical IDs. Never serve stale sensitive data merely to preserve availability.
108. A scheduled export must survive restarts and run only once per logical job across replicas. What guarantees are missing from @Scheduled and @Async alone?
@Scheduled triggers work in each application instance, and @Async submits it to an executor; neither provides durable job state, cluster-wide ownership, or crash recovery. A restarted process can forget pending work, while multiple replicas can execute the same schedule.
Persist a logical job identifier such as (exportType, tenant, reportingPeriod) under a unique constraint. Workers claim work atomically and track progress, attempts, and terminal status. If ownership uses a lease, include expiry, renewal, and fencing so an old worker cannot publish after a replacement takes over. A clustered scheduler or durable queue can supply parts of this design.
Aim for one committed business outcome, not an unsupported promise that code executes once. Make chunks and output publication idempotent, use stable destination keys, and reconcile uncertain completion. Test worker crashes before and after publishing, expired leases, retries, and restarts, and expose stalled-job alerts and a controlled replay path.
109. What testing strategy would give confidence in controller contracts, database behavior, authorization, and downstream failures without loading the full application for every test?
Use ordinary unit tests for business rules and failure decisions without a Spring context. Add MVC slice tests for binding, validation, status codes, JSON shape, and the actual security configuration. Exercise anonymous, permitted, and forbidden users; session-authenticated mutations also need missing and valid CSRF-token cases.
Use persistence-focused tests against a containerized instance of the production database engine for migrations, constraints, locking, and query behavior. An in-memory substitute can hide SQL-dialect and isolation differences. Test HTTP client integrations against a controllable stub that returns errors, delays, and malformed responses.
Reserve @SpringBootTest and real-server tests for critical wiring and end-to-end journeys. In Boot 4, use the appropriate modular test starters and current slice imports, with Framework's @MockitoBean where a bean replacement is needed. Verify durable state after retries and concurrency scenarios. Coverage percentages cannot establish that authorization or transaction boundaries are correct.
110. How would you diagnose a slow or flaky Spring test suite caused by context-cache misses, shared state, or external-service timing?
Measure test duration by context startup, fixture preparation, execution, and teardown before adding parallelism. Enable TestContext cache diagnostics to identify avoidable cache misses. Different profiles, property sets, bean overrides, dynamic-property customizers, and configuration classes can create distinct contexts; excessive @DirtiesContext or separate test JVMs can eliminate reuse.
Standardize compatible test configurations without hiding genuine isolation requirements. Reset database rows, caches, clocks, and static state deliberately. Transactional test rollback does not clean up server-side commits made by a random-port HTTP test, because the client and server run in different transactions.
Replace fixed sleeps with bounded condition-based waits and controllable downstream stubs. Align container lifecycle with cached-context lifecycle so a reused context does not point at a stopped database. Reproduce failures individually and in randomized order, then introduce parallel execution only where resources and data namespaces are isolated. Do not mask nondeterminism with unrestricted retries.
111. How would you verify a Boot 4 Jackson migration preserves public JSON contracts instead of assuming that successful compilation proves compatibility?
Capture representative public JSON requests and responses before migration, including dates, time zones, decimals, enums, nulls, unknown properties, polymorphic payloads, and validation errors. Compare contracts semantically where field order is irrelevant, and byte-for-byte only when signatures or another protocol require it. Test serialization and deserialization independently.
Boot 4 prefers Jackson 3. Most Jackson packages move to tools.jackson, while Jackson annotations retain com.fasterxml.jackson.annotation. Review custom modules, serializers, mix-ins, mapper customization, and the format-specific mapper actually used by MVC. A separately created mapper can make a test pass while production uses different defaults.
Use focused JSON tests plus endpoint-level tests with the application configuration. Check third-party libraries that still expect Jackson 2 and avoid accidentally registering incompatible modules. Compatibility settings can ease migration but do not prove identical behavior. Release only after consumer-relevant differences are accepted or corrected, not merely after import changes compile.
112. How would you configure a Spring Boot application behind a reverse proxy without trusting attacker-supplied forwarding headers?
Define the trusted proxy boundary before enabling forwarded-header processing. The edge proxy must remove client-supplied Forwarded and X-Forwarded-* headers and write authoritative values. Restrict direct access to the application so an attacker cannot bypass that sanitation. Otherwise, spoofed scheme, host, or client address can affect redirects, URL generation, auditing, and security decisions.
Choose Boot's server.forward-headers-strategy for the actual container and topology: NATIVE uses container support, while FRAMEWORK uses framework processing. Neither is permission to trust arbitrary clients. Configure trusted proxy ranges or equivalent enforcement where supported and avoid overlapping mechanisms that interpret the headers twice.
Test HTTPS termination, redirect targets, context paths, multiple proxy hops, and direct spoofed-header requests. Keep allowed-host and redirect validation explicit, and do not treat a forwarded client IP as identity. Validate cookie security and generated external URLs through the real proxy path.
113. How would you coordinate readiness removal, in-flight HTTP requests, background executors, and database work during a rolling shutdown?
Begin draining before termination: remove the instance from readiness-based routing and allow for load-balancer propagation. Stop accepting new background jobs as well as HTTP work. Boot 4.1.2 enables graceful web shutdown by default, but its lifecycle timeout is per shutdown phase, not a universal deadline covering every external component.
YAML example
Set the platform termination grace period to cover routing delay and all required shutdown phases. Configure executors and lifecycle ordering so accepted tasks finish or checkpoint before dependencies such as the database pool close. Bound individual requests and transactions; an indefinitely blocked downstream call cannot be made safe by a grace period alone.
Durable jobs need recoverable ownership and idempotent resume behavior when forced termination occurs. Exercise real termination signals under load, including long requests and active jobs, then verify committed data, duplicate effects, and the next replica's recovery.
114. How would you design dependency health checks so a shared downstream outage does not trigger restart loops or remove all replicas unnecessarily?
Liveness should indicate that restarting this process can repair its internal failure. Do not include a shared database or external API in liveness: restarting every healthy application instance cannot fix that dependency and may amplify the outage.
Readiness asks whether this instance should receive traffic. Include a dependency only when its failure genuinely makes the instance unable to serve the relevant workload and removal is preferable to controlled failures. A shared dependency check can make all replicas unready simultaneously, so consider partial service, circuit breakers, and explicit degraded responses rather than removing useful capacity automatically.
Use short timeouts, inexpensive checks, and thresholds that tolerate brief disturbances. Keep detailed dependency health available to operators without turning every diagnostic indicator into a routing condition. Test the probes on the application's serving path, not solely a separate management server. Simulate a shared outage, recovery, startup delay, and shutdown to verify the platform's actual behavior.
115. How would you make an application rollback safe when a release changes code, configuration, dependencies, and database schema together?
Make rollback a compatibility property designed before deployment. Record the exact application artifact, dependency set, configuration version, feature flags, and schema migration state. Use expand-and-contract database changes so the previous application can still read and write the current schema during the rollback window.
Separate deployment from activating incompatible behavior. Introduce a dormant capability, validate it with limited traffic, and enable it only after compatible readers and consumers are in place. Flags need known defaults and ownership; they cannot reverse data already transformed into an old-code-incompatible shape.
Rehearse rollback using production-like data and both application versions concurrently. Check queued messages, background jobs, serialized cache entries, and external side effects, not just HTTP startup. Database down-migrations can destroy newly written data, so a forward fix or compensating migration may be safer. Define objective rollback triggers, preserve observability across versions, and delay destructive cleanup until the compatibility window closes.
116. How would you investigate a production-only 500 error using correlation IDs and targeted diagnostics without exposing customer payloads or enabling unrestricted debug access?
Return a stable error response with a correlation identifier, not a stack trace or customer payload. Generate or validate correlation values at the trust boundary to prevent unbounded or injected log fields. Use that identifier to connect the request's route template, application version, instance, exception category, and relevant trace spans.
Compare the failing cohort with successful requests using non-sensitive dimensions: tenant configuration category, feature state, dependency version, or resource size bucket. Inspect sanitized exception details and downstream status without logging authorization headers, session cookies, SQL parameters containing personal data, or complete bodies.
Enable narrowly scoped diagnostics for a limited duration through an authenticated operational path, with an owner and automatic reversion. Reproduce with synthetic or appropriately sanitized inputs in a representative environment. If a dump is necessary, treat it as sensitive evidence with restricted access and retention. Verify the fix with a regression test that asserts the error contract and privacy boundaries.
117. How would you load-test a Spring Boot service to verify concurrency limits, error budgets, and correctness rather than reporting throughput alone?
Define the workload and acceptance criteria before running the test: request mix, data distribution, cache state, arrival rate, concurrency, latency objectives, and allowed error-budget consumption. Include realistic downstream limits and production-like CPU and memory constraints. A closed-loop client can hide queueing by slowing its own request generation when the service degrades, so choose the load model deliberately.
Measure achieved and offered throughput, latency distributions, errors, rejected work, pool waits, CPU throttling, GC, and queue growth. Include spikes, sustained load, dependency slowdown, and recovery rather than a short happy-path peak.
Assert business correctness under load: no oversold inventory, duplicate payments, cross-tenant responses, or lost updates. Distinguish successful operations from fast failures. Verify bounded concurrency and deadlines actually protect the database and downstream services. Report the test environment, warm-up, bottleneck, and saturation point; do not present an isolated requests-per-second number as a production capacity guarantee.
118. How would you ensure business authorization still applies when the same operation is invoked by an HTTP controller, a scheduled task, and another bean?
Place authorization at the business-service boundary rather than relying solely on controller URL rules. Enable method security in a scanned configuration and use permission checks that include the action, tenant, and target resource. Authentication establishes the actor; the service must still decide whether that actor may perform this operation in the current business state.
Java example
The annotation is illustrative, not a complete object-authorization policy. With proxy-based method security, self-invocation and manually constructed objects can bypass interception. Route calls through a managed service proxy or move the protected operation into a separate bean.
A scheduled task has no browser principal by default. Give it an explicit least-privilege service identity or a separately authorized job policy, rather than bypassing checks. Test invocation through HTTP, another bean, and the actual scheduled execution path.
119. A vulnerability affects a transitive dependency managed by Spring Boot. How would you select, verify, and roll out a fix without assuming an arbitrary version override is compatible?
Confirm the affected artifact, resolved version, vulnerable functionality, and exposure using the vendor advisory and the deployed dependency graph. A scanner finding is a starting point; unreachable functionality may change urgency, but it does not justify ignoring an applicable patch. Record any temporary mitigation and its limitations.
Prefer a supported Boot maintenance release that manages the fixed dependency as part of a compatible set. If an urgent override is necessary, check the dependency's compatibility requirements and the Boot team's guidance, pin the exception explicitly, and assign its removal to a tracked upgrade. Do not override related Framework modules independently without assessing the whole set.
Verify the resolved runtime artifact, not just the build declaration, and run targeted regression, authentication, serialization, and packaged-startup tests. Produce an updated dependency inventory, deploy through a canary, and rescan the built image. Track evidence that the vulnerable artifact is absent or the verified mitigation is active.
120. How would you explain an UnexpectedRollbackException after an inner transactional operation failed and its exception was caught, and redesign the business flow?
With PROPAGATION_REQUIRED, an inner transactional method normally joins the outer physical transaction. If an exception crosses the inner transactional interceptor and triggers rollback rules, that shared transaction can become rollback-only. Catching the exception in the outer method does not erase the marker. When the outer method attempts to commit, Spring raises UnexpectedRollbackException rather than falsely reporting success.
For an all-or-nothing operation, let the failure propagate and handle it outside the transaction. If a failure should be an expected business result, design that path before performing work that leaves the transaction unusable; do not try to rescue an aborted persistence context.
For genuinely independent work, such as recording a failure audit, a separate proxied REQUIRES_NEW service can use another transaction. It must not be used to disguise partial business commits, and it needs additional connection capacity. Savepoint-based NESTED behavior is transaction-manager and database dependent, not a universal JPA solution.
Spring Boot Documentation and Further Reading
Examples target Spring Boot 4.1.2 with Spring Framework 7 and Java 17 or later unless an answer states another requirement. Features such as virtual threads require a newer Java version. Use compatible Boot-managed dependencies and distinguish servlet from reactive behavior. Examples may be method or configuration excerpts and require the stated classes, beans, dependencies, and database objects. Source review does not establish compilation or runtime behavior; validate examples in the intended development environment.
Use these curated references to verify Spring Boot configuration, framework behavior, public APIs, security, data access, and testing assumptions. Select documentation that matches the application's release line and dependencies, especially when adapting transaction, concurrency, or deployment examples.
Similar Posts
