Spring Boot

Spring Boot Interview Questions

Challenge yourself with 20 Spring Boot interview questions covering Dependency Injection, REST APIs, Security, JPA/Hibernate, Annotations, Testing, Actuator, and Microservices. Ideal prep for backend Java developer interviews.

20 Questions
30 min
Mixed Difficulty
Start Quiz

Topics Covered

AnnotationsDependency InjectionREST APIsSecurityJPA/HibernateActuatorTestingMicroservices

Difficulty Breakdown

6
Junior
11
Mid-Level
3
Senior

What to Expect

  • Multiple choice questions with 4 options each
  • Instant score and topic-by-topic breakdown
  • Detailed explanations for every question
  • Personalized course recommendations based on your weak areas

Spring Boot Interview Questions and Answers

Below are all 20 questions covered in this quiz, grouped by topic. Each question includes the correct answer and a detailed explanation to help you prepare for your next interview.

3Annotations

Q

What is the purpose of the @SpringBootApplication annotation?

A

It combines @Configuration, @EnableAutoConfiguration, and @ComponentScan

@SpringBootApplication is a convenience annotation that combines @Configuration (marks class as a source of bean definitions), @EnableAutoConfiguration (enables Spring Boot's auto-configuration), and @ComponentScan (scans for components in the current package and below).

Q

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

A

They are all specializations of @Component with semantic meaning for different layers

All four are stereotype annotations. @Component is the generic one. @Service, @Repository, and @Controller are specializations that indicate the role of the class (business logic, data access, web controller). @Repository also adds automatic exception translation for persistence.

Q

What are Spring Boot profiles and how are they used?

A

Profiles allow you to define environment-specific configurations (dev, test, prod) activated via spring.profiles.active

Spring Boot profiles let you segregate configurations for different environments. Use application-dev.yml, application-prod.yml etc. Activate with spring.profiles.active property, environment variable, or JVM argument. You can also use @Profile annotation on beans.

3Dependency Injection

Q

What is Dependency Injection in Spring?

A

A design pattern where the framework provides object dependencies instead of the object creating them itself

Dependency Injection (DI) is a design pattern where an object's dependencies are provided (injected) by the Spring container rather than the object creating them. This promotes loose coupling, testability, and separation of concerns.

Q

What is the difference between constructor injection and field injection in Spring?

A

Constructor injection is preferred because it supports immutability, makes dependencies explicit, and enables easier testing

Constructor injection is the recommended approach in Spring. It makes dependencies explicit, supports immutable objects (final fields), prevents circular dependencies at startup, and makes unit testing easier (you can pass mocks directly). Field injection hides dependencies and makes testing harder.

Q

How do you handle bean scope in Spring Boot?

A

Use @Scope annotation to define lifecycle: singleton (default), prototype, request, session, or application

Spring supports several bean scopes. Singleton (default) creates one instance per Spring container. Prototype creates a new instance each time the bean is requested. Request, Session, and Application scopes are for web applications. Use @Scope annotation to specify.

3REST APIs

Q

Which HTTP status code should a REST API return when a new resource is successfully created?

A

201 Created

201 Created is the correct status code for successful resource creation. 200 OK is for general success, 204 No Content for successful operations with no response body, and 202 Accepted for async processing.

Q

What is the difference between @RequestParam and @PathVariable?

A

@PathVariable extracts values from the URL path template; @RequestParam reads query string parameters

@PathVariable extracts values from the URI template (e.g., /users/{id}). @RequestParam reads query string parameters (e.g., /users?name=John). @PathVariable is typically used for resource identification, while @RequestParam is for filtering, sorting, and optional parameters.

Q

What is the purpose of @ControllerAdvice in Spring Boot?

A

To define global exception handlers, model attributes, and data binders across all controllers

@ControllerAdvice is used to define global exception handling (@ExceptionHandler), model attributes (@ModelAttribute), and data binding (@InitBinder) that apply across multiple controllers. Combined with @ResponseStatus or ResponseEntity, it creates a centralized error handling strategy.

1Security

Q

How does Spring Security's SecurityFilterChain work?

A

It defines a chain of servlet filters that intercept requests to apply authentication and authorization rules

SecurityFilterChain is a bean that defines a chain of security filters applied to incoming HTTP requests. Each filter handles a specific security concern (CSRF, authentication, authorization, etc.). You configure it in a @Configuration class to define which endpoints require authentication.

4JPA/Hibernate

Q

What is the difference between @Entity and @Table annotations in JPA?

A

@Entity marks a class as a JPA entity; @Table customizes the mapped database table name and properties

@Entity (javax.persistence) marks a class as a JPA entity to be managed by the persistence context. @Table is optional and allows you to customize the table name, schema, and constraints. Without @Table, the table name defaults to the class name.

Q

What is the N+1 query problem in JPA, and how do you solve it?

A

When fetching a parent entity triggers N additional queries for lazy-loaded children; solved with JOIN FETCH or @EntityGraph

The N+1 problem occurs when fetching a list of N entities triggers N additional SQL queries to load their lazy-loaded relationships. Solutions include using JOIN FETCH in JPQL, @EntityGraph annotations, or batch fetching with @BatchSize.

Q

What does @Transactional do in Spring?

A

It wraps the annotated method in a database transaction, handling commit and rollback automatically

@Transactional creates a proxy that wraps the method in a database transaction. If the method completes normally, the transaction is committed. If a runtime exception is thrown, it is rolled back. You can customize rollback rules, propagation, and isolation levels.

Q

What is the difference between spring.jpa.hibernate.ddl-auto values update and validate?

A

update modifies the schema to match entities; validate only checks that the schema matches entities without changes

update will alter existing tables and create new ones to match your entities (but never drops columns/tables). validate only checks if the current schema matches your entities and throws an exception if it doesn't. For production, use validate or none with a migration tool like Flyway.

1Actuator

Q

What is the purpose of Spring Boot Actuator?

A

To provide production-ready features like health checks, metrics, and monitoring endpoints

Spring Boot Actuator provides production-ready features for monitoring and managing your application. It exposes endpoints like /actuator/health, /actuator/metrics, /actuator/info, and /actuator/env. These are essential for production monitoring and Kubernetes readiness/liveness probes.

2Testing

Q

How do you write an integration test for a Spring Boot REST controller?

A

Use @SpringBootTest with MockMvc or TestRestTemplate to test the full request/response cycle

@SpringBootTest loads the full application context. Combined with MockMvc (for testing without a real server) or TestRestTemplate (for testing with a real embedded server), you can test the entire request/response cycle including serialization, validation, and exception handling.

Q

What is the difference between @MockBean and @Mock in Spring Boot testing?

A

@MockBean replaces a bean in the Spring context; @Mock creates a standalone mock not managed by Spring

@MockBean (from Spring Boot Test) creates a mock and adds it to the Spring ApplicationContext, replacing any existing bean of the same type. @Mock (from Mockito) creates a standalone mock not managed by Spring. Use @MockBean for integration tests and @Mock for unit tests.

3Microservices

Q

In a microservices architecture, what is the purpose of an API Gateway?

A

To act as a single entry point that routes requests to appropriate microservices, handling cross-cutting concerns

An API Gateway (e.g., Spring Cloud Gateway) serves as a single entry point for all client requests. It handles routing, load balancing, authentication, rate limiting, and other cross-cutting concerns. This simplifies client-side code and centralizes common functionality.

Q

What is the Circuit Breaker pattern in microservices?

A

A resilience pattern that stops cascading failures by failing fast when a downstream service is unresponsive

The Circuit Breaker pattern (implemented by Resilience4j or Hystrix) monitors calls to a service. When failures exceed a threshold, the circuit 'opens' and subsequent calls fail immediately without attempting the network call. After a timeout, it 'half-opens' to test if the service has recovered.

Q

What is Spring WebFlux and when would you use it instead of Spring MVC?

A

WebFlux is a reactive, non-blocking web framework ideal for high-concurrency scenarios with many I/O-bound operations

Spring WebFlux is a reactive web framework that uses non-blocking I/O and the Reactor library (Mono/Flux). It excels in high-concurrency scenarios with many I/O-bound operations (microservices, streaming). Use Spring MVC for traditional request-per-thread applications; WebFlux when you need reactive streams and backpressure.

Ready to test yourself?

Take the interactive quiz and get your score with a personalized topic breakdown.

Start the Quiz

Your Career Transformation Starts Now

Join thousands of developers mastering in-demand skills with Amigoscode. Try it free today.