Technology

Spring Boot Interview Questions and Answers

Spring Boot is the standard framework for Java backend development. These Spring Boot interview questions cover annotations, dependency injection and REST controllers for freshers, then auto-configuration, Spring Data JPA, transactions, security, exception handling, microservices and performance for experienced Java developers.

30 questions · Updated

Reading answers is not the same as saying them.Practise Spring Boot questions out loud and get a score, what you missed and a model answer for each one.
Practise free with AI
Spring Boot Interview Questions with answers. Examples: What is Spring Boot, and how is it different from Spring? What does @SpringBootApplication do? What is the difference between @Component, @Service, @Repository and @Controller? What is dependency injection, and which type is best?
Spring Boot Interview Questions: 30 questions with model answers on this page.

Basic Spring Boot interview questions

Fundamentals, definitions and simple scenarios. Good for freshers and warm-ups.

1. What is Spring Boot, and how is it different from Spring?

Spring is a large framework for Java applications built around dependency injection. Spring Boot makes Spring easy to use with auto-configuration, starter dependencies, an embedded server such as Tomcat, and production features through Actuator, so you can run an app with a single main method and very little configuration.

2. What does @SpringBootApplication do?

It combines three annotations: @Configuration (the class can define beans), @EnableAutoConfiguration (Spring Boot configures beans based on the dependencies on the classpath) and @ComponentScan (finds components in the package and its sub-packages). It is placed on the main class.

3. What is the difference between @Component, @Service, @Repository and @Controller?

All of them mark a class as a Spring bean found by component scanning. @Service marks business logic, @Repository marks data access and translates database exceptions into Spring's DataAccessException, @Controller handles web requests and returns views, and @RestController combines @Controller with @ResponseBody to return JSON.

4. What are Spring Boot starters?

Starters are dependency bundles that bring everything needed for a feature with compatible versions, such as spring-boot-starter-web for REST APIs with Tomcat and Jackson, spring-boot-starter-data-jpa for JPA and Hibernate, spring-boot-starter-security and spring-boot-starter-test. They save you from choosing and matching many individual libraries.

5. How do application.properties, application.yml and profiles work?

Answer flow · 3 steps
  1. Configuration such as server port, database URL and logging levels goes in application.properties or application.yml.

  2. Profiles such as dev, test and prod have their own files, like application-prod.yml, activated with spring.profiles.active.

  3. Values can be overridden by environment variables and command-line arguments, and injected with @Value or, better, type-safe @ConfigurationProperties classes.

6. What is the difference between @PathVariable, @RequestParam and @RequestBody?

@PathVariable reads a value from the URL path, such as id in /users/{id}. @RequestParam reads query parameters, such as /users?page=2, with optional defaults. @RequestBody converts the JSON request body into a Java object using Jackson. Mappings such as @GetMapping, @PostMapping, @PutMapping and @DeleteMapping bind methods to HTTP methods and paths.

@RestController
@RequestMapping("/api/users")
class UserController {
    @GetMapping("/{id}")
    UserDto get(@PathVariable Long id) { return service.get(id); }

    @GetMapping
    Page<UserDto> list(@RequestParam(defaultValue = "0") int page) { return service.list(page); }

    @PostMapping
    ResponseEntity<UserDto> create(@Valid @RequestBody CreateUser body) {
        return ResponseEntity.status(HttpStatus.CREATED).body(service.create(body));
    }
}

7. What is Spring Boot Actuator?

Actuator adds production endpoints for monitoring and managing an application, such as /actuator/health for health checks used by Kubernetes and load balancers, /actuator/metrics, /actuator/info and /actuator/prometheus for metrics scraping. Endpoints are exposed selectively, and sensitive ones must be secured or kept on an internal port.

8. What is an embedded server?

Answer flow · 3 steps
  1. Spring Boot packages a web server, Tomcat by default or Jetty or Undertow, inside the application, so it runs as a single executable JAR with java -jar instead of being deployed to an external server.

  2. This makes applications self-contained and easy to run in containers.

  3. The port and other settings are configured in application properties.

9. What do @Autowired, @Qualifier and @Primary do?

Answer flow · 3 steps
  1. @Autowired asks Spring to inject a dependency; with a single constructor it is optional.

  2. When several beans of the same type exist, @Primary marks the default one, and @Qualifier("name") picks a specific bean at the injection point.

  3. Constructor injection with final fields is the recommended style.

10. How do you validate request data in Spring Boot?

