Spring Boot Interview Master Guide

Complete coding edition • Concept-wise tabs • Interview Q&A • Production • Microservices • Concurrency • Java 8+

1. Spring Boot Fundamentals

QuestionInterview Answer
What is Spring Boot?Spring Boot simplifies Spring application development through auto-configuration, starter dependencies, embedded servers, externalized configuration and production-ready features.
Why Spring Boot over traditional Spring?Less configuration, embedded server, starter dependencies, auto-configuration and easier production deployment.
Main Spring Boot features?Auto-configuration, starters, embedded servers, Actuator, externalized configuration and profiles.
What is auto-configuration?Spring Boot conditionally configures beans based on classpath dependencies, application configuration and existing beans.
What are starters?Curated dependency bundles such as spring-boot-starter-web, JPA and Security.
What is an embedded server?The application can run with an embedded Tomcat, Jetty or other supported server and be started using java -jar.
What is Actuator?A production-ready module exposing health, metrics, mappings, environment and other operational information.
What is externalized configuration?Configuration is kept outside business code using YAML/properties, environment variables, command-line arguments, config servers and secret stores.
Interview tip: Explain not only what Spring Boot does, but why it reduces boilerplate and how it behaves at runtime.

2. SpringApplication.run() – Internal Flow

Question: What happens internally when SpringApplication.run(Application.class, args) executes?

main()→SpringApplication.run()→ Create SpringApplication→Prepare Environment→ Create ApplicationContext→Apply Initializers→ Refresh Context→Start Web Server→ Run Runners→ApplicationReadyEvent
main()
  |
  v
SpringApplication.run()
  |
  +-- Create/configure SpringApplication
  +-- Prepare Environment
  +-- Load application.yml / properties
  +-- Create ApplicationContext
  +-- Apply Context Initializers
  +-- Refresh ApplicationContext
  |     +-- Register beans
  |     +-- Component scanning
  |     +-- Auto-configuration
  |     +-- Dependency injection
  |     +-- Start embedded server
  +-- Execute ApplicationRunner / CommandLineRunner
  +-- Publish ApplicationReadyEvent
  |
  v
Application ready

Strong interview answer: SpringApplication.run() bootstraps the application. It prepares the environment, creates and refreshes the application context, applies auto-configuration, registers and initializes beans, starts the embedded web server for web applications, executes startup runners and finally signals that the application is ready.

EventMeaning
ApplicationStartingEventStartup begins.
ApplicationEnvironmentPreparedEventEnvironment has been prepared.
ApplicationPreparedEventContext prepared before refresh.
ContextRefreshedEventApplication context refreshed.
ServletWebServerInitializedEventWeb server initialized.
ApplicationStartedEventApplication has started.
ApplicationReadyEventApplication is ready to serve requests.
ApplicationFailedEventStartup failed.

3. Core Spring Boot Annotations & Component Stereotypes

AnnotationPurpose
@SpringBootApplicationCombines Boot configuration, auto-configuration and component scanning.
@ConfigurationDefines configuration class and usually contains @Bean methods.
@EnableAutoConfigurationEnables conditional Boot auto-configuration.
@ComponentScanScans packages for Spring components.
@BeanExplicitly registers a method return object as a Spring bean.
@ComponentGeneric Spring-managed component.
@ServiceBusiness/service-layer stereotype.
@RepositoryPersistence/DAO-layer stereotype.
@ControllerMVC controller.
@RestControllerREST controller with response-body semantics.
@AutowiredDependency injection.
@QualifierSelects a particular bean when multiple candidates exist.
@PrimaryGives a bean preference among candidates.
@ValueInjects a configuration value.
@ConfigurationPropertiesStrongly typed grouped configuration binding.
@ProfileActivates beans for selected environments.

Component hierarchy

@Component
   ├── @Service
   ├── @Repository
   └── @Controller
          └── @RestController
Important: @Service and @Repository are stereotype annotations. They are discovered because component scanning finds them.

4. IoC, Dependency Injection and Bean Management

