Skip to content

Learn. Practice. Feel prepared.

Spring Boot Interview Questions and Answers with Instant Scoring

Strengthen your Spring Boot interview preparation with real-world scenarios, architecture challenges, and debugging questions. Practice at your own pace, understand important concepts, and measure your progress with instant scoring.

Top Spring Boot Interview Questions for Freshers and Experienced

50 Questions Easy · Medium · Hard

Try answering from memory, then check the reference answer and rate yourself. Your notes are optional and are not automatically graded.

Filter:

1 What problems does Spring Boot solve compared to configuring a traditional Spring application manually? easy

spring-bootfundamentalsauto-configuration
Reference answer
Spring Boot reduces repetitive configuration through opinionated defaults, starter dependencies, and auto-configuration. It supports embedded web servers, externalized configuration, and production monitoring through Actuator. Developers can focus on application logic while retaining control over Spring configuration.
Did you know it?

2 What happens internally when SpringApplication.run() is invoked? medium

application-lifecyclespring-contextstartup
Reference answer
SpringApplication prepares the environment, creates the appropriate ApplicationContext, and applies initializers. It loads bean definitions, refreshes the context, and starts an embedded web server when applicable. Finally, it invokes application and command-line runners and publishes lifecycle events.
Did you know it?

3 How does @SpringBootApplication combine multiple Spring annotations? easy

annotationscomponent-scanningconfiguration
Reference answer
@SpringBootApplication combines @SpringBootConfiguration, @EnableAutoConfiguration, and @ComponentScan. These enable Java-based configuration, conditional auto-configuration, and component discovery. By default, component scanning begins in the package containing the application class and its subpackages.
Did you know it?

4 How does Spring Boot decide whether to create an auto-configured bean? medium

auto-configurationconditional-beansspring-context
Reference answer
Auto-configuration classes use conditions such as @ConditionalOnClass, @ConditionalOnMissingBean, and @ConditionalOnProperty. Spring evaluates the classpath, existing beans, configuration properties, and application type. A user-defined bean can cause an auto-configured bean to back off when its conditions require a missing bean.
Explain how the conditions evaluation report helps investigate unexpected auto-configuration.
Did you know it?

5 How do Spring Boot starter dependencies simplify dependency management? easy

startersdependency-managementmaven
Reference answer
Starters provide curated groups of dependencies for specific application capabilities. Spring Boot dependency management supplies compatible versions for supported libraries. For example, the Spring Web starter brings together dependencies needed for building web applications without manually selecting every library version.
Did you know it?

6 How would you override a property supplied by application.yml without modifying the packaged application? easy

configurationpropertiesdeployment
Reference answer
Spring Boot supports externalized configuration through environment variables, command-line arguments, and external configuration files. For example, --server.port=9090 overrides the configured server port. Property precedence determines the effective value, allowing environment-specific deployment without rebuilding the application.
Did you know it?

7 What is the difference between @Component, @Service, and @Repository? easy

annotationsdependency-injectionstereotypes
Reference answer
All three register Spring-managed components through component scanning. @Service communicates business-layer intent, while @Repository identifies persistence components and participates in persistence exception translation. @Component is the general-purpose stereotype for classes that do not require a more specific role.
Did you know it?

8 Why is constructor injection generally preferred over field injection? easy

dependency-injectiontestingbean-design
Reference answer
Constructor injection makes required dependencies explicit and supports immutable fields. It allows objects to be instantiated directly in unit tests without reflection or a Spring container. It also exposes circular dependencies during application initialization rather than hiding them behind field injection.
Did you know it?

9 How do Spring profiles help manage application behavior across environments? easy

profilesconfigurationenvironments
Reference answer
Profiles activate environment-specific beans and configuration documents. For example, application-prod.yml can provide production database settings while application-dev.yml supplies local settings. Profiles can be activated using spring.profiles.active, and @Profile can restrict bean registration.
Did you know it?

10 What is the purpose of Spring Boot Actuator in a production application? easy

actuatormonitoringproduction
Reference answer
Actuator exposes operational capabilities such as health checks, metrics, application information, and environment diagnostics. It integrates with monitoring systems through Micrometer. Sensitive endpoints should be restricted because some can expose configuration or internal application details.
Did you know it?

