Module 18: Spring Boot Interview Questions
Objectives
This module prepares you for technical interviews in Java/Spring Boot development. The questions are organized by difficulty level and theme, covering the most frequently asked topics in interviews.
Do not memorize the answers word for word. Understand the concepts and be able to explain them in your own words with concrete examples.
Module Chapters
| # | Chapter | Content |
|---|---|---|
| 1 | JPA & Database | N+1 problem, Lazy/Eager loading, @Transactional, pagination, entity relationships |
| 2 | Refactoring Exercises | Guard clauses, Strategy Pattern, SRP (God Class), magic constants, composition vs inheritance |
| 3 | Algorithms & Data Structures | HashMap, Stack, LinkedList, Binary Search, Two Sum, FizzBuzz, anagrams |
| 4 | REST Design & Design Patterns | REST API, Builder, Singleton, Observer with Spring Events |
| 5 | Debugging & Code Review | Finding bugs, code review, memory leak, concurrency, exceptions, code smells |
| 6 | Java Fundamentals Traps | == vs .equals(), hashCode(), final, static, immutable String, Optional, pass by value |
| 7 | Java Collections | List.of() vs new ArrayList<>(), HashMap, HashSet, Stream API, thread-safety, iteration |
| 8 | "What is...?" — 30 concepts | DTO, MVC, REST API, CRUD, POJO, Bean, IoC, ORM/JPA, Maven, Docker, JWT, CORS, Lombok, Record... |
Level 1: Fundamental Questions
Q1. What is Spring Boot and how does it differ from Spring Framework?
Expected Answer:
Spring Boot is a framework built on top of Spring Framework that simplifies configuration and deployment. The main differences:
| Aspect | Spring Framework | Spring Boot |
|---|---|---|
| Configuration | Manual (XML or Java) | Auto-configuration |
| Server | External server required | Embedded server (Tomcat) |
| Dependencies | Managed individually | Pre-configured starters |
| Startup | Complex | main() + @SpringBootApplication |
Spring Boot does not replace Spring, it makes it easier to use.
Q2. What does the @SpringBootApplication annotation do?
Expected Answer:
It is a meta-annotation that combines three annotations:
@SpringBootConfiguration: indicates a Spring configuration class@EnableAutoConfiguration: enables auto-configuration based on classpath dependencies@ComponentScan: scans the current package and its sub-packages to find beans
Q3. What is dependency injection (DI)?
Expected Answer:
Dependency injection is a design pattern where an object's dependencies are provided from the outside rather than created by the object itself.
// WITHOUT DI (tight coupling)
public class OrderService {
private UserRepository repo = new UserRepository(); // Creates its own dependency
}
// WITH DI (loose coupling)
public class OrderService {
private final UserRepository repo;
public OrderService(UserRepository repo) { // Injected from outside
this.repo = repo;
}
}
Advantages: testability, decoupling, flexibility.
Q4. What is the difference between @Controller and @RestController?
Expected Answer:
@Controllerreturns view names (HTML templates). To return JSON, you need to add@ResponseBodyto each method.@RestController=@Controller+@ResponseBody. Each method directly returns data serialized in JSON.
Q5. What are the different bean scopes in Spring?
Expected Answer:
| Scope | Description |
|---|---|
| singleton | A single instance per container (default) |
| prototype | New instance for each injection |
| request | One instance per HTTP request |
| session | One instance per HTTP session |
| application | One instance per ServletContext |
Q6. What is the difference between application.properties and application.yml?
Expected Answer:
Same functionality, different syntax:
# application.properties (key=value, flat)
server.port=8080
spring.datasource.url=jdbc:postgresql://localhost:5432/mydb
# application.yml (hierarchical, more readable)
server:
port: 8080
spring:
datasource:
url: jdbc:postgresql://localhost:5432/mydb
YAML is more readable for nested configurations, but be careful with indentation.
Q7. What is a Spring Boot Starter?
Expected Answer:
A starter is a set of pre-configured dependencies for a specific use:
spring-boot-starter-web: web application (Tomcat, Spring MVC, Jackson)spring-boot-starter-data-jpa: persistence (Hibernate, Spring Data JPA)spring-boot-starter-security: security (Spring Security)spring-boot-starter-test: tests (JUnit, Mockito, MockMvc)
They avoid manually managing version compatibilities.
Level 2: Intermediate Questions
Q8. Explain the layered architecture of a Spring Boot application.
Expected Answer:
HTTP Client
↓
┌─────────────────┐
│ Controller │ Receives requests, validates, returns responses
├─────────────────┤
│ Service │ Business logic, business rules, orchestration
├─────────────────┤
│ Repository │ Data access (CRUD, DB queries)
├─────────────────┤
│ Database │ PostgreSQL, MySQL, H2...
└─────────────────┘
Each layer only communicates with the layer directly below. The Controller never directly accesses the Repository.
Q9. What is the difference between JpaRepository, CrudRepository, and PagingAndSortingRepository?
Expected Answer:
JpaRepository (most complete)
↑ inherits from
PagingAndSortingRepository (pagination + sorting)
↑ inherits from
CrudRepository (basic CRUD)
↑ inherits from
Repository (marker)
- CrudRepository:
save(),findById(),findAll(),deleteById() - PagingAndSortingRepository: adds
findAll(Pageable),findAll(Sort) - JpaRepository: adds
flush(),saveAndFlush(),deleteInBatch(), returnsListinstead ofIterable
In practice, we almost always use JpaRepository.
Q10. How does auto-configuration work in Spring Boot?
Expected Answer:
Spring Boot examines the classpath at startup and automatically configures the necessary beans:
- If
spring-boot-starter-data-jpais on the classpath AND aDataSourceis configured → auto-configures Hibernate, EntityManager, etc. - If
spring-boot-starter-webis on the classpath → auto-configures Tomcat, Jackson, DispatcherServlet @ConditionalOn...annotations determine if an auto-configuration applies
You can always override auto-configured beans with your own @Bean.
Q11. What are Spring Profiles and what are they used for?
Expected Answer:
Profiles allow loading different configurations depending on the environment:
# application-dev.yml
spring:
datasource:
url: jdbc:h2:mem:devdb
# application-prod.yml
spring:
datasource:
url: jdbc:postgresql://prod-server:5432/mydb
Activation: --spring.profiles.active=prod or SPRING_PROFILES_ACTIVE=prod
You can also condition beans with @Profile("dev").
Q12. Explain the difference between @Transactional for reading and writing.
Expected Answer:
@Transactional(readOnly = true) // Read: Hibernate optimization (no dirty checking)
public List<User> findAll() { ... }
@Transactional // Write: commit if successful, rollback if exception
public User create(UserDto dto) { ... }
Best practice: Put @Transactional(readOnly = true) at the service class level, and @Transactional on write methods only.
Q13. How do you handle exceptions in a Spring Boot REST API?
Expected Answer:
Three approaches, from the most local to the most global:
@ExceptionHandlerin a controller (local scope)@RestControllerAdvicewith@ExceptionHandler(global scope)@ResponseStatuson a custom exception
The best practice is a global @RestControllerAdvice that centralizes all error handling.
Q14. What is the N+1 problem in JPA and how do you solve it?
Expected Answer:
The N+1 problem occurs when loading an entity and JPA executes N additional queries to load the relationships:
1 query to load 100 departments
+ 100 queries to load employees of each department
= 101 queries instead of 1 or 2
Solutions:
JOIN FETCHin JPQL:@Query("SELECT d FROM Department d JOIN FETCH d.employees")@EntityGraph:@EntityGraph(attributePaths = {"employees"})@BatchSize: loads relationships in batches
Q15. How do you secure a REST API with JWT?
Expected Answer:
The JWT flow:
1. Client sends login/password → POST /api/auth/login
2. Server verifies credentials
3. If OK → generates a signed JWT and returns it
4. Client stores the JWT
5. For each request → Authorization: Bearer <token>
6. JwtAuthenticationFilter extracts and validates the token
7. If valid → authenticates the user in the SecurityContext
Key components: JwtService (generation/validation), JwtAuthenticationFilter (filter), SecurityConfig (configuration).
Level 3: Advanced Questions
Q16. Explain the IoC (Inversion of Control) pattern in Spring.
Expected Answer:
IoC inverts the flow of control: instead of the code creating its dependencies, the Spring container creates and injects them.
The Spring container (ApplicationContext) is responsible for:
- Creating objects (beans)
- Configuring objects
- Assembling dependencies
- Managing the lifecycle
Dependency injection (DI) is the main mechanism of IoC in Spring.
Q17. What is the difference between @Component, @Service, @Repository, and @Controller?
Expected Answer:
Technically, all four are @Component. The difference is semantic (role in the architecture):
@Component: generic bean@Service: business logic@Repository: data access + automatic translation of SQL exceptions into Spring exceptions@Controller: web request handling
Using the correct annotation helps readability and allows specific processing (e.g., exception translation for @Repository).
Q18. How do you implement pagination in Spring Data JPA?
Expected Answer:
// Repository
public interface UserRepository extends JpaRepository<User, Long> {
Page<User> findByRole(Role role, Pageable pageable);
}
// Controller
@GetMapping("/users")
public Page<User> getUsers(
@RequestParam(defaultValue = "0") int page,
@RequestParam(defaultValue = "20") int size,
@RequestParam(defaultValue = "name") String sortBy) {
Pageable pageable = PageRequest.of(page, size, Sort.by(sortBy));
return userRepository.findAll(pageable);
}
The returned Page<T> contains: content, page number, size, total elements, number of pages.
Q19. Explain the different propagation strategies of @Transactional.
Expected Answer:
| Propagation | Behavior |
|---|---|
REQUIRED (default) | Joins existing transaction or creates a new one |
REQUIRES_NEW | Always creates a new transaction (suspends existing) |
SUPPORTS | Joins if existing, otherwise executes without transaction |
NOT_SUPPORTED | Always executes without transaction (suspends existing) |
MANDATORY | Requires existing transaction, otherwise exception |
NEVER | No transaction, otherwise exception |
NESTED | Nested transaction (savepoint) |
Common use case for REQUIRES_NEW: audit log that must persist even if the main transaction fails.
Q20. How do you optimize the performance of a Spring Boot application?
Expected Answer:
-
JPA/Hibernate:
- Avoid N+1 problem (JOIN FETCH, EntityGraph)
- Use
@Transactional(readOnly = true)for reads - DTO projections instead of full entities
- Systematic pagination
-
Cache:
@Cacheablewith Spring Cache (Redis, Caffeine)- HTTP Cache (ETag, Cache-Control)
-
Configuration:
- Connection pooling (properly configured HikariCP)
- GZIP compression
- Profiles optimized for production
-
Architecture:
- Asynchronous operations (
@Async) - Proper DB indexing
- Lazy loading of relationships
- Asynchronous operations (
Q21. What is Spring Actuator and what useful endpoints does it provide?
Expected Answer:
Spring Actuator provides monitoring and management endpoints:
| Endpoint | Description |
|---|---|
/actuator/health | Application status (UP/DOWN) |
/actuator/info | Application information |
/actuator/metrics | Metrics (memory, CPU, requests) |
/actuator/env | Environment variables |
/actuator/beans | List of all beans |
/actuator/mappings | All REST endpoints |
/actuator/loggers | Logger configuration |
/actuator/prometheus | Metrics in Prometheus format |
In production, these endpoints should be secured and only /health and /info exposed publicly.
Q22. Explain the lifecycle of a Spring bean.
Expected Answer:
1. Instantiation (constructor)
2. Dependency injection (@Autowired)
3. Aware interfaces (BeanNameAware, ApplicationContextAware...)
4. BeanPostProcessor.postProcessBeforeInitialization()
5. @PostConstruct
6. InitializingBean.afterPropertiesSet()
7. Custom init-method
8. BeanPostProcessor.postProcessAfterInitialization()
9. ══════ Bean ready for use ══════
10. @PreDestroy
11. DisposableBean.destroy()
12. Custom destroy-method
In practice, we mainly use @PostConstruct and @PreDestroy.
Q23. How do you implement a simplified CQRS pattern with Spring Boot?
Expected Answer:
CQRS (Command Query Responsibility Segregation) separates read and write operations:
// Command (write)
@Service
@Transactional
public class UserCommandService {
public User create(CreateUserCommand cmd) { ... }
public void update(UpdateUserCommand cmd) { ... }
public void delete(Long id) { ... }
}
// Query (read)
@Service
@Transactional(readOnly = true)
public class UserQueryService {
public UserDto findById(Long id) { ... }
public Page<UserDto> findAll(Pageable page) { ... }
}
This allows optimizing reads and writes separately (e.g., DTO projections for reads, complex validations for writes).
Behavioral / Scenario Questions
Q24. You need to design a REST API for an e-commerce system. What endpoints do you create?
Expected Answer:
Products:
GET /api/products → Paginated list
GET /api/products/{id} → Product details
POST /api/products → Create (ADMIN)
PUT /api/products/{id} → Update (ADMIN)
DELETE /api/products/{id} → Delete (ADMIN)
Orders:
POST /api/orders → Place an order
GET /api/orders → My orders
GET /api/orders/{id} → Order details
PATCH /api/orders/{id} → Update status (ADMIN)
Auth:
POST /api/auth/register → Register
POST /api/auth/login → Login (returns JWT)
POST /api/auth/refresh → Refresh token
Cart:
GET /api/cart → My cart
POST /api/cart/items → Add to cart
DELETE /api/cart/items/{id} → Remove from cart
Q25. Your Spring Boot application is slow in production. How do you diagnose?
Expected Answer:
- Actuator metrics: check
/actuator/metrics/http.server.requeststo identify slow endpoints - Logs: enable
logging.level.org.hibernate.SQL=DEBUGto see SQL queries - N+1 problem: check the number of queries with
spring.jpa.show-sql=true - Connection pool: check HikariCP metrics (
hikaricp.connections.active) - Profiling: VisualVM or JFR (Java Flight Recorder)
- DB Index: analyze slow queries with
EXPLAIN ANALYZE - Memory: check garbage collector and heap size
Preparation Checklist
Before your interview, make sure you can:
- Explain IoC and DI with a concrete example
- Describe the layered architecture of a Spring Boot app
- Write a complete CRUD (Controller → Service → Repository)
- Explain JWT and the authentication flow
- Talk about your personal Spring Boot projects
- Describe how you handle exceptions
- Explain the difference between key annotations
- Talk about Docker and CI/CD with Spring Boot
- Know the basics of pagination and sorting
- Diagnose performance issues