Spring Boot, Spring Data JPA & Cloud Microservices Master Interview Bank
Spring Boot auto-configuration, IoC/DI, Spring Data JPA & Hibernate caching, Spring Security, Kafka integration, Resilience4j, and Microservices.
Curriculum Roadmap & Learning Path
3 StagesPart 1: Spring Core, Auto-Configuration & Architecture (1 - 10)
10 QuestionsWhat is Inversion of Control (IoC) and Dependency Injection (DI) in Spring?
Inversion of Control (IoC): Instead of a class instantiating its dependencies with new OrderRepository(), control of object lifecycle and • Dependency Injection (DI): The mechanism where the IoC container injects dependent objects into a bean at runtime.
What are Spring Bean Scopes?
singleton (Default): Exactly one instance per Spring IoC container • prototype: A new instance is created every time the bean is requested from the container • request: One instance per HTTP request lifecycle (Web-aware) • session: One instance per HTTP session lifecycle (Web-aware).
Walk through the Spring Bean Lifecycle.
Instantiation: JVM creates bean instance via constructor • Populate Properties: Dependencies injected via setters/constructors • Aware Interfaces: Spring injects container references (BeanNameAware, ApplicationContextAware) • BeanPostProcessor (Before Init): postProcessBeforeInitialization called.
How does Spring Boot Auto-Configuration (`@EnableAutoConfiguration`) work?
Spring Boot scans dependencies on the classpath and automatically registers pre-configured beans unless you define your own: @SpringBootApplication meta-annotates @EnableAutoConfiguration.
What is the difference between `@Component`, `@Service`, `@Repository`, and `@Controller`?
All are Spring stereotype annotations that inherit from @Component for classpath scanning, but provide semantic clarity: @Component: Generic Spring-managed component • @Service: Marks business logic layer • @Repository: Marks data access layer • @Controller / @RestController: Marks HTTP web entrypoints.
How does Spring AOP work, and how does `@Transactional` leverage dynamic proxies?
Spring AOP (Aspect-Oriented Programming) intercepts method execution using Dynamic Proxies (CGLIB class-based or JDK dynamic interface-based). When a class has @Transactional: Spring generates a proxy wrapper around the target bean • The caller invokes the proxy's method.
How do you handle Global Exceptions in Spring Boot REST APIs?
Use @RestControllerAdvice and @ExceptionHandler to intercept exceptions across all controllers and return standardized RFC-7807 ProblemDetail or structured error payloads.
What is Spring Boot Actuator, and how do you configure it in production?
Spring Boot Actuator provides production-ready monitoring endpoints (/actuator/health, /actuator/metrics, /actuator/prometheus).: In production, never expose all endpoints publicly • Expose only health and prometheus metrics to internal monitoring tools • Protect sensitive endpoints with Spring Security.
How do Spring Profiles work, and how do you separate environments?
Spring Profiles segregate application configuration for different target environments (dev, staging, prod): Uses naming convention: application-dev.yml, application-prod.yml • Activated via system environment variable: SPRINGPROFILESACTIVE=prod • Beans can be conditionally loaded using @Profile("prod").
How do you implement asynchronous execution with `@Async` in Spring?
Annotating a method with @Async runs it in a separate background thread from a dedicated thread pool: Must enable with @EnableAsync • Must configure a custom ThreadPoolTaskExecutor (avoid default SimpleAsyncTaskExecutor which creates a new unbounded thread per task).
Part 2: Persistence, Transactions & Security (11 - 24)
14 QuestionsWhat is the difference between `@RequestParam`, `@PathVariable`, and `@RequestBody`?
@PathVariable: Extracts values from URI template path (e.g., /orders/{id} -> @PathVariable UUID id) • @RequestParam: Extracts query parameters (e.g., /orders?status=active&page=2 -> @RequestParam String status) • @RequestBody: Deserializes JSON HTTP payload into a Java POJO/Record using Jackson.
What is `@ConfigurationProperties` and how is it superior to `@Value`?
@Value: Weakly typed, error-prone SpEL string injections (e.g. @Value("${app.timeout}") private int timeout;) • @ConfigurationProperties: Strongly typed, supports hierarchical YAML binding, validation via @Validated, and IDE autocomplete.
What are Spring Events and how do you implement loose coupling?
Spring Events allow components to communicate asynchronously without direct dependencies: Publisher calls ApplicationEventPublisher.publishEvent(new OrderCreatedEvent(order)) • Consumer listens via @EventListener or @TransactionalEventListener(phase = TransactionPhase.AFTERCOMMIT).
How do you prevent and resolve circular dependencies in Spring Boot?
A circular dependency occurs when Bean A requires Bean B, and Bean B requires Bean A: Best Fix (Architectural): Refactor code to extract shared logic into a third service (Bean C) • Event-driven: Replace direct call with Spring ApplicationEvent.
How do you implement graceful shutdown in Spring Boot on Kubernetes?
When Kubernetes terminates a pod, it sends a SIGTERM signal: Configure server.shutdown: graceful • Set timeout spring.lifecycle.timeout-per-shutdown-phase: 30s • Spring stops accepting new HTTP traffic and allows in-flight requests and background jobs up to 30 seconds to finish before terminating.
What is the N+1 Query Problem in JPA/Hibernate, and how do you solve it?
Problem: Fetching 100 Order records issues 1 SQL query • Solutions • JOIN FETCH in JPQL: SELECT o FROM Order o JOIN FETCH o.customer fetches parent and children in 1 query • EntityGraph: @EntityGraph(attributePaths = {"customer"}).
What are Hibernate First-Level and Second-Level Caches?
First-Level Cache (L1): Bound to the EntityManager / Session lifecycle • Second-Level Cache (L2): Shared across all sessions and transactions at the EntityManagerFactory level (e.g. Ehcache, Redis, Hazelcast).
What are JPA Cascade Types and Orphan Removal?
cascade = CascadeType.ALL: Propagates entity operations (PERSIST, MERGE, REMOVE) from parent to children (e.g. saving Order automatically saves • orphanRemoval = true: If a child entity is removed from the parent's collection (order.getItems().remove(item)), JPA automatically executes an.
How does `@Transactional` propagation work (`REQUIRED` vs `REQUIRES_NEW`)?
REQUIRED (Default): Joins the existing transaction if one exists; creates a new one if none exists • REQUIRES_NEW: Suspends the existing outer transaction and always starts an independent, new physical transaction.
How do Optimistic and Pessimistic Locking work in JPA?
Optimistic Locking: Assumes low conflict • Pessimistic Locking: Assumes high conflict.
What is the difference between `findById()` and `getReferenceById()` in Spring Data JPA?
findById(): Immediately issues an SQL SELECT to fetch the entity and initialize all eager properties • getReferenceById(): Returns a lazy Hibernate proxy without hitting the database.
What is Dirty Checking in Hibernate?
When an entity is loaded inside an @Transactional method, Hibernate stores a snapshot of its state in the L1 cache. When the transaction commits, Hibernate compares the entity's current state with the initial snapshot. If any fields changed, Hibernate automatically generates and executes the SQL UPDATE statement.
How does HikariCP connection pooling work and how do you size it?
HikariCP is Spring Boot's default ultra-fast, zero-overhead JDBC connection pool: Formula: Pool Size = 2 * (CPU Cores) + Effective Spindle Count • On a 4-core database server with fast SSDs: A pool of 10–20 connections outperforms a pool of 200 connections, because excessive connections.
What is Flyway or Liquibase and why use them over `ddl-auto=update`?
Never use hibernate.ddl-auto=update in production: it cannot rename columns, cannot handle complex data transformations, and can inadvertently • Flyway: Executes versioned SQL migration scripts (V1init.sql, V2addstatus.sql) sequentially, tracking executed migrations in a.
Part 3: Microservices, Distributed Systems & Observability (25 - 35)
26 QuestionsWhat is the difference between Embedded IDs and IdClass in JPA?
Both represent composite primary keys in JPA: @EmbeddedId: Defines a separate @Embeddable class instance inside the entity (@EmbeddedId private OrderItemId id;) • @IdClass: Annotates the entity with @IdClass(OrderItemId.class) and duplicates the primary key fields directly in the entity class.
Walk through the Spring Security 6 filter chain architecture.
Spring Security intercepts HTTP requests using SecurityFilterChain (a DelegatingFilterProxy managing a chain of filters): CorsFilter & CsrfFilter validate cross-origin headers and tokens • JwtAuthenticationFilter extracts Bearer from the Authorization header.
How do you implement Stateless JWT Authentication in Spring Boot 3?
User logs in with username/password via /api/auth/login • Server validates credentials and signs a JWT (containing user ID, roles, expiration) using HMAC-SHA256 or RSA • Client stores token and sends it in Authorization: Bearer on subsequent requests.
How does Method-Level Security (`@PreAuthorize`) work?
@PreAuthorize uses Spring Expression Language (SpEL) to evaluate permissions before a method executes: @PreAuthorize("hasRole('ADMIN')") • @PreAuthorize("#userId == authentication.principal.id or hasRole('MANAGER')").
What is CSRF and why is it disabled in stateless REST APIs?
CSRF (Cross-Site Request Forgery) tricks a browser into sending authenticated session cookies to a malicious site. In stateless REST APIs using JWT stored in memory or request headers (not ambient browser cookies), CSRF attacks are fundamentally impossible, so csrf.disable() is safe and standard practice.
How does Password Hashing work with BCrypt in Spring Security?
Never store plaintext or plain MD5/SHA256 hashes: BCryptPasswordEncoder uses a slow, adaptive hashing algorithm that automatically generates a random cryptographic salt and incorporates a configurable work factor (cost parameter, default 10 = 1024 iterations). It is resistant to rainbow table and brute-force GPU attacks.
What is the difference between Authentication and Authorization in Spring Security?
Authentication ("Who are you?"): Verified via AuthenticationManager -> returns Principal • Authorization ("What are you allowed to do?"): Evaluated by AccessDecisionManager / AuthorizationManager -> checks GrantedAuthority roles.
How does OAuth 2.0 / OpenID Connect work with Spring Security?
Spring Security supports OAuth2 Resource Server and Client: Uses oauth2ResourceServer(oauth2 -> oauth2.jwt()) • Automatically fetches and caches the Identity Provider's public keys from the JWKS URI (.well-known/jwks.json) to verify JWT tokens without.
What is the Circuit Breaker Pattern, and how do you implement it with Resilience4j in Spring Boot?
Prevents cascading failures when a downstream service is down: CLOSED: Traffic flows normally • OPEN: Failure rate exceeds threshold (e.g. 50%); requests fail fast immediately without calling the broken service • HALF-OPEN: After a wait duration, test requests are sent to check if the downstream service recovered.
How does Apache Kafka integrate with Spring Boot (`@KafkaListener`)?
Spring for Apache Kafka provides KafkaTemplate for publishing and @KafkaListener for consuming messages: Producers send structured JSON/Avro events to a topic partition • Consumers belong to a ConsumerGroup • Dead Letter Topics (DLT) handle poisoned pills using DefaultErrorHandler.
What is the Saga Pattern in Microservices (Choreography vs Orchestration)?
Manages distributed transactions across microservices without two-phase commit (2PC): Choreography: Each service publishes an event (e.g., OrderCreated -> PaymentProcessed -> InventoryReserved), and services react.
Spring Boot 3 Virtual Threads Integration: `spring.threads.virtual.enabled=true`.
In Spring Boot 3.2+, enabling Java 21 Virtual Threads requires a single configuration property: spring.threads.virtual.enabled=true: What it Does: Replaces Tomcat's platform thread pool with an unbounded Virtual Thread executor.
`@Transactional` Internals: The Self-Invocation Anti-Pattern.
Spring manages transactions using AOP dynamic proxies: The Self-Invocation Trap: If MethodA() calls this.MethodB() within the same class, and MethodB() is annotated with @Transactional, the • Rollback Rule: By default, Spring only rolls back for unchecked exceptions (RuntimeException, Error).
Spring Bean Lifecycle: Creation to Destruction.
Instantiation: JVM instantiates the bean class via reflection or factory method • Populate Properties: Injects dependencies (@Autowired, constructor args) • BeanNameAware / BeanFactoryAware: Injects Spring internal context references • BeanPostProcessor::postProcessBeforeInitialization: Intercepts bean before custom init.
Prototype Beans Inside Singleton Beans: The Scoped Proxy Solution.
A @Scope("prototype") bean is supposed to create a new instance on every request. However, if injected into a default @Scope("singleton") service: The singleton is only created once at startup, so the prototype bean is only injected once, acting like a singleton!
Spring Security 6 Architecture: Stateless SecurityFilterChain.
Spring Security 6 deprecated WebSecurityConfigurerAdapter in favor of component-based SecurityFilterChain beans: Incoming HTTP requests pass through a chain of filters (SecurityContextPersistenceFilter, JwtAuthenticationFilter • Stateless REST APIs disable CSRF and session management, setting SessionCreationPolicy.STATELESS.
Spring Boot Actuator and Micrometer Observability.
Actuator exposes production-ready operational metrics: Health check endpoints (/actuator/health) reporting Kubernetes liveness and readiness probe states • Micrometer Tracing: Integrates with OpenTelemetry, Jaeger, and Zipkin to propagate traceId and spanId across microservice boundaries in HTTP.
Spring Data JPA: Resolving the N+1 Query Problem.
The N+1 Problem occurs when loading 100 parent records executes 1 query for the parents plus 100 separate sub-queries to fetch child relationships: Solution 1: Join Fetch in JPQL • Solution 2: @EntityGraph • Solution 3: DTO Projection: Select only the exact columns needed into a Java Record.
Spring Cache with Redis: `@Cacheable`, `@CachePut`, and `@CacheEvict`.
Spring Cache provides declarative abstraction over caching layers: @Cacheable(value = "users", key = "#id"): Returns cached value if present; otherwise runs method and stores result • @CachePut(value = "users", key = "#user.id"): Always executes method and updates the cache.
Spring Cloud Gateway vs Zuul.
Netflix Zuul 1: Legacy blocking I/O model based on Java Servlets • Spring Cloud Gateway: Built on non-blocking Netty and Project Reactor • Supports route predicates (matching path, host, headers) and filters (JWT auth validation, request rewriting, rate limiting via Redis token bucket).
Resilience4j: Circuit Breakers and Bulkheads in Spring Boot.
Resilience4j protects services from cascading downstream failures: Circuit Breaker (@CircuitBreaker(name = "payment", fallbackMethod = "fallback")): If error rate exceeds 50%, the circuit transitions to OPEN.
Spring Boot 3 AOT and GraalVM Native Compilation.
Spring Boot 3 natively supports Ahead-Of-Time (AOT) compilation with GraalVM: Analyzes reflection, proxies, and resource loading at build time • Compiles the application into a standalone Linux/Windows executable with under 50ms startup times and < 50\text{MB} memory footprint, ideal for.
Asynchronous Execution with `@Async` and Context Propagation.
Annotating a method with @Async executes it on a background thread pool: SecurityContext Loss: Thread-local state (SecurityContextHolder, MDC correlation IDs) does not automatically transfer to the async thread!
Spring Kafka: Idempotent Listeners and Dead Letter Queues (DLQ).
Dead Letter Topic (DLT): When message processing fails after maximum retries (e.g. 3 attempts), Spring Kafka's DeadLetterPublishingRecoverer • Idempotency: Store consumed Kafka offsets or business idempotency keys (order_id) in Redis/DB to prevent duplicate executions from message replays.
Transactional Application Events: `@TransactionalEventListener`.
Standard Spring @EventListener executes immediately when the event is published, even if the database transaction later rolls back!: @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT): Guarantees the listener executes only after the database transaction has.
Database Migrations: Flyway vs Liquibase in Enterprise CI/CD.
Automates version-controlled database schema changes on application startup: Flyway: Uses plain SQL migration scripts (V1init.sql, V2add_index.sql) • Liquibase: Uses XML, YAML, or SQL change sets.