QuestionKey Point
What is IoC?Spring controls object creation and dependency management instead of application code doing it manually.
What is DI?Dependencies are supplied to a class rather than created by the class.
What is a Spring Bean?An object managed by the Spring IoC container.
Default scope?Singleton per Spring application context.
Singleton bean = Java Singleton?No. Spring singleton is scoped to one application context.
Constructor vs field injection?Constructor injection makes required dependencies explicit, supports final fields and improves testability.
Multiple beans of same type?Use @Qualifier or @Primary.
@Service
public class OrderService {
    private final PaymentService paymentService;

    public OrderService(PaymentService paymentService) {
        this.paymentService = paymentService;
    }
}

@Bean vs @Component

@Component@Bean
Put on class.Put on method.
Discovered through scanning.Explicit registration.
Good for application classes.Good for third-party/custom objects.

5. Mutable vs Immutable State in Spring Boot

MutableImmutable
State can change after construction.State cannot change after construction.
May need synchronization.Naturally safer for sharing.
Example: ArrayList.Example: String.
Useful when state must change.Preferred for shared value/configuration objects.

How to accidentally create unsafe mutable state

@Service
public class CounterService {
    private int count = 0;

    public void increment() {
        count++;
    }
}
Why is this risky? Spring beans are singleton by default. Multiple requests can access the same instance concurrently, so a mutable field can become shared state and produce race conditions.

Safer alternatives

ApproachWhen useful
Immutable objectPreferred whenever possible.
AtomicInteger / AtomicLongSimple atomic counters/state.
ConcurrentHashMapConcurrent map state.
synchronized / locksProtecting critical sections.
DatabaseDurable shared state.
RedisDistributed shared state/cache.
private final AtomicInteger counter = new AtomicInteger();

public int increment() {
    return counter.incrementAndGet();
}

Creating an immutable class

public final class Employee {
    private final String name;
    private final int age;

    public Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() { return name; }
    public int getAge() { return age; }
}

Rules: final class, private final fields, initialize in constructor, no setters, and defensive copies when fields contain mutable objects.

6. Configuration, Profiles & Spring Cloud Config

Profiles

application.yml
application-dev.yml
application-qa.yml
application-uat.yml
application-prod.yml

Activate a profile using deployment configuration rather than hard-coding production settings:

SPRING_PROFILES_ACTIVE=prod

# or
java -jar app.jar --spring.profiles.active=prod

@Value vs @ConfigurationProperties

@Value@ConfigurationProperties
Good for individual properties.Good for grouped configuration.
Convenient for small values.Strongly typed and maintainable.
Can use SpEL.Better for structured configuration.
payment:
  url: https://payment-service
  timeout: 5000
  retry: 3
@ConfigurationProperties(prefix = "payment")
public class PaymentProperties {
    private String url;
    private int timeout;
    private int retry;
}

What is Spring Cloud Config?

Spring Cloud Config provides centralized external configuration for distributed applications.

                 Git Repository
                       |
                       v
                 Config Server
                  /     |     \
                 v      v      v
             Order   Payment   User
             Service Service  Service
ProblemConfig Server benefit
Configuration duplicated across servicesCentral repository
Different environmentsProfile-based configuration
Many microservicesCentralized configuration management
Configuration changesManage externally without rebuilding application artifacts

How do you manage production configuration?

TypeRecommended approach
Application defaultsapplication.yml
Environment-specific valuesExternal configuration / Config Server
DB passwordsSecrets manager / Kubernetes Secret
API keysSecret management system
Feature flagsFeature-flag system or external config
Never commit production secrets such as database passwords or API keys into source control.

7. REST APIs, Validation & Exception Handling

AnnotationPurpose
@GetMappingHTTP GET
@PostMappingHTTP POST
@PutMappingHTTP PUT
@PatchMappingHTTP PATCH
@DeleteMappingHTTP DELETE
@PathVariableReads URI path variable
@RequestParamReads query parameter
@RequestBodyReads request body
ResponseEntityControls HTTP status, headers and response body

Global exception handling

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<String> handleNotFound(
            ResourceNotFoundException ex) {

        return ResponseEntity
                .status(HttpStatus.NOT_FOUND)
                .body(ex.getMessage());
    }
}
ApproachScope
try-catchLocal operation
@ExceptionHandlerController exception handling
@ControllerAdviceShared controller handling
@RestControllerAdviceREST APIs
Custom exceptionBusiness-specific failures