11 A custom DataSource bean is defined, but Spring Boot no longer creates its default DataSource. Why? medium

datasourceauto-configurationconditional-beans
Reference answer
DataSource auto-configuration commonly uses @ConditionalOnMissingBean to avoid replacing an existing DataSource. Once a matching custom bean exists, the default creation path backs off. Inspect the conditions evaluation report to confirm which condition matched and which configuration was skipped.
Did you know it?

12 A Spring Boot application starts successfully, but a @Service class is not injected into a controller. What would you investigate? medium

component-scanningdependency-injectionbean-registration
Reference answer
Check whether the service package is included in component scanning and whether its registration conditions are satisfied. Verify that the class has an appropriate stereotype annotation or is registered through @Bean. Also inspect active profiles, bean qualifiers, and whether the controller itself is Spring-managed.
Did you know it?

13 How would you resolve multiple implementations of the same interface when Spring cannot determine which bean to inject? medium

qualifierprimarydependency-injection
Reference answer
Use @Qualifier to identify the intended implementation at the injection point. Alternatively, mark one implementation with @Primary to make it the default candidate. For strategies requiring multiple implementations, inject a List or Map of beans and select the appropriate implementation explicitly.
Did you know it?

14 Why can injecting a prototype-scoped bean into a singleton produce unexpected behavior? medium

bean-scopesingletonprototype
Reference answer
Spring resolves the prototype dependency when the singleton is created, so the singleton normally retains that same instance. Prototype scope does not automatically create a new object for every method call. Use ObjectProvider, a scoped proxy, or an appropriate factory when fresh instances are required.
Did you know it?

15 What is the practical difference between @ConfigurationProperties and @Value when binding application settings? medium

configuration-propertiesproperty-bindingvalidation
Reference answer
@Value is convenient for injecting individual configuration values or expressions. @ConfigurationProperties binds related settings into structured, type-safe objects and supports validation. For large configuration groups, it improves maintainability, discoverability, and testing.
Did you know it?

16 A Spring Boot application fails during startup because two beans depend on each other. How would you redesign it? medium

circular-dependencybean-lifecycledesign
Reference answer
A circular dependency usually indicates tightly coupled responsibilities between components. Extract shared functionality into a separate service, introduce an event-based interaction, or restructure ownership of the dependency. @Lazy can defer dependency resolution in some cases, but it should not replace correcting the underlying design.
Did you know it?

17 Why might a method annotated with @Transactional not start a transaction when called from another method in the same class? hard

transactionsaop-proxyself-invocation
Reference answer
In Spring's default proxy-based transaction management, internal method calls bypass the transactional proxy. Consequently, the transaction interceptor is not invoked for that self-invocation. Move the transactional operation into another Spring-managed bean or use an appropriate programmatic transaction mechanism.
Explain proxy interception and why simply adding @Transactional to a private method does not solve the issue.
Did you know it?

18 A @Transactional method updates a database record and then throws a checked exception. Why might the update still be committed? medium

transaction-managementrollbackexceptions
Reference answer
By default, Spring rolls back transactions for RuntimeException and Error, but not ordinary checked exceptions. A checked exception can therefore propagate while the transaction commits. Configure rollbackFor for the required exception or use an explicit rollback policy appropriate to the business operation.
Did you know it?

19 How does REQUIRES_NEW behave when a transactional service calls another transactional operation? hard

transaction-propagationrequires-newdatabase
Reference answer
REQUIRES_NEW suspends an existing transaction and starts an independent transaction for the invoked operation. Its commit or rollback is independent of the outer transaction. It can require an additional database connection and should be used carefully when many concurrent requests execute nested transactions.
Did you know it?

20 A REST endpoint returns a list of 100 orders, but Hibernate executes more than 100 additional queries. What is the likely cause? hard

hibernaten-plus-onequery-optimization
Reference answer
This commonly indicates the N+1 query problem, where related entities are loaded individually during iteration. Investigate SQL logs and Hibernate statistics to identify repeated relationship queries. Use targeted fetch joins, entity graphs, DTO projections, or batching based on the endpoint's data requirements.
Did you know it?