Answer flow · 3 steps
  1. Add spring-boot-starter-validation, annotate DTO fields with Bean Validation constraints such as @NotBlank, @Email, @Size, @Min and @Pattern, and put @Valid on the @RequestBody parameter.

  2. Invalid input throws MethodArgumentNotValidException, which a @RestControllerAdvice turns into a 400 response listing each field error.

  3. Custom constraints are created with your own annotation and validator.

11. What is ResponseEntity?

Answer flow · 3 steps
  1. ResponseEntity represents the whole HTTP response: status code, headers and body.

  2. Returning it from a controller gives full control, for example ResponseEntity.status(HttpStatus.CREATED).header("Location", url).body(dto), or ResponseEntity.noContent().build() for a 204.

  3. Returning a plain object sends it with status 200.

Intermediate Spring Boot interview questions

Applied problems, trade-offs and questions about your own projects.

12. What is dependency injection, and which type is best?

Answer flow · 3 steps
  1. Dependency injection means the framework creates objects and provides their dependencies, instead of classes creating them.

  2. Spring supports constructor, setter and field injection.

  3. Constructor injection is recommended because dependencies are explicit, can be final, the class is easy to test without Spring, and missing dependencies fail at startup.

13. How do you handle exceptions globally in a Spring Boot REST API?

Answer flow · 3 steps
  1. I create a class annotated with @RestControllerAdvice and methods with @ExceptionHandler for specific exceptions, such as a custom ResourceNotFoundException returning 404 or validation errors returning 400 with field messages.

  2. This keeps controllers clean and responses consistent.

  3. Spring Boot 3 supports ProblemDetail for a standard error format.

14. What is Spring Data JPA?

Answer flow · 4 steps
  1. Spring Data JPA reduces data access code.

  2. You define an interface extending JpaRepository, and Spring provides CRUD methods, paging and sorting.

  3. Query methods are derived from method names, such as findByEmailAndActiveTrue, and custom queries use @Query with JPQL or native SQL.

  4. It uses Hibernate as the JPA implementation by default.

15. What are bean scopes in Spring?

singleton (the default) creates one instance per Spring container, prototype creates a new instance each time it is requested, and web-aware scopes include request, session and application. Singleton beans must be thread-safe because they are shared, so they should not hold user-specific state.

16. How does auto-configuration work?

Answer flow · 4 steps
  1. Spring Boot contains many auto-configuration classes listed in its AutoConfiguration.imports file.

  2. Each is guarded by conditions such as @ConditionalOnClass (a library is on the classpath), @ConditionalOnMissingBean (you have not defined your own) and @ConditionalOnProperty.

  3. So adding a database driver creates a DataSource automatically, but defining your own bean replaces the default.

  4. The --debug flag prints the conditions report.

17. What is the bean lifecycle?

Spring creates the bean instance, injects dependencies, calls Aware interfaces, runs BeanPostProcessors before initialisation, then initialisation callbacks such as @PostConstruct or afterPropertiesSet, then post-processing after initialisation, which is where proxies for @Transactional and AOP are created. On shutdown it calls @PreDestroy or destroy methods.

18. What are fetch types in JPA, and which should you use?

LAZY loads a relationship only when it is accessed; EAGER loads it immediately with the entity. @ManyToOne and @OneToOne default to EAGER and collections to LAZY. Best practice is to make everything LAZY and fetch what each use case needs with JOIN FETCH, entity graphs or DTO projections, because EAGER loading causes extra queries and loads far more data than needed.

19. How do you implement pagination and sorting?

Answer flow · 3 steps
  1. Repository methods accept a Pageable, such as findByStatus(Status s, Pageable p), and return a Page with the content, total count and page information, or a Slice when you do not need the total.

  2. Controllers can receive Pageable directly from query parameters such as ?page=0&size=20&sort=createdAt,desc.

  3. Limit the maximum page size to protect the database.

20. How do you add caching in Spring Boot?

Enable caching with @EnableCaching and annotate methods with @Cacheable to store results by key, @CachePut to update the cache and @CacheEvict to remove entries when data changes. The cache provider can be a simple in-memory map, Caffeine for fast local caching, or Redis for a cache shared between instances, with time-to-live settings.

21. How do @Scheduled and @Async work?

Answer flow · 3 steps
  1. @EnableScheduling with @Scheduled runs methods on a schedule, using fixedRate, fixedDelay or cron expressions, for jobs such as cleanup or report generation.

  2. In a cluster, a lock such as ShedLock stops the job running on every instance. @EnableAsync with @Async runs a method on a thread pool and can return a CompletableFuture.

  3. Both rely on proxies, so self-invocation does not work.