Validation

public class UserRequest {
    @NotBlank
    private String name;

    @Email
    private String email;
}

@PostMapping
public ResponseEntity<?> create(
        @Valid @RequestBody UserRequest request) {
    return ResponseEntity.ok().build();
}

Controller vs RestController

@Controller@RestController
Traditional MVC controller.REST controller.
Can return views.Return values are response-body oriented.
May require @ResponseBody.Includes response-body semantics.

8. JPA, Transactions & Database

@Transactional

@Transactional
public void transferMoney(...) {
    debit();
    credit();
}
QuestionKey answer
What is @Transactional?Defines a transactional boundary.
Where should it normally be used?Service/business layer.
Runtime exception rollback?Typically rolls back by default.
Checked exception?Rollback behavior may require explicit configuration.
Private transactional method?Proxy-based transaction interception does not work through private methods.
Self-invocation?Calling another transactional method via this bypasses the Spring proxy.

Important database interview topics

  • JPA vs Hibernate
  • Lazy vs eager loading
  • N+1 query problem
  • Pagination
  • Connection pooling
  • Optimistic vs pessimistic locking
  • Transaction isolation
  • Database indexes
  • Deadlocks
  • Read/write transaction boundaries

9. Actuator, Metrics & Separate Management Port

Separate port

server.port=8080
management.server.port=8081
Application APIs
http://host:8080

Management / Actuator
http://host:8081

Example endpoints:

/actuator/health
/actuator/metrics
/actuator/prometheus

Expose only the endpoints required by your environment:

management.endpoints.web.exposure.include=health,info,metrics,prometheus
management.server.port=8081
Why separate the management port? It allows different network controls and security policies for operational endpoints and application traffic.

Actuator endpoints

EndpointPurpose
/actuator/healthHealth status
/actuator/infoApplication information
/actuator/metricsMetrics
/actuator/prometheusPrometheus format metrics
/actuator/loggersLogger configuration
/actuator/envEnvironment information
/actuator/beansSpring bean information
/actuator/mappingsRequest mappings

Observability

SignalAnswers
LogsWhat happened?
MetricsHow much/how often?
TracesWhere did the request travel?
HealthCan the service operate?
Spring Boot
    |
    +-- Actuator
    +-- Micrometer
          |
      Prometheus
          |
       Grafana

Liveness vs Readiness

LivenessReadiness
Is the application alive?Can it receive traffic?
Failure may trigger restart.Failure should remove instance from traffic.

10. CommandLineRunner, ApplicationRunner & Startup Hooks

FeatureCommandLineRunnerApplicationRunner
ArgumentsString...ApplicationArguments
Startup taskYesYes
Structured argument parsingManualBuilt in
@Component
public class StartupRunner implements CommandLineRunner {
    @Override
    public void run(String... args) {
        System.out.println("Application started");
    }
}
MechanismTypical timing/use
@PostConstructBean initialization.
CommandLineRunnerStartup callback with raw command-line args.
ApplicationRunnerStartup callback with parsed arguments.
ApplicationReadyEventApplication is ready.

11. Caching

@Cacheable("products")
public Product getProduct(Long id) {
    return repository.findById(id).orElseThrow();
}
AnnotationPurpose
@EnableCachingEnables caching.
@CacheableCaches method result.
@CachePutUpdates cache while executing method.
@CacheEvictRemoves cache entry.
@CachingCombines cache operations.

For distributed applications, Redis is a common cache implementation.

12. Spring Security – Frequently Asked

QuestionAnswer focus
Authentication vs authorization?Authentication identifies the caller; authorization determines access.
JWT?Stateless token-based authentication commonly used in REST systems.
OAuth2?Authorization framework and ecosystem.
CORS?Controls permitted cross-origin browser requests.
CSRF?Protection against cross-site request forgery; strategy depends on application type.
Password storage?Use a strong password hash such as BCrypt or Argon2; never plaintext.

13. Concurrency, Atomic & Thread Safety

Question: Are Spring singleton beans thread-safe?

Answer: No. Spring manages lifecycle and scope; it does not automatically make mutable fields thread-safe.