21 Why can changing every JPA relationship to FetchType.EAGER make an application slower? medium

jpafetch-strategyperformance
Reference answer
Eager fetching can retrieve relationships that a particular use case does not need. It may increase query complexity, memory consumption, and database traffic, and does not universally eliminate N+1 queries. Prefer use-case-specific fetch plans and projections rather than globally eager relationships.
Did you know it?

22 A Spring Data JPA repository loads an entity successfully, but accessing a lazy relationship later throws LazyInitializationException. Why? medium

hibernatelazy-loadingpersistence-context
Reference answer
The relationship was not initialized while an appropriate persistence context was available. Accessing it after the persistence context closes prevents Hibernate from loading the associated data. Fetch the required relationship within the service transaction using an entity graph, fetch join, or DTO projection.
Did you know it?

23 How would you prevent two concurrent requests from overwriting each other's updates to the same database entity? hard

optimistic-lockingconcurrencyjpa
Reference answer
Use optimistic locking with a @Version field when conflicts are relatively uncommon. Hibernate includes the version in update checks and detects conflicting modifications. For highly contended operations, evaluate pessimistic locking, atomic database updates, or application-specific concurrency controls.
Did you know it?

24 A batch import saves thousands of JPA entities but becomes progressively slower and consumes excessive memory. How would you optimize it? hard

batch-processinghibernatememory-optimization
Reference answer
Process records in bounded batches and periodically flush and clear the persistence context. Enable suitable JDBC batching and avoid unnecessary entity loading or per-record queries. Measure transaction size, database constraints, indexes, and memory usage before selecting the batch size.
Did you know it?

25 What happens when a @Transactional(readOnly = true) method modifies a managed JPA entity? hard

transactionshibernateread-only
Reference answer
readOnly is primarily a transaction hint, not a universal guarantee that database writes are prohibited. With Hibernate, Spring may adjust flush behavior, so automatic persistence of modifications can be suppressed. Do not rely on readOnly as a security boundary; use database permissions for strict write restrictions.
Did you know it?

26 A controller uses @Valid on a request DTO, but invalid requests still reach the service layer. What would you check? medium

bean-validationrest-apirequest-binding
Reference answer
Verify that Bean Validation support and a validation provider are present and that constraints are declared correctly. Ensure @Valid or @Validated is applied to the appropriate request parameter. Also confirm that validation errors are not being swallowed by custom exception handlers or unusual binding logic.
Did you know it?

27 How would you design consistent error responses across multiple REST controllers? medium

exception-handlingproblem-detailrest-api
Reference answer
Use @RestControllerAdvice with @ExceptionHandler methods to centralize exception translation. Return appropriate HTTP status codes and structured error details, such as Spring's ProblemDetail representation. Avoid exposing internal stack traces or sensitive exception messages to clients.
Did you know it?

28 A client retries a POST request after a timeout and accidentally creates two payment records. How would you prevent duplication? hard

idempotencyrest-apiconcurrency
Reference answer
Introduce an idempotency key supplied by the client and persist its processing outcome. Enforce uniqueness atomically so concurrent retries cannot create duplicate operations. Return the previously recorded result for a completed request, while handling in-progress requests and failures explicitly.
Discuss database uniqueness constraints and the difference between an idempotent API contract and an HTTP method's usual semantics.
Did you know it?

29 How would you implement pagination for a large Spring Data JPA dataset without creating unnecessary count queries? medium

paginationspring-data-jpadatabase-performance
Reference answer
Use Pageable with Page when the total number of records is required. Use Slice when only the existence of another page is needed, avoiding a typical total-count query. For very large or frequently changing datasets, consider keyset pagination with stable ordering and suitable indexes.
Did you know it?

30 Why can returning JPA entities directly from REST controllers create architectural and security problems? medium

dtorest-designjpa
Reference answer
Entities expose persistence structure and may unintentionally serialize sensitive fields or lazy relationships. Bidirectional associations can also create serialization problems or unexpectedly expensive queries. Use request and response DTOs to define stable API contracts and control which fields are exposed.
Did you know it?

