Top 50 Spring Boot Interview Questions and Answers (2026 Edition)
Top 50 Spring Boot Interview Questions and Answers (2026 Edition) Work through these 50 questions out loud. Open any question for the full model answer, the trap to avoid, and the follow-up a panel usually asks.
Your Spring Boot service crashes under high traffic. What could be the reasons?
Common causes: too-small heap (`-Xmx`), Hikari pool smaller than concurrent requests, blocking calls on limited threads, missing backpressure. Fix: tune...
You need different configs for dev, test, and prod. How will you design this?
Use `application.yml` for shared defaults plus `application-dev.yml`, `application-test.yml`, `application-prod.yml`. Activate via env `SPRING_PROFILES_ACTIVE=prod`. Never...
How do you handle API failures when calling another microservice?
Use Resilience4j with Spring Boot 3: timeout, circuit breaker, bulkhead. Never retry POST payments without idempotency key. ```java @CircuitBreaker(name = "billing",...
How do you implement retry logic for failed REST calls?
```java @Retry(name = "inventory", fallbackMethod = "inventoryFallback") public StockLevel fetchStock(String sku) { return restClient.get().uri("/stock/{sku}",...
You deployed a new version but users still hit the old behavior. Why?
Check K8s rollout status — old ReplicaSet still receiving traffic. Bust cache on static assets; API GET with `Cache-Control`. Confirm image tag in running pod matches CI build....
How do you secure sensitive values like DB passwords in Spring Boot
Reference secrets via environment or mounted files — not plaintext in repo. ```yaml spring: datasource: password: ${DB_PASSWORD} ``` Use Vault, AWS Secrets Manager, or K8s...
Your logs are missing in production. Where do you look?
Check `logback-spring.xml` and `logging.level` in prod profile. Containers should log to stdout for ELK/Datadog — file-only paths lost when pod restarts. ```yaml logging:...
How do you handle versioning of REST APIs without breaking clients?
Prefer non-breaking changes: add optional JSON fields. Breaking changes → new path `/api/v2`. ```java @RestController @RequestMapping("/api/v1/users") public class...
One microservice is down and others are failing. How do you prevent this?
Cascade failure happens when callers block waiting. Use Resilience4j circuit breaker — open circuit fails fast with degraded response. ```java @CircuitBreaker(name = "catalog",...
How do you reduce startup time of a Spring Boot application?
Exclude unused auto-config, defer heavy beans, use `spring.main.lazy-initialization=true` cautiously in dev. Measure with Spring Boot startup actuator. ```java...
You need to execute code only once after application startup. How?
```java @Component public class CacheWarmup implements ApplicationRunner { @Override public void run(ApplicationArguments args) { catalogService.warmCache(); } } ``` Runs once...
How do you handle long-running background jobs in Spring Boot?
Do not block HTTP threads. Use `@Async` with named executor or message-driven workers. ```java @EnableAsync @Configuration public class AsyncConfig { @Bean Executor...
How do you implement rate limiting for APIs?
Apply at API Gateway; in-app use Redis-backed limiter for cluster-wide counts. ```java @RateLimiter(name = "apiLimiter") @GetMapping("/users") public List<User> users() {...
How do you test production-like behavior locally?
Local H2 ≠ prod Postgres. Use Testcontainers for integration tests. ```java @Testcontainers @SpringBootTest class OrderApiIT { @Container static PostgreSQLContainer<?> db = new...
What are common mistakes freshers make in Spring Boot projects?
```java // ❌ Wrong @RestController public class OrderController { @PostMapping("/orders") public Order create(@RequestBody Order o) { return orderRepository.save(o); // DB in...
API returns correct data but response time is inconsistent. Why?
Tail latency often from stop-the-world GC, connection pool contention, or cold cache. Monitor p99 separately from mean. ```yaml spring.datasource.hikari.maximum-pool-size: 10...
What strategy do you use for graceful shutdown?
```yaml server: shutdown: graceful spring: lifecycle: timeout-per-shutdown-phase: 30s ``` K8s preStop hook + readiness fail removes pod from LB before SIGTERM. Prevents dropped...
Your Spring Boot app fails only when deployed in Docker. Why?
Container `-Xmx256m` with 256Mi limit causes OOMKilled. Missing `DB_HOST` defaults to localhost inside container. ```dockerfile ENV JAVA_OPTS="-XX:MaxRAMPercentage=75.0" ```...
One API intermittently times out, no errors in logs. How do you debug?
No app log may mean thread blocked waiting on external IO. Enable Feign/logger + trace. Check LB/proxy timeouts vs client timeouts. ```yaml feign: client: config: default:...
How do you handle backward compatibility for response fields?
Old mobile clients break on removed JSON keys. Add new fields as optional nullables. ```java public record UserResponse( String id, String email,...
How do you safely rotate secrets in a running app?
Store secrets in Vault/K8s Secrets; refresh without full restart using Spring Cloud. ```java @RefreshScope @Component public class DbConfig { @Value("${db.password}") private...
New deployment causes random 5xx errors. Rollback fixes it. Why?
Compare metrics before/after: error rate, pool saturation, GC. Enable DEBUG temporarily in canary pod only. Check new dependency version, connection pool default change, or...
You enabled caching but performance did not improve. Why?
Measure hits/misses. Wrong key expression caches per wrong granularity. ```java @Cacheable(value = "users", key = "#id") public User findById(Long id) { return...
How does Spring Boot auto-configuration work?
@SpringBootApplication enables @EnableAutoConfiguration, which loads candidate configs from starters. Each auto-config uses @ConditionalOn* to register beans only when...
@RestController vs @Controller?
@Controller is for traditional MVC — return "user/list" view name. @RestController adds @ResponseBody so return types become JSON/XML body — standard for REST APIs. Use...
What are Spring Boot starters?
spring-boot-starter-web brings spring-webmvc, Tomcat, Jackson with tested versions and enables WebMvcAutoConfiguration. You declare one starter instead of 10 coordinates....
How do you handle exceptions globally in Spring?
Create @RestControllerAdvice with @ExceptionHandler(MethodArgumentNotValidException.class) returning 400 + field map, NotFoundException → 404, generic Exception → 500 without...
How do you test Spring Boot applications?
Unit test services with Mockito — no Spring. @WebMvcTest + MockMvc for controller contract. @DataJpaTest for repository queries. @SpringBootTest + Testcontainers for critical...
How do you version REST APIs?
We use /api/v1/users for clarity. Non-breaking: add optional JSON fields. Breaking: launch v2 path, maintain v1 for 6 months with Deprecation header. Spring maps...
What are virtual threads in Java 21 and when should you use them?
Virtual threads excel when code blocks on IO — HTTP clients, JDBC, file reads — allowing one platform thread to serve thousands of concurrent requests. For CPU-heavy parallel...
What is the Java Platform Module System (JPMS) and who needs it?
Use modules when building custom JDK images or publishing strict API boundaries. Typical microservice: no module-info — Spring Boot repackages classpath. Watch for illegal...
What changed migrating Spring Boot 2 to Spring Boot 3 (Jakarta EE)?
Upgrade to Java 17+, replace imports javax.persistence → jakarta.persistence, update Spring Security config to SecurityFilterChain lambda DSL, run OpenRewrite migration recipe,...
How does spring.config.import work for externalized configuration?
In K8s: spring.config.import=optional:configtree:/etc/secrets/,optional:configtree:/etc/config/ mounts volumes as properties. Vault:...
How do Spring Boot Actuator health probes work with Kubernetes?
Enable probes, configure K8s readinessProbe on /actuator/health/readiness, liveness on /actuator/health/liveness. Custom HealthIndicator for critical deps on readiness group...
What are GraalVM native image considerations for Spring Boot?
Use spring-boot-maven-plugin native profile + GraalVM 21. Run integration tests on native binary. Register reflection for Jackson/custom serializers. Trade longer CI builds for...
How does Bean Validation work in Spring Boot 3?
DTO fields: @NotBlank, @Email, @Size. Controller: createUser(@Valid @RequestBody UserDto dto). Global @RestControllerAdvice maps MethodArgumentNotValidException to 400 + field...
Explain @ConfigurationProperties vs @Value.
@ConfigurationProperties(prefix = "app.payment") record PaymentProps(int timeout, String apiUrl) {} — validated, testable, grouped. Use @Value only for single feature flags....
How do you enable virtual threads in Spring Boot 3.2+?
application.yml: spring.threads.virtual.enabled=true on Java 21. Verify integration tests pass — especially security, transactions, MDC logging. Replace custom fixed thread...
What is ProblemDetail (RFC 7807) in Spring 6 error handling?
@ExceptionHandler(NotFoundException.class) ProblemDetail handle(NotFoundException ex) { return ProblemDetail.forStatusAndDetail(NOT_FOUND, ex.getMessage()); } — consistent 404...
When should you use spring.main.lazy-initialization?
Use in test slices or large batch apps where most beans unused per run. Production APIs: fix slow @PostConstruct and DB migrations instead. Combine with...
How do you expose custom metrics with Micrometer in Spring Boot?
Service method: orderCounter.increment(); timer.record(() -> process()). Add Tags.of("tenant", tenantId) for multi-tenant. Expose...
springdoc-openapi vs legacy springfox — what should new projects use?
Add springdoc-openapi-starter-webmvc-ui dependency. Annotate with @Operation, @Schema on DTOs. Disable in prod via springdoc.api-docs.enabled=false or secure endpoint. Generate...
How do Spring profiles work for dev, staging, and production?
Base application.yml shared defaults. application-dev.yml local Docker Compose. application-prod.yml from K8s ConfigMap + secrets. Activate via SPRING_PROFILES_ACTIVE=prod....
What is Spring Boot Docker Compose dev services support?
Add compose.yaml with postgres and redis services. Include spring-boot-docker-compose on runtimeOnly. Boot starts Postgres, sets JDBC URL — zero local install. CI uses...
How does Micrometer Tracing replace Spring Cloud Sleuth?
Dependencies: micrometer-tracing-bridge-otel, opentelemetry-exporter-otlp. Traces propagate Authorization-safe headers across RestClient/WebClient calls. Correlate logs with...
How do Flyway/Liquibase integrate with Spring Boot JPA?
Prod: spring.jpa.hibernate.ddl-auto=validate, Flyway V1__init.sql through Vn. CI: @Testcontainers PostgreSQL + Flyway migrate + integration tests. Never rename column without...
Kubernetes liveness vs readiness vs startup probes?
deployment.yaml: startupProbe HTTP /actuator/health with failureThreshold*period covering 60s startup. readinessProbe /actuator/health/readiness includes DB. livenessProbe...
Your Spring Boot app works locally but fails after deployment. What are the first 3 things you check?
First: confirm `spring.profiles.active` and required env vars exist in prod (`kubectl describe pod`, deployment manifest). Second: read startup logs and `/actuator/health` —...
A REST API is slow only in production, not locally. How do you debug it?
Enable Micrometer timers and Hibernate statistics or datasource-proxy in staging with prod-like data. Check Hikari `connections-active`, JVM GC pauses, and Feign/RestClient...
You changed application.properties but changes are not reflecting. Why?
Spring resolves properties in order: command line > OS env > profile-specific file. `SPRING_DATASOURCE_URL` overrides `application.properties`. After config change, confirm new...
Cracking the Spring Boot Interview: Tips and Must-Know Questions · Spring Boot Interview Questions and Answers · Top 40 Spring Boot Interview Questions | Must-Prepare before interview. · Spring Boot Interview Questions Every Fresher Must Know
All interview question lists · Interview guides · Home · Support the platform