ToolUse case
AtomicInteger / AtomicLongSimple lock-free atomic state updates.
ConcurrentHashMapConcurrent key/value state.
synchronizedProtect critical sections.
ReentrantLockAdvanced explicit locking.
Immutable objectsSafest approach for shared values.

Common concurrency questions

  • Why is count++ not atomic?
  • Atomic vs synchronized?
  • What is a race condition?
  • What is deadlock?
  • What is ConcurrentHashMap?
  • What is volatile?
  • What is happens-before?
  • How do singleton Spring beans behave under concurrent requests?

14. CompletableFuture

CompletableFuture
   |
   +-- supplyAsync()
   +-- thenApply()
   +-- thenCompose()
   +-- thenCombine()
   +-- allOf()
   +-- exceptionally()
   +-- handle()
MethodPurpose
supplyAsync()Start asynchronous computation returning a result.
thenApply()Transform a completed result.
thenCompose()Chain dependent asynchronous operations.
thenCombine()Combine independent futures.
allOf()Wait for multiple futures.
exceptionally()Provide exception recovery.
handle()Process result or exception.
Senior-level point: Discuss the executor used for asynchronous work, timeouts, cancellation, exception propagation and avoiding unbounded concurrency.

15. Virtual Threads

Virtual threads are lightweight JVM-managed threads designed for high-concurrency workloads, especially applications with many blocking operations.

Platform Threads
Request → Platform Thread
Request → Platform Thread
Request → Platform Thread

Virtual Threads
Request → Virtual Thread
Request → Virtual Thread
Request → Virtual Thread
        ↓
JVM schedules work onto carrier threads
QuestionAnswer
Do virtual threads make CPU-bound work faster?No. They primarily improve scalability for high-concurrency blocking workloads.
Can Spring Boot use virtual threads?Modern Spring Boot versions provide support when running on a suitable modern JDK.
Do they eliminate all concurrency problems?No. Shared mutable state, synchronization, DB limits and downstream bottlenecks still matter.
What should be checked?Thread pinning, blocking behavior, connection pools and resource limits.

16. Microservices & Spring Boot

QuestionKey answer
How do microservices communicate?Synchronous REST/gRPC or asynchronous messaging such as Kafka/JMS/MQ.
Can Spring Boot integrate with Kafka?Yes, commonly through Spring for Apache Kafka.
Can Spring Boot integrate with Apache Camel?Yes. Camel can be used for routing, mediation and integration patterns alongside Spring Boot.
What is service discovery?Mechanism for locating service instances dynamically.
What is API Gateway?Central entry point for routing, security, rate limiting and cross-cutting concerns.
What is centralized configuration?Externalized configuration managed centrally for multiple services.
How handle distributed transactions?Prefer patterns such as Saga and transactional messaging where appropriate.
What is idempotency?Repeated processing of the same request produces the intended single logical effect.

Resilience patterns

PatternPurpose
TimeoutPrevent indefinite waiting.
RetryRecover from transient failures.
Circuit BreakerStop repeated calls to an unhealthy dependency.
BulkheadIsolate resources to limit blast radius.
Rate LimiterControl request volume.
FallbackReturn a graceful alternative when dependency fails.
Client
  |
  v
Service A -----> Service B
                    |
                    X Failure
                    |
              Timeout / Retry
                    |
              Circuit Breaker
                    |
                Fallback

17. Logging & Distributed Tracing

TopicInterview point
Log levelsTRACE, DEBUG, INFO, WARN, ERROR.
Structured loggingPrefer machine-readable fields for centralized log analysis.
Correlation IDIdentifies a request across service boundaries.
MDCStores contextual data associated with logging operations.
Distributed tracingFollows a request across multiple services.
Client
  ↓  Correlation / Trace ID
Service A
  ↓
Service B
  ↓
Service C
Never log passwords, tokens, secrets or sensitive personal information.

18. Testing

TestPurpose
@SpringBootTestLoads the Spring application context for broader integration testing.
@WebMvcTestTests MVC/controller slice.
@DataJpaTestTests JPA/repository slice.
MockitoMock dependencies in unit tests.
MockMvcTest MVC HTTP interactions without starting a real external server.

Unit vs Integration