31 How does Spring Security process an incoming HTTP request in a Spring Boot application? medium

spring-securityfilter-chainauthentication
Reference answer
The request passes through the servlet filter chain, where Spring Security's FilterChainProxy selects the applicable SecurityFilterChain. Security filters perform tasks such as authentication, authorization, and security-context management. Filter order and request matching determine which security mechanisms apply.
Did you know it?

32 A JWT is cryptographically valid, but a protected endpoint still returns HTTP 403. What would you investigate? hard

jwtauthorizationspring-security
Reference answer
A valid signature does not guarantee sufficient authorization. Inspect token issuer, audience, expiration, authority mapping, and endpoint authorization rules. Check whether the authenticated principal has the expected roles or scopes and whether method-level security imposes additional restrictions.
Did you know it?

33 Why is RS256 often preferable to HS256 when multiple microservices must validate access tokens? medium

jwtrs256microservices-security
Reference answer
RS256 uses a private key for signing and a public key for verification. Resource services can validate tokens without possessing the signing secret, reducing the impact of a compromised verifier. HS256 uses a shared secret, so any service holding it can potentially generate valid tokens.
Did you know it?

34 How would you rotate JWT signing keys without immediately invalidating every active access token? hard

jwtkey-rotationjwks
Reference answer
Publish verification keys through a JWKS endpoint and identify signing keys using a key ID in the JWT header. Introduce a new signing key while retaining the old public key for verification during the overlap period. Remove the old key after its issued tokens have expired, accounting for clock skew and verifier cache behavior.
Did you know it?

35 Why is disabling CSRF protection for every Spring Boot application an unsafe general recommendation? medium

csrfspring-securityweb-security
Reference answer
CSRF risk depends on how browsers automatically attach authentication credentials. Stateless APIs authenticated exclusively through explicitly supplied bearer tokens often do not need traditional CSRF protection. Applications using session cookies or other automatically attached credentials may still require CSRF defenses.
Did you know it?

36 How would you secure Actuator endpoints while keeping health probes accessible to infrastructure? medium

actuatorendpoint-securityhealth-checks
Reference answer
Expose only the operational endpoints required by the deployment. Configure a dedicated SecurityFilterChain or management interface with appropriate authentication and network restrictions. Allow narrowly scoped health probes while protecting sensitive endpoints such as environment, heap dump, and configuration diagnostics.
Did you know it?

37 A Spring Boot service experiences connection timeouts under load even though the database CPU remains low. How would you investigate? hard

hikaricpconnection-poolperformance-debugging
Reference answer
Inspect HikariCP metrics for active, idle, pending, and maximum connections. Look for long-running transactions, leaked connections, slow queries, and connection-pool exhaustion. Compare pool sizing with database connection limits and request concurrency before increasing the pool size.
Did you know it?

38 HikariCP reports an apparent connection leak, but the connection is eventually returned. Does this prove a leak? hard

hikaricpconnection-leaktransactions
Reference answer
No. Leak detection reports connections held longer than the configured threshold, including legitimately long operations. Investigate transaction boundaries, query duration, blocking calls, and the reported acquisition stack trace. A later return can indicate a slow operation rather than a permanently leaked connection.
Did you know it?

39 A method annotated with @Async executes synchronously when called from another method in the same class. Why? medium

asyncaop-proxythread-pool
Reference answer
With default proxy-based async execution, self-invocation bypasses the Spring proxy responsible for scheduling asynchronous execution. Move the asynchronous method into another Spring-managed bean and call it through the proxy. Also ensure asynchronous execution is enabled and a suitable executor is configured.
Did you know it?

40 How would you prevent @Async tasks from exhausting application resources during a sudden traffic spike? hard

asyncthread-poolbackpressure
Reference answer
Configure a bounded ThreadPoolTaskExecutor with appropriate core size, maximum size, and queue capacity. Define a rejection policy and apply backpressure or rate limiting when the system reaches capacity. Monitor queue depth, active threads, execution latency, and task failures.
Did you know it?

41 Why can @Scheduled tasks run multiple times when a Spring Boot application is deployed with several replicas? medium

