Top 40 Spring Transactions Interview Questions | Must-Prepare before interview.

Top 40 Spring Transactions Interview Questions | Must-Prepare before interview Work through these 40 questions out loud. Open any question for the full model answer, the trap to avoid, and the follow-up a panel usually asks.

  1. What is the difference between JPA and Hibernate?

    JPA is the API contract; Hibernate is the engine under Spring Boot by default. You write @Entity per JPA spec; Hibernate handles SQL generation. Spring Data JpaRepository adds...

    Full answer

  2. What is CSRF and how does Spring Security handle it?

    CSRF tricks logged-in user's browser to POST to your site. Spring stores CsrfToken and validates on mutating requests. For SPA with session cookies, expose token via...

    Full answer

  3. Bean scopes in Spring — singleton vs prototype?

    Default singleton shares one instance — stateless services. Prototype for per-operation objects. Request/session scopes tie to web lifecycle with proxies. Prototype inside...

    Full answer

  4. 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...

    Full answer

  5. 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...

    Full answer

  6. 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,...

    Full answer

  7. 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:...

    Full answer

  8. 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...

    Full answer

  9. 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...

    Full answer

  10. 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...

    Full answer

  11. Explain @ConfigurationProperties vs @Value.

    @ConfigurationProperties(prefix = "app.payment") record PaymentProps(int timeout, String apiUrl) {} — validated, testable, grouped. Use @Value only for single feature flags....

    Full answer

  12. 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...

    Full answer

  13. 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...

    Full answer

  14. 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...

    Full answer

  15. 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...

    Full answer

  16. 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...

    Full answer

  17. 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....

    Full answer

  18. 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...

    Full answer

  19. 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...

    Full answer

  20. What is the difference between @Configuration and @Component?

    AppConfig @Configuration with @Bean DataSource — calling dataSource() from another @Bean method returns same instance. Mistake: @Component Config { @Bean Service s() { return...

    Full answer

  21. BeanFactoryPostProcessor vs BeanPostProcessor — explain both.

    BFPP: replace ${placeholder} in definitions via PropertySourcesPlaceholderConfigurer. BPP: @Autowired injection, @PostConstruct detection, AOP proxy wrapping. Custom BPP can...

    Full answer

  22. @Primary vs @Qualifier — when to use each?

    Two DataSource beans: @Primary mainDataSource for JPA, @Qualifier("analytics") for reporting repo. Prefer @Qualifier when both are equally valid — @Primary for sensible...

    Full answer

  23. ApplicationContext vs BeanFactory — what extra does ApplicationContext provide?

    BeanFactory sufficient for minimal DI tests. ApplicationContext adds @EventListener infrastructure, @MessageSource for i18n, Environment integration. Spring Boot creates...

    Full answer

  24. How does @Transactional work?

    Spring creates a proxy around @Transactional beans. Calling createOrder() from another bean starts a transaction on the thread-bound EntityManager; commit on success, rollback...

    Full answer

  25. How do Spring application events work with @EventListener?

    OrderService publishes OrderCreatedEvent after save. EmailListener @EventListener sends confirmation. @TransactionalEventListener(AFTER_COMMIT) prevents email on rolled-back...

    Full answer

  26. Saga pattern — choreography vs orchestration?

    Order saga: reserve inventory → charge payment → ship. Failure at payment triggers release inventory compensation. Orchestration clearer for complex flows with visibility....

    Full answer

  27. Explain the transactional outbox pattern.

    OrderService @Transactional saves Order and OutboxEvent(type=ORDER_CREATED, payload=json). OutboxProcessor @Scheduled polls FOR UPDATE SKIP LOCKED, sends to Kafka, updates...

    Full answer

  28. Load shedding and backpressure in microservices?

    Tomcat max queue + reject policy returns 503 with Retry-After. WebClient timeout + circuit breaker stops calling slow dependency. Kafka consumer pause partitions when...

    Full answer

  29. What happens if @Transactional fails midway? How do you verify rollback?

    Default: runtime exception marks rollback-only; transaction commits nothing on exit. ```java @Transactional(rollbackFor = Exception.class) public void placeOrder(Order o) {...

    Full answer

  30. 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...

    Full answer

  31. How do you stop a LangChain4j agent loop from running forever, and who owns the workflow?

    I set maxSequentialToolsInvocations to a small number — three or four for triage. Writes take an idempotency key. Approve is not a @Tool. Automating a business process with AI...

    Full answer

  32. 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...

    Full answer

  33. Describe the Spring Bean lifecycle.

    Container instantiates the bean, injects dependencies, runs BeanPostProcessors, then @PostConstruct or InitializingBean. Singleton lives for context lifetime; prototype creates...

    Full answer

  34. What is the N+1 query problem and how do you fix it?

    Loading 100 orders then accessing each order's items triggers 101 queries. Fix with JOIN FETCH in JPQL, @EntityGraph on repository method, or a DTO query selecting only...

    Full answer

  35. What is dependency injection and why does Spring use it?

    DI supplies collaborators from outside the class — typically via constructor. Problem solved: tight coupling to concrete classes, hard unit tests, scattered object...

    Full answer

  36. @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...

    Full answer

  37. Explain JWT authentication flow in Spring Security.

    POST /login with credentials → auth provider validates → issue JWT with exp/sub/roles. Subsequent requests include Bearer token. JwtAuthenticationFilter runs before...

    Full answer

  38. 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....

    Full answer

  39. How do you handle exceptions globally in Spring?

    Create @RestControllerAdvice with @ExceptionHandler(MethodArgumentNotValidException.class) returning 400 + field map, NotFoundException → 404, generic Exception → 500 without...

    Full answer

  40. Difference between @Component, @Service, @Repository?

    All register as singleton beans via component scan. Choose by layer for readability: @Repository on DAOs (plus SQLException translation), @Service on business logic, @Component...

    Full answer

Spring Transactions Interview Questions and Answers · Top 50 Spring Transactions Interview Questions and Answers (2026 Edition) · Spring Transactions Interview Questions Every Fresher Must Know · Spring Transactions Interview Questions for 2–3 Years

All interview question lists · Interview guides · Home · Support the platform