Unit TestIntegration Test
Tests a small unit in isolation.Tests multiple components together.
Fast.Usually slower.
Mocks dependencies heavily.Uses real Spring context/infrastructure as needed.

19. Java 8 Features Frequently Asked with Spring Boot

FeatureInterview focusSmall example
LambdaFunctional programminglist.forEach(x -> System.out.println(x));
Functional InterfaceSingle abstract methodPredicate<String> p = s -> s.length() > 3;
Stream APIDeclarative collection processinglist.stream().filter(x -> x > 10).toList()
OptionalExplicit absence/presenceOptional.ofNullable(value)
Default methodsEvolve interfacesdefault void log(){}
Method referenceShorter lambdaSystem.out::println
New Date/Time APIImmutable date/time typesLocalDate.now()
CompletableFutureAsync computationCompletableFuture.supplyAsync(...)

Common functional interfaces

InterfaceInputOutputTypical use
Predicate<T>TbooleanFiltering
Function<T,R>TRTransformation
Consumer<T>TvoidSide effect
Supplier<T>noneTLazy/provided value

Stream example

List<String> names = List.of("Ravi", "John", "Robert");

List<String> result = names.stream()
        .filter(name -> name.length() > 4)
        .map(String::toUpperCase)
        .toList();

20. Top 30 Priority Interview Questions

PriorityQuestion
⭐⭐⭐⭐⭐What is Spring Boot and why use it?
⭐⭐⭐⭐⭐Explain @SpringBootApplication.
⭐⭐⭐⭐⭐Explain SpringApplication.run() internal flow.
⭐⭐⭐⭐⭐How does auto-configuration work?
⭐⭐⭐⭐⭐Explain component scanning.
⭐⭐⭐⭐⭐@Component vs @Service vs @Repository.
⭐⭐⭐⭐⭐@Controller vs @RestController.
⭐⭐⭐⭐⭐Constructor injection vs field injection.
⭐⭐⭐⭐⭐What is a Spring Bean?
⭐⭐⭐⭐⭐Explain singleton beans and thread safety.
⭐⭐⭐⭐⭐Mutable vs immutable state.
⭐⭐⭐⭐⭐How do you handle exceptions globally?
⭐⭐⭐⭐⭐@ControllerAdvice vs @RestControllerAdvice.
⭐⭐⭐⭐⭐How do you manage production configuration?
⭐⭐⭐⭐⭐What is Spring Cloud Config?
⭐⭐⭐⭐⭐How do profiles work?
⭐⭐⭐⭐⭐How do you manage secrets?
⭐⭐⭐⭐⭐What is Spring Boot Actuator?
⭐⭐⭐⭐⭐How do you expose metrics on a separate port?
⭐⭐⭐⭐⭐Explain Micrometer, Prometheus and Grafana.
⭐⭐⭐⭐CommandLineRunner vs ApplicationRunner.
⭐⭐⭐⭐@PostConstruct vs Runner.
⭐⭐⭐⭐@Bean vs @Component.
⭐⭐⭐⭐@Value vs @ConfigurationProperties.
⭐⭐⭐⭐@Transactional and transaction boundaries.
⭐⭐⭐⭐Spring Boot testing strategies.
⭐⭐⭐⭐REST API validation.
⭐⭐⭐⭐Caching with Redis.
⭐⭐⭐⭐CompletableFuture.
⭐⭐⭐⭐Virtual threads.

21. Senior-Level Scenario Questions

A REST API is slow in production. How do you investigate?

Check metrics, request latency, traces, logs, database timings, downstream calls, connection pools, thread utilization, GC and resource saturation. Identify whether the bottleneck is application, database, network or dependency.

One microservice is down. How do you prevent cascading failure?

Use timeouts, bounded retries, circuit breakers, bulkheads, fallbacks and appropriate rate limits. Avoid retry storms.

How would you safely store mutable state in a singleton service?

Prefer immutable state. If mutable state is required, use appropriate concurrent structures or atomic classes. For distributed/durable state, use Redis or a database.

How would you expose application metrics without exposing them publicly?

Use a separate management port, restrict network access, expose only required endpoints, and secure management endpoints.

How would you manage configuration across 50 microservices?