schedulingdistributed-lockdeployment
Reference answer
Each application instance has its own scheduler, so the same scheduled method can execute independently on every replica. For a cluster-wide single execution, use a distributed lock, a centralized scheduler, or an external job system. Design jobs to tolerate retries and duplicate execution where possible.
Did you know it?

42 How would you implement reliable event publication when a database transaction and a message broker must both be involved? hard

transactional-outboxmessagingdistributed-systems
Reference answer
Use the transactional outbox pattern to store the business change and an outgoing event in the same database transaction. A separate publisher transfers committed outbox records to the message broker. Consumers should handle duplicate delivery through idempotent processing because publication may be retried.
Did you know it?

43 A Spring Boot service calls another service that becomes intermittently unavailable. How would you prevent cascading failures? hard

resiliencecircuit-breakermicroservices
Reference answer
Apply connection and response timeouts, bounded retries with backoff, and circuit breakers where appropriate. Use concurrency limits or bulkheads to prevent one failing dependency from consuming all request-processing resources. Only retry operations that are safe to repeat, and monitor failure rates and fallback behavior.
Did you know it?

44 How would you choose between RestClient, WebClient, and RestTemplate for outbound HTTP calls? medium

restclientwebclienthttp-client
Reference answer
RestClient provides a modern synchronous fluent API and is suitable for typical blocking request-response interactions. WebClient supports reactive, non-blocking communication and streaming use cases. RestTemplate remains usable for existing applications but is generally not the preferred choice for new development.
Did you know it?

45 Why can calling block() inside a Spring WebFlux request-processing pipeline reduce application throughput? hard

webfluxreactornon-blocking-io
Reference answer
block() waits synchronously and can occupy a Reactor event-loop thread that should remain available for non-blocking work. Under load, this can cause thread starvation, increased latency, or blocking-operation errors. Compose reactive publishers instead, and isolate unavoidable blocking work on an appropriate bounded scheduler.
Did you know it?

46 How would you investigate a Spring Boot application that becomes slow only after running for several days? hard

memory-leakobservabilityproduction-debugging
Reference answer
Compare historical metrics for heap usage, garbage collection, thread counts, connection pools, and response latency. Use thread dumps, heap dumps, profiling, and distributed traces to identify accumulating resources or slow operations. Correlate the degradation with traffic, scheduled jobs, cache growth, and recent deployments.
Did you know it?

47 What is the difference between @SpringBootTest and @WebMvcTest, and when should each be used? medium

spring-boot-testwebmvctestintegration-testing
Reference answer
@SpringBootTest loads a broad application context and is useful for integration testing across components. @WebMvcTest focuses on the MVC layer, including controllers and relevant web infrastructure, while excluding most application services. Choose the narrowest test scope that verifies the behavior to reduce execution time and unnecessary dependencies.
Did you know it?

48 Why can a @Transactional integration test pass even though the equivalent production operation fails? hard

transactional-testsintegration-testingdatabase
Reference answer
Transactional tests commonly roll back their changes and may share a transaction across setup and verification steps. This can hide commit-time constraints, flushing behavior, and differences in transaction boundaries. Test explicit commits, separate transactions, and real database behavior when validating production transaction semantics.
Did you know it?

49 How would you use Testcontainers to detect database-specific issues that an in-memory test database might miss? medium

testcontainersintegration-testingdatabase
Reference answer
Testcontainers runs integration tests against disposable instances of real database engines. It helps verify SQL dialect behavior, migrations, indexes, constraints, and database-specific features. Configure Spring Boot tests to use the container's connection details and keep test data isolated and reproducible.
Did you know it?

50 A Spring Boot application passes its startup health check but fails requests immediately after deployment. How would you improve deployment readiness? hard

readiness-probegraceful-shutdowndeployment
Reference answer
Separate liveness from readiness so infrastructure can distinguish an unhealthy process from one temporarily unable to serve traffic. Configure readiness probes to reflect essential startup and service availability conditions without depending on every optional downstream system. Use graceful shutdown and appropriate probe thresholds to reduce failed requests during rolling deployments.
Explain why liveness checks should not depend on shared downstream services and how readiness controls traffic routing.
Did you know it?
0 / 0 answered

↑ Back to top