200 Essential Spring Boot Interview Questions
200 Essential Spring Boot Interview Questions
Questions
This comprehensive collection of 200 Spring Boot interview questions covers every aspect of modern Spring Boot
development, from basic concepts to advanced enterprise patterns. The questions are organized by difficulty and topic
areas to provide a structured learning path for developers at all levels.
Each question is designed to test both theoretical knowledge and practical implementation skills, preparing candidates
for real-world Spring Boot development challenges and technical interviews at any level of expertise.
3
Fundamentals
1. What is Spring Boot and how does it differ from the Spring Framework?
Spring Boot is a framework built on top of Spring Framework that simplifies application development by providing auto-
configuration, embedded servers, and starter dependencies. Unlike traditional Spring, it reduces boilerplate
configuration and enables rapid application development.[1][2]
Auto-configuration automatically configures Spring applications based on the dependencies present in the classpath. It
uses @EnableAutoConfiguration annotation and conditional annotations like @ConditionalOnClass to determine
what to configure.[3][4]
@EnableAutoConfiguration, and @ComponentScan. It marks the main class of a Spring Boot application[1][5].
Spring Boot follows these steps: creates SpringApplication instance, loads configuration, scans for components, creates
ApplicationContext, starts embedded server, and runs the main method with auto-configuration enabled.[3]
5. What are Spring Boot Starters and why are they important?
Starters are pre-configured dependency descriptors that include all necessary dependencies for specific functionality.
Examples include spring-boot-starter-web, spring-boot-starter-data-jpa, and spring-boot-starter-
security.[5][1]
These files provide externalized configuration for Spring Boot applications, allowing developers to configure database
connections, server ports, logging levels, and custom properties without hardcoding values.[6]
All are specializations of @Component: @Service for business logic, @Repository for data access with exception
translation, and @Controller for MVC controllers. They provide semantic meaning and specialized functionality.[5]
Spring Boot uses IoC (Inversion of Control) container to manage beans and their dependencies. It supports constructor
injection (recommended), field injection with @Autowired, and setter injection.[6][5]
9. What are Spring Boot profiles and how do you use them?
Profiles allow different configurations for different environments (dev, test, prod). You can create profile-specific
property files like [Link] and activate them using [Link].[6]
Conditional beans are created only when specific conditions are met. Annotations like @ConditionalOnProperty,
@ConditionalOnClass, and @ConditionalOnMissingBean control bean creation.[6]
Spring Boot supports externalized configuration through property files, environment variables, command-line
arguments, and config servers. It follows a specific property precedence order.[7][6]
@ConfigurationProperties binds external properties to Java objects, providing type-safe configuration management.
Use Spring profiles to manage environment-specific configurations. Create separate property files for each environment
and activate appropriate profiles during deployment.[6]
Command-line arguments > Environment variables > application-{profile}.properties > [Link] > Default
properties.[6]
Use @ConditionalOnProperty annotation with boolean properties to enable/disable features dynamically without code
changes.[8]
@RestController combines @Controller and @ResponseBody, automatically serializing return values to JSON/XML.
@Value injects values from property files, environment variables, or SpEL expressions into fields or constructor
parameters[10].
@ComponentScan tells Spring where to look for components. By default, it scans the package of the main class and all sub-
packages[6].
@Autowired enables automatic dependency injection. Alternatives include constructor injection (recommended),
Singleton (default), Prototype, Request, Session, Application, and WebSocket scopes. Each determines how many
instances are created and their lifecycle.[11]
Use @PostConstruct and @PreDestroy annotations, implement InitializingBean and DisposableBean interfaces, or
use @Bean(initMethod, destroyMethod).[11]
@Component is used for automatic component scanning, while @Bean is used in configuration classes to explicitly define
beans[11].
Spring Boot detects circular dependencies at startup and throws BeanCurrentlyInCreationException. Solutions
include constructor injection restructuring or @Lazy annotation.[11]
6
Lazy initialization defers bean creation until first use, improving startup time. Enable with [Link]-
initialization=true or @Lazy annotation.[12]
Both interfaces allow executing code after Spring Boot application startup. CommandLineRunner receives raw string
arguments, while ApplicationRunner receives parsed ApplicationArguments.[10]
DevTools provides development-time features like automatic restart, live reload, remote debugging, and property
defaults to improve developer productivity.[12][5]
Add spring-boot-devtools dependency to enable automatic application restart when classpath changes are
detected.[6]
Command Line Interface allows running Groovy scripts with Spring Boot features, rapid prototyping, and application
development without explicit build configuration.[10]
Use IDE debugging, Spring Boot DevTools remote debugging, Actuator endpoints for monitoring, and logging
configuration for troubleshooting.[13]
RESTful Services
Spring Boot provides @RestController, automatic JSON/XML serialization with Jackson, content negotiation, and
embedded servers for REST API development.[9][6]
@PathVariable extracts values from URI templates (/users/{id}), while @RequestParam extracts query parameters
(/users?id=1)[9].
Use validation annotations like @Valid, @NotNull, @Size, @Min with @RequestBody and handle validation errors with
@ExceptionHandler.[9][5]
Content negotiation allows APIs to return different formats (JSON, XML) based on client preferences specified in Accept
headers.[9]
HATEOAS (Hypermedia as the Engine of Application State) includes links in responses. Use Spring HATEOAS library
with RepresentationModel and linkTo() methods.[9]
Use method-specific annotations: @GetMapping for retrieval, @PostMapping for creation, @PutMapping for updates,
@DeleteMapping for deletion.[9]
Use ResponseEntity to control status codes, or use @ResponseStatus annotation on methods or exception classes.[9]
Idempotency ensures that multiple identical requests have the same effect as a single request. GET, PUT, DELETE are
idempotent; POST is not.[9]
Use Pageable parameter with Spring Data, return Page objects, and include pagination metadata in responses.[9]
Implement versioning through URL paths (/api/v1/users), request headers (Accept-Version), or query parameters
(?version=1).[1][9]
Exception Handling
8
responses to JSON/XML[5].
Extend RuntimeException or specific exception classes, add @ResponseStatus annotation, and handle with
@ExceptionHandler.[9]
Catch MethodArgumentNotValidException in @ExceptionHandler and return structured error responses with field-
level error details.[9]
Include error codes, messages, timestamps, request IDs, and field-level validation errors in consistent JSON structure.[9]
Use @WebMvcTest for slice testing, MockMvc for integration testing, and TestRestTemplate or WebTestClient for full
integration tests.[14]
@MockBean creates mock beans in Spring context for testing, replacing actual beans with Mockito mocks during tests[14].
Use @WithMockUser or @WithUserDetails for authentication testing, and test authorization with different user roles.[14]
@WebMvcTest loads only web layer components for faster testing, while @SpringBootTest loads the complete application
context[14].
Use tools like JMeter, Gatling, or Spring Boot's built-in metrics with Actuator endpoints to measure response times and
throughput.[13]
Spring Data JPA is a library that simplifies data access by providing repository interfaces, query derivation from method
names, and integration with JPA providers like Hibernate.[15][16]
JPA is a specification for ORM in Java, while Hibernate is a specific implementation of JPA with additional features like
caching and custom mapping strategies.[15]
Configure multiple DataSource beans with @Primary and @Qualifier annotations, create separate @Configuration
classes for each database.[1][15]
Use @Entity annotation on classes, @Id for primary keys, @GeneratedValue for auto-generation, and @Column for field
mapping.[15]
@OneToOne, @OneToMany, @ManyToOne, and @ManyToMany relationships, each with options for fetch types and cascade
operations[15].
Use @Embeddable class with @EmbeddedId annotation or @IdClass annotation for composite primary keys.[15]
EAGER loading fetches related entities immediately, while LAZY loading fetches them only when accessed, improving
performance for large datasets.[15]
Use @Inheritance with strategies: SINGLE_TABLE, TABLE_PER_CLASS, or JOINED for different inheritance mapping
approaches.[15]
Use @Query annotation with JPQL or native SQL, method name derivation, or Criteria API for dynamic queries.[15]
62. What is the difference between JPQL and native SQL queries?
JPQL operates on entity objects and is database-agnostic, while native SQL works directly with database tables and is
database-specific.[15]
Use Pageable parameter in repository methods and return Page<T> objects containing data and pagination metadata.[9]
Use @Transactional annotation on methods or classes, configure transaction managers, and handle transaction
propagation and isolation levels.[15]
REQUIRED, REQUIRES_NEW, MANDATORY, SUPPORTS, NOT_SUPPORTED, NEVER, and NESTED - each defining how
transactions behave when method calls are nested.[15]
Use @EnableCaching configuration and cache annotations: @Cacheable, @CacheEvict, @CachePut with cache providers
like Redis or EhCache.[13][5]
67. What is the N+1 query problem and how do you solve it?
11
N+1 problem occurs when fetching a list triggers additional queries for each item. Solve with @BatchSize, fetch joins, or
entity graphs.[15]
Use proper indexing, fetch joins, batch fetching, query optimization, connection pooling, and monitoring with SQL
logging.[13][15]
Entity graphs define which associations should be loaded eagerly, providing fine-grained control over fetching strategies
without changing entity definitions.[15]
Use Flyway or Liquibase for version-controlled database schema migrations with automatic execution during
application startup.[7]
Create custom repository interfaces, implement them with @Repository classes, and combine with Spring Data
repositories using composition.[15]
Spring Data REST automatically exposes repository interfaces as REST endpoints with HATEOAS support, reducing
boilerplate code for CRUD operations.[15]
Spring Boot uses HikariCP by default. Configure pool size, timeout, and other properties through
[Link].* properties.[13]
save() persists entity to persistence context, while saveAndFlush() immediately synchronizes with database and
flushes changes[15].
Use @DataJpaTest for slice testing, TestEntityManager for test data setup, and @Sql for script-based test data.[14]
Use in-memory databases like H2 for fast, isolated tests, or Testcontainers for testing with real database instances.[14]
Use @Transactional in tests for automatic rollback, @Rollback(false) to commit changes, and @DirtiesContext for
context cleanup.[14]
Use @Sql scripts, TestEntityManager, factory methods, or builders pattern for consistent test data creation.[14]
@DataJpaTest loads only JPA-related components, provides TestEntityManager, configures in-memory database, and
Authentication verifies user identity (who you are), while authorization determines what actions a user can perform
(what you can do).[19][17]
Use httpBasic() in security configuration and provide user credentials through in-memory, database, or custom user
details service.[17]
Form-based authentication, HTTP Basic, OAuth2, JWT, LDAP, database authentication, and custom authentication
providers.[20][17]
Use @EnableMethodSecurity and annotations like @PreAuthorize, @PostAuthorize, @Secured, and @RolesAllowed on
methods.[20]
Create JWT utility classes, configure JWT authentication filter, validate tokens in security filter chain, and handle token
generation/validation.[20][9]
OAuth2 is an authorization framework enabling third-party access. Implement using Spring Security OAuth2 with
authorization server and resource server configurations.[21][17]
Configure OAuth2 client with client ID, secret, authorization URI, token URI, and redirect URI for user authorization
flow.[21]
89. What is the difference between access tokens and refresh tokens?
Access tokens provide short-term API access, while refresh tokens enable obtaining new access tokens without re-
authentication.[20]
Configure resource server, validate access tokens, implement scope-based authorization, and handle token
introspection.[20]
Define roles and authorities, use @PreAuthorize("hasRole('ADMIN')"), configure URL-based authorization, and
implement custom authorization logic.[20]
Roles are higher-level permissions (ROLE_ADMIN), while authorities are specific permissions (READ_USER,
WRITE_USER).[20]
Use SpEL expressions in @PreAuthorize, implement custom security expressions, use method parameter-based
authorization.[20]
Configure CORS using @CrossOrigin annotation, CorsConfigurationSource bean, or global CORS configuration in
security config.[9]
Spring Security provides CSRF protection by default using tokens. Configure CSRF settings and disable for stateless APIs
using JWT.[17][21]
Implement AuthenticationFailureHandler, configure custom failure URLs, and provide meaningful error messages.[17]
Create custom filters extending OncePerRequestFilter, add to security filter chain, and handle
authentication/authorization logic.[20]
Use service-to-service authentication with JWT, implement API gateways, use mutual TLS, and secure inter-service
communication.[22]
101. What are security best practices for Spring Boot applications?
Use HTTPS, implement proper authentication/authorization, validate inputs, handle sensitive data securely, and keep
dependencies updated.[20]
Use strong password encoders like BCrypt, implement password policies, avoid storing plain text passwords, and use
secure password reset flows.[17]
Integrate with TOTP libraries, implement QR code generation, validate time-based tokens, and provide backup codes.[20]
Use encrypted properties, environment variables, external configuration servers, and avoid hardcoding sensitive
values.[20]
Use @WithMockUser, @WithUserDetails, security slice tests, and integration tests with different security contexts.[14]
Use tenant-specific security configurations, implement custom authentication providers, and isolate data access per
tenant.[20]
Configure session creation policy, implement session fixation protection, handle concurrent sessions, and use stateless
authentication for APIs.[17]
Configure security headers like CSP, HSTS, X-Frame-Options using Spring Security's header configuration.[17]
Use filters or interceptors to count requests, implement token bucket algorithm, and integrate with external rate limiting
services.[9]
Implement security event listeners, log authentication attempts, track authorization failures, and integrate with security
monitoring tools.[17]
Microservices Architecture
Spring Boot provides embedded servers, externalized configuration, health checks with Actuator, and integrates well
with Spring Cloud for distributed systems.[23][22]
Spring Cloud provides tools for distributed systems: service discovery (Eureka), load balancing, circuit breakers,
configuration management, and API gateways.[22]
Use Spring Cloud Netflix Eureka for service registry, clients register themselves and discover other services
dynamically.[24][22]
API Gateway acts as single entry point for clients, handling routing, authentication, rate limiting. Implement using Spring
Cloud Gateway or Netflix Zuul.[24][22]
Use Spring Cloud Config Server to centralize configuration, support dynamic refresh, and manage environment-specific
properties.[22]
Inter-Service Communication
Synchronous communication via REST/HTTP, asynchronous messaging with RabbitMQ/Kafka, and service mesh for
advanced scenarios.[24][22]
Use Resilience4j or Netflix Hystrix to prevent cascading failures, implement fallback methods, and monitor service
health.[22][24]
Saga pattern manages distributed transactions through sequence of local transactions with compensating actions for
failure scenarios.[24]
Use JWT tokens, mutual TLS, service mesh authentication, or OAuth2 client credentials flow for secure inter-service
communication.[22]
Use Spring Cloud Stream with message brokers like RabbitMQ or Apache Kafka for event-driven architecture and loose
coupling.[24]
Use @Retryable annotation with backoff policies, configure retry attempts, and implement recovery methods for failed
operations.[1][13]
Bulkhead pattern isolates resources to prevent failure in one area from affecting others, implementing separate thread
pools or connection pools.[24]
Configure read/connection timeouts, implement circuit breakers, use async processing, and provide meaningful timeout
responses.[22]
Use Spring Boot Actuator health endpoints, implement custom health indicators, and integrate with load balancers and
orchestration platforms.[13]
Implement circuit breakers, provide fallback responses, use eventual consistency, and design for graceful
degradation.[22]
Use Spring Cloud Sleuth with Zipkin or Jaeger to trace requests across microservices and identify performance
bottlenecks.[22]
Use Micrometer with Prometheus, implement custom metrics, monitor business and technical metrics, and create
dashboards.[13]
Use ELK stack (Elasticsearch, Logstash, Kibana) or similar solutions, implement correlation IDs, and structure logs for
better searchability.[13]
Actuator provides production-ready features: health checks, metrics, environment info, and management endpoints for
monitoring applications.[5][13]
Integrate APM tools like New Relic or Datadog, monitor JVM metrics, track response times, and set up alerting.[13]
Create Docker images using layered approach, optimize image size, use multi-stage builds, and implement proper
security practices.[25]
Use build pipelines, automated testing, independent deployments, blue-green deployments, and infrastructure as
code.[24]
Implement API versioning strategies, use backward compatibility, rolling deployments, and feature flags for gradual
rollouts.[22]
Blue-green deployment, rolling updates, canary deployments, and A/B testing for safe production deployments.[24]
Use Spring Cloud Config, Kubernetes ConfigMaps/Secrets, environment-specific configurations, and dynamic
configuration refresh.[22]
Create Kubernetes manifests, implement health checks, use ConfigMaps for configuration, and follow cloud-native
principles.[25]
Use Spring WebFlux for non-blocking, asynchronous programming with Reactor library for handling high-concurrency
scenarios.[25]
Store events instead of current state, use event store, implement event handlers, and support replay and temporal
queries.[24]
Each microservice owns its database, implement data consistency through events, use CQRS pattern, and handle
distributed queries.[24]
Use container security, service mesh for communication security, secrets management, and zero-trust architecture
principles.[22]
Performance Optimization
Enable lazy initialization, optimize database queries, implement caching, use connection pooling, and configure JVM
parameters appropriately.[12][13]
Use Spring Cache abstraction with Redis/EhCache, implement cache eviction policies, handle cache invalidation, and
monitor cache hit ratios.[13]
Use proper indexing, connection pooling with HikariCP, query optimization, batch processing, and database-specific
optimizations.[12][13]
Implement pagination, use Spring Batch for batch processing, stream processing, and asynchronous processing for
heavy operations.[13]
Use @Async annotation, configure thread pools, implement CompletableFuture, and handle asynchronous exceptions
properly.[26][13]
Configure heap size, garbage collector settings, enable flight recorder, and monitor memory usage patterns.[12][13]
Use profiling tools, monitor heap dumps, implement proper resource cleanup, and avoid common memory leak
patterns.[13]
Choose appropriate GC algorithm, tune heap sizes, monitor GC logs, and optimize for application-specific patterns.[12]
Use Spring Boot Actuator, APM tools, JVM monitoring, custom metrics, and performance testing tools.[13]
Use tools like JMeter, Gatling, or k6, create realistic test scenarios, monitor system behavior under load, and identify
bottlenecks.[13]
Testing Strategies
Unit tests, integration tests, slice tests (@WebMvcTest, @DataJpaTest), and end-to-end tests with different scopes and
configurations.[14]
Write tests first, implement minimal code to pass tests, refactor for better design, and maintain high test coverage.[14]
Use @SpringBootTest for integration tests, slice tests for specific layers, mock external dependencies, and implement
proper test data management.[14]
Use Spring Cloud Contract for consumer-driven contracts, implement contract verification, and ensure API
compatibility.[14]
Use [Link]() with timeouts, @Async testing with proper context, and verify asynchronous
behavior.[14]
Quality Assurance
Use static analysis tools, code coverage tools like JaCoCo, implement code review processes, and maintain coding
standards.[14]
Regular refactoring, code quality metrics, dependency updates, performance monitoring, and architectural
improvements.[13]
Automated test execution in CI/CD, parallel test execution, test environment management, and fast feedback loops.[14]
Use immutable objects, proper synchronization, thread-safe collections, stateless designs, and avoid shared mutable
state.[13]
Use JMH for microbenchmarks, establish baseline metrics, regular performance testing, and performance regression
detection.[13]
Use security test utilities, mock authentication, test authorization rules, and verify security headers and CSRF
protection.[14]
Introduce controlled failures, test system resilience, use tools like Chaos Monkey, and verify recovery mechanisms.[13]
Test migration scripts, verify schema changes, test rollback scenarios, and ensure data integrity during migrations.[14]
Use QuickCheck-style testing, generate random test inputs, verify properties instead of specific examples, and find edge
cases.[14]
Use WireMock for HTTP service mocking, implement contract tests, test error scenarios, and verify retry mechanisms.[14]
Use profiling tools, analyze thread dumps, monitor metrics, implement distributed tracing, and use APM tools.[13]
Custom health indicators, liveness and readiness probes, dependency health checks, and integration with monitoring
systems.[13]
Structured logging, correlation IDs, appropriate log levels, async logging, and centralized log management.[13]
Define SLIs/SLOs, implement custom metrics, set up alerts, use monitoring dashboards, and establish on-call
procedures.[13]
Use Actuator endpoints, analyze logs, thread dumps, heap dumps, and implement proper error handling and
reporting.[13]
23
Advanced Configuration
Create configuration classes with @Configuration, use conditional annotations, provide configuration properties, and
create [Link] file.[6]
Package related dependencies, create auto-configuration classes, provide configuration properties, and publish as
Maven/Gradle dependency.[6]
Use @ConditionalOnProperty annotations, external feature flag services, configuration-based toggles, and runtime
feature control.[6]
Create custom events extending ApplicationEvent, use @EventListener annotation, implement async event
processing, and handle event ordering.[27]
Implement BeanPostProcessor interface, register as Spring bean, modify beans during initialization, and handle
dependency injection.[11]
Use @EnableAspectJAutoProxy, create aspects with @Aspect, implement advice types (@Before, @After, @Around), and
define pointcuts.[11]
Define annotation with @interface, use meta-annotations, implement annotation processors, and integrate with Spring
framework.[28]
Use @EnableScheduling, @Scheduled annotation, configure task executors, implement dynamic scheduling, and handle
scheduler management.[6]
24
Configure WebSocket endpoints, implement message handling, use STOMP protocol, handle
connections/disconnections, and implement authentication.[11]
Use MultipartFile for uploads, implement file storage strategies, handle large files, implement download endpoints,
and ensure security.[9]
Singleton (beans), Factory (bean creation), Proxy (AOP), Template Method (JDBC/REST templates), Observer (event
handling), and Dependency Injection.[29]
Separate command and query models, use different data stores, implement event sourcing, handle eventual consistency,
and optimize read/write operations.[24]
Define domain core, implement ports and adapters, separate business logic from infrastructure, use dependency
inversion, and enable testability.[24]
Implement aggregates, entities, value objects, domain services, repositories, and maintain bounded contexts.[24]
Use Spring WebFlux, Reactor library, implement backpressure handling, non-blocking I/O, and functional programming
concepts.[25]
Use Spring Cloud Stream, implement message producers/consumers, handle message routing, implement error
handling, and ensure message reliability.[24]
Use Spring Mail, configure SMTP settings, create email templates, handle attachments, implement async email sending,
and error handling.[10]
Use RestTemplate, WebClient, implement retry mechanisms, handle authentication, implement circuit breakers, and
manage API rate limits.[9]
Use Spring Batch for large files, implement streaming, handle different formats, error handling, and progress
monitoring.[13]
Implement WebSocket connections, use message brokers, stream processing, handle backpressure, and implement
event-driven architecture.[24]
Use Spring Native, configure reflection hints, optimize for ahead-of-time compilation, handle native image limitations,
and measure startup improvements.[25]
Maintain two identical environments, route traffic gradually, implement health checks, automate rollback procedures,
and minimize downtime.[24]
Use Redis Cluster, implement cache partitioning, handle cache consistency, implement cache warming strategies, and
monitor cache performance.[13]
Database per tenant, shared database with tenant isolation, implement tenant resolution, secure tenant data, and handle
tenant-specific configurations.[20]
Implement shutdown hooks, complete in-flight requests, close resources properly, implement health check updates, and
configure shutdown timeouts.[13]
26
Use Spring Cloud Function, optimize for cold starts, handle stateless design, implement event-driven processing, and
manage resource constraints.[25]
Use Spring AI, integrate ML models, implement model serving, handle data preprocessing, implement A/B testing for
models, and monitor model performance.[25]
Implement MQTT integration, handle high-volume data ingestion, implement stream processing, use time-series
databases, and implement device management.[24]
Use Web3j library, implement smart contract interaction, handle cryptocurrency transactions, implement decentralized
identity, and ensure security.[25]
Native compilation, reactive programming, cloud-native development, microservices patterns, AI/ML integration, and
improved developer experience.[25]
⁂
27
Sources
1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]
6. [Link]
developers
7. [Link]
8. [Link]
9. [Link]
10. [Link]
11. [Link]
12. [Link]
13. [Link]
14. [Link]
15. [Link]
16. [Link]
17. [Link]
18. [Link]
19. [Link]
20. [Link]
21. [Link]
22. [Link]
23. [Link]
28
24. [Link]
25. [Link]
26. [Link]
27. [Link]
28. [Link]
29. [Link]
30. [Link]
31. [Link]
32. [Link]
33. [Link]
34. [Link]
35. [Link]
36. [Link]
37. [Link]
38. [Link]
39. [Link]
40. [Link]
41. [Link]
42. [Link]
43. [Link]
44. [Link]
45. [Link]
46. [Link]
47. [Link]
48. [Link]
29
49. [Link]
50. [Link]
51. [Link]
52. [Link]
53. [Link]
54. [Link]
55. [Link]
56. [Link]
57. [Link]
58. [Link]
59. [Link]
60. [Link]
61. [Link]
62. [Link]
63. [Link]
64. [Link]
65. [Link]
66. [Link]
67. [Link]
68. [Link]