Centralize non-secret configuration using a configuration service/repository and use a dedicated secret-management solution for credentials and keys.

When would you choose Kafka instead of REST?

Prefer messaging when decoupling, asynchronous processing, buffering, event-driven workflows or independent consumer scaling are important. REST is often suitable for request/response interactions.

How do you make a POST operation idempotent?

Use an idempotency key, persist request/result state where appropriate, and ensure duplicate requests map to the same logical operation rather than creating duplicate side effects.

How do virtual threads change application design?

They can support very high concurrency for blocking workloads, but they do not remove limits from databases, downstream services or shared state. Resource pools and synchronization still need careful design.

22. Spring Boot Coding Cookbook – Most Important Examples

Purpose: This section contains the practical code snippets most commonly requested during Java/Spring Boot interviews. Each example is intentionally small so it can be explained quickly on a whiteboard.
1. Main class – @SpringBootApplication
package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
2. Controller + Service + Repository structure
@RestController
@RequestMapping("/api/orders")
public class OrderController {

    private final OrderService service;

    public OrderController(OrderService service) {
        this.service = service;
    }

    @GetMapping("/{id}")
    public Order getOrder(@PathVariable Long id) {
        return service.getOrder(id);
    }
}

@Service
public class OrderService {

    private final OrderRepository repository;

    public OrderService(OrderRepository repository) {
        this.repository = repository;
    }

    public Order getOrder(Long id) {
        return repository.findById(id)
                .orElseThrow(() -> new ResourceNotFoundException("Order not found"));
    }
}

@Repository
public interface OrderRepository extends JpaRepository<Order, Long> {
}
3. @Configuration + @Bean
@Configuration
public class AppConfig {

    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper();
    }
}
4. Constructor injection with multiple implementations
public interface PaymentService {
    void pay();
}

@Service("cardPayment")
public class CardPaymentService implements PaymentService {
    public void pay() {
        System.out.println("Card payment");
    }
}

@Service("upiPayment")
public class UpiPaymentService implements PaymentService {
    public void pay() {
        System.out.println("UPI payment");
    }
}

@Service
public class CheckoutService {

    private final PaymentService paymentService;

    public CheckoutService(
            @Qualifier("upiPayment") PaymentService paymentService) {
        this.paymentService = paymentService;
    }
}
5. REST CRUD API
@RestController
@RequestMapping("/api/products")
public class ProductController {

    @GetMapping("/{id}")
    public ResponseEntity<Product> get(@PathVariable Long id) {
        return ResponseEntity.ok(service.get(id));
    }

    @PostMapping
    public ResponseEntity<Product> create(
            @Valid @RequestBody ProductRequest request) {

        Product saved = service.create(request);
        return ResponseEntity.status(HttpStatus.CREATED).body(saved);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Product> update(
            @PathVariable Long id,
            @Valid @RequestBody ProductRequest request) {

        return ResponseEntity.ok(service.update(id, request));
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> delete(@PathVariable Long id) {
        service.delete(id);
        return ResponseEntity.noContent().build();
    }
}
6. DTO validation
public class UserRequest {

    @NotBlank(message = "Name is required")
    private String name;

    @Email(message = "Invalid email")
    @NotBlank
    private String email;

    @Min(value = 18, message = "Age must be at least 18")
    private int age;

    // getters and setters
}
7. Global exception handling
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    public ResponseEntity<ApiError> handleNotFound(
            ResourceNotFoundException ex,
            HttpServletRequest request) {

        ApiError error = new ApiError(
                Instant.now(),
                404,
                "RESOURCE_NOT_FOUND",
                ex.getMessage(),
                request.getRequestURI());

        return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ApiError> handleValidation(
            MethodArgumentNotValidException ex) {

        String message = ex.getBindingResult()
                .getFieldErrors()
                .stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));

        return ResponseEntity.badRequest()
                .body(new ApiError(Instant.now(), 400,
                        "VALIDATION_ERROR", message, null));
    }
}
8. Immutable class
public final class Employee {

    private final String id;
    private final String name;
    private final List<String> skills;

    public Employee(String id, String name, List<String> skills) {
        this.id = id;
        this.name = name;
        this.skills = List.copyOf(skills); // defensive copy
    }

    public String getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public List<String> getSkills() {
        return skills;
    }
}
9. Safe mutable state – AtomicInteger
@Service
public class CounterService {

    private final AtomicInteger counter = new AtomicInteger();

    public int increment() {
        return counter.incrementAndGet();
    }

    public int get() {
        return counter.get();
    }
}
10. Safe concurrent map
@Service
public class CacheService {

    private final ConcurrentHashMap<Long, String> cache =
            new ConcurrentHashMap<>();

    public void put(Long id, String value) {
        cache.put(id, value);
    }

    public String get(Long id) {
        return cache.get(id);
    }
}
11. @ConfigurationProperties
@ConfigurationProperties(prefix = "payment")
public class PaymentProperties {

    private String url;
    private Duration timeout;
    private int retry;

    // getters and setters
}
payment:
  url: https://payment-service
  timeout: 5s
  retry: 3
12. Profiles
# application.yml
spring:
  profiles:
    active: dev

# application-dev.yml
server:
  port: 8080

# application-prod.yml
server:
  port: 8080

Production deployments can set SPRING_PROFILES_ACTIVE=prod externally instead of hard-coding it.

13. Separate Actuator / metrics port
server.port=8080

management.server.port=8081

management.endpoints.web.exposure.include=
health,info,metrics,prometheus

Application APIs can use port 8080 while management endpoints use port 8081.

14. CommandLineRunner
@Component
public class StartupRunner implements CommandLineRunner {

    @Override
    public void run(String... args) {
        System.out.println("Startup task executed");
    }
}
15. ApplicationRunner
@Component
public class AppRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) {
        System.out.println("Option names: " + args.getOptionNames());
    }
}
16. @Transactional service method
@Service
public class TransferService {

    @Transactional
    public void transfer(Long from, Long to, BigDecimal amount) {
        accountRepository.debit(from, amount);
        accountRepository.credit(to, amount);
    }
}
Interview point: Explain transaction boundaries, rollback behavior, proxy interception and the self-invocation limitation.
17. @Cacheable
@Service
public class ProductService {

    @Cacheable(value = "products", key = "#id")
    public Product getProduct(Long id) {
        return repository.findById(id)
                .orElseThrow();
    }

    @CacheEvict(value = "products", key = "#id")
    public void delete(Long id) {
        repository.deleteById(id);
    }
}
18. CompletableFuture – parallel calls
CompletableFuture<User> user =
        CompletableFuture.supplyAsync(() -> userClient.getUser(id));

CompletableFuture<Orders> orders =
        CompletableFuture.supplyAsync(() -> orderClient.getOrders(id));

return user.thenCombine(orders,
        (u, o) -> new UserDashboard(u, o));
19. CompletableFuture – exception handling
CompletableFuture.supplyAsync(() -> service.call())
    .orTimeout(2, TimeUnit.SECONDS)
    .exceptionally(ex -> {
        log.error("Async call failed", ex);
        return fallbackValue();
    });
20. Virtual thread example (JDK 21+)
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {

    Future<String> future = executor.submit(() -> {
        return callBlockingService();
    });

    System.out.println(future.get());
}

For Spring Boot, use the supported virtual-thread configuration for the Spring Boot/JDK version you deploy. Virtual threads improve concurrency for suitable blocking workloads; they do not make CPU-bound work inherently faster.

21. Spring Security – conceptual SecurityFilterChain
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http)
        throws Exception {

    http
        .csrf(csrf -> csrf.disable())
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/actuator/health").permitAll()
            .requestMatchers("/api/admin/**").hasRole("ADMIN")
            .anyRequest().authenticated());

    return http.build();
}
22. Retry + timeout + circuit breaker – conceptual flow
Client
   |
   v
Order Service
   |
   +-- Timeout
   |
   +-- Retry (only transient failures)
   |
   +-- Circuit Breaker
   |
   v
Payment Service
   |
   X unavailable
   |
   v
Fallback / graceful response
Interview point: Never blindly retry every failure. Consider idempotency, retry count, backoff, jitter, timeouts and downstream capacity.
23. REST client – service-to-service call
@Service
public class PaymentClient {

    private final RestClient restClient;