22. How do you call another REST API from Spring Boot?

Answer flow · 4 steps
  1. RestClient, added in Spring 6.1, is the modern synchronous client with a fluent API, replacing RestTemplate.

  2. WebClient is the reactive, non-blocking client.

  3. Declarative HTTP interfaces (@HttpExchange) or OpenFeign generate clients from an interface.

  4. Always set timeouts, handle errors, and add retries and circuit breakers with Resilience4j for unreliable services.

High level Spring Boot interview questions

System design, deep internals, leadership and tough follow-ups.

23. How does @Transactional work, and what are common pitfalls?

Answer flow · 4 steps
  1. Spring wraps the bean in a proxy that starts a transaction before the method and commits or rolls back after.

  2. By default it rolls back only on unchecked exceptions.

  3. Common pitfalls: calling a @Transactional method from another method in the same class bypasses the proxy, it does not work on private methods, and long transactions holding locks hurt performance.

  4. Propagation and isolation settings control nested behaviour.

24. What is the N+1 problem in JPA, and how do you fix it?

Answer flow · 4 steps
  1. It happens when you load a list of entities with one query, then lazy-loading a relationship runs one extra query per entity.

  2. With 100 orders, that is 101 queries.

  3. Fixes include JOIN FETCH in JPQL, @EntityGraph to fetch associations, batch fetching with @BatchSize, or projecting to DTOs that fetch only needed data.

  4. I detect it by logging SQL or counting queries in tests.

25. How do you secure a Spring Boot REST API?

Answer flow · 3 steps
  1. With Spring Security I define a SecurityFilterChain bean that sets which endpoints are public or require roles, disables session state for stateless APIs and configures CORS.

  2. Authentication commonly uses JWT, often as an OAuth2 resource server validating tokens from Keycloak, Okta or Auth0.

  3. Passwords use BCryptPasswordEncoder, and method-level rules use @PreAuthorize.

26. How do you build microservices with Spring Cloud?

Spring Cloud provides Config Server for central configuration, service discovery with Eureka or Kubernetes, Spring Cloud Gateway as the API gateway for routing, authentication and rate limiting, Resilience4j for circuit breakers, retries and timeouts, and Spring Cloud Stream for messaging with Kafka or RabbitMQ. Micrometer Tracing correlates requests across services.

27. What is the difference between Spring MVC and Spring WebFlux?

Answer flow · 3 steps
  1. Spring MVC uses a thread per request on a servlet container and blocking code, which is simple and works with JPA.

  2. WebFlux is reactive and non-blocking, built on Project Reactor (Mono and Flux) and usually Netty, handling many concurrent connections with few threads, which suits streaming and high-concurrency I/O.

  3. With Java 21 virtual threads, MVC now scales well for most I/O-bound applications.

28. How do you test a Spring Boot application?

Answer flow · 3 steps
  1. Unit test services with JUnit 5 and Mockito, without starting Spring.

  2. Use slice tests such as @WebMvcTest for controllers with MockMvc and @DataJpaTest for repositories, and @SpringBootTest for full integration tests.

  3. Testcontainers runs real PostgreSQL, Kafka or Redis in Docker for reliable integration tests, and @ServiceConnection wires them up automatically.

29. How do virtual threads help Spring Boot applications?

Answer flow · 3 steps
  1. With spring.threads.virtual.enabled=true (Spring Boot 3.2+ on Java 21), Tomcat and @Async tasks run on virtual threads.

  2. Blocking calls to databases and HTTP services no longer tie up scarce platform threads, so a traditional Spring MVC app can handle far more concurrent requests without rewriting it reactively.

  3. Database connection pools still limit concurrency and must be sized correctly.

30. How do you monitor a Spring Boot application in production?

Use Actuator with Micrometer to export metrics to Prometheus and dashboards in Grafana, covering request rates, latency, errors, JVM memory, garbage collection and connection pools. Add distributed tracing with Micrometer Tracing and OpenTelemetry, structured JSON logs with trace IDs, health checks for Kubernetes liveness and readiness probes, and alerts on key indicators.

Ready to test yourself?Pick your topics and level, answer by voice or text, and get instant feedback. Free.
Start a mock interview

Preparing for a backend developer interview?

See all Backend Developer interview questions, covering Node.js, Express.js, NestJS, Python, Django and more.

Related skill interview questions

More technology interview questions

HR round, company and bank interview questions

Bank and government exams

Interview questions for other fields