    public PaymentClient(RestClient.Builder builder) {
        this.restClient = builder
                .baseUrl("http://payment-service")
                .build();
    }

    public PaymentResponse getPayment(Long id) {
        return restClient.get()
                .uri("/api/payments/{id}", id)
                .retrieve()
                .body(PaymentResponse.class);
    }
}
24. Kafka producer – conceptual example
@Service
public class OrderEventPublisher {

    private final KafkaTemplate<String, OrderCreatedEvent> kafka;

    public OrderEventPublisher(
            KafkaTemplate<String, OrderCreatedEvent> kafka) {
        this.kafka = kafka;
    }

    public void publish(OrderCreatedEvent event) {
        kafka.send("order-created", event.orderId(), event);
    }
}
25. Health endpoint – custom HealthIndicator
@Component
public class PaymentHealthIndicator implements HealthIndicator {

    @Override
    public Health health() {

        boolean available = checkPaymentService();

        if (available) {
            return Health.up()
                    .withDetail("payment", "available")
                    .build();
        }

        return Health.down()
                .withDetail("payment", "unavailable")
                .build();
    }
}
26. Custom Micrometer metric
@Service
public class OrderService {

    private final Counter orderCounter;

    public OrderService(MeterRegistry registry) {
        this.orderCounter = Counter.builder("orders.created")
                .description("Number of created orders")
                .register(registry);
    }

    public void createOrder() {
        // business logic
        orderCounter.increment();
    }
}
27. Java 8 Stream example
List<String> names =
        Arrays.asList("Ravi", "John", "Robert", "Sam");

List<String> result = names.stream()
        .filter(name -> name.length() > 4)
        .map(String::toUpperCase)
        .sorted()
        .collect(Collectors.toList());
28. Optional example
public Product findProduct(Long id) {
    return repository.findById(id)
            .orElseThrow(() ->
                new ResourceNotFoundException(
                    "Product not found: " + id));
}
29. Java 8 functional interfaces
Predicate<Integer> positive =
        n -> n > 0;

Function<String, Integer> length =
        String::length;

Consumer<String> printer =
        System.out::println;

Supplier<UUID> idSupplier =
        UUID::randomUUID;
30. Idempotency – simple REST pattern
@PostMapping("/payments")
public ResponseEntity<PaymentResponse> create(
        @RequestHeader("Idempotency-Key") String key,
        @RequestBody PaymentRequest request) {

    // 1. Look up key in durable storage
    // 2. If already processed, return stored response
    // 3. Otherwise process once
    // 4. Store result against key

    return ResponseEntity.status(HttpStatus.CREATED)
            .body(service.processOnce(key, request));
}

23. One-Page Revision Map

SPRING BOOT INTERVIEW
│
├── Fundamentals
│   ├── Spring vs Spring Boot
│   ├── Starters
│   ├── Auto Configuration
│   └── Embedded Server
│
├── Application Startup
│   ├── SpringApplication.run()
│   ├── ApplicationContext
│   ├── Events
│   ├── Runners
│   └── ApplicationReadyEvent
│
├── Core
│   ├── IoC / DI
│   ├── Beans
│   ├── Scopes
│   └── Component Stereotypes
│
├── Configuration
│   ├── application.yml
│   ├── Profiles
│   ├── @Value
│   ├── @ConfigurationProperties
│   ├── Spring Cloud Config
│   └── Secrets
│
├── Web
│   ├── REST
│   ├── Validation
│   └── Global Exception Handling
│
├── Database
│   ├── JPA / Hibernate
│   ├── Transactions
│   ├── Connection Pool
│   └── N+1
│
├── Production
│   ├── Actuator
│   ├── Metrics
│   ├── Prometheus
│   ├── Grafana
│   ├── Health
│   ├── Logging
│   └── Tracing
│
├── Concurrency
│   ├── Mutable / Immutable
│   ├── Atomic
│   ├── Concurrent Collections
│   ├── CompletableFuture
│   └── Virtual Threads
│
└── Microservices
    ├── REST / Kafka / Camel
    ├── Config
    ├── Discovery
    ├── Gateway
    ├── Circuit Breaker
    ├── Retry / Timeout
    ├── Saga
    └── Idempotency