Skip to main content

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.

Advice

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​

#ChapterContent
1JPA & DatabaseN+1 problem, Lazy/Eager loading, @Transactional, pagination, entity relationships
2Refactoring ExercisesGuard clauses, Strategy Pattern, SRP (God Class), magic constants, composition vs inheritance
3Algorithms & Data StructuresHashMap, Stack, LinkedList, Binary Search, Two Sum, FizzBuzz, anagrams
4REST Design & Design PatternsREST API, Builder, Singleton, Observer with Spring Events
5Debugging & Code ReviewFinding bugs, code review, memory leak, concurrency, exceptions, code smells
6Java Fundamentals Traps== vs .equals(), hashCode(), final, static, immutable String, Optional, pass by value
7Java CollectionsList.of() vs new ArrayList<>(), HashMap, HashSet, Stream API, thread-safety, iteration
8"What is...?" — 30 conceptsDTO, 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:

AspectSpring FrameworkSpring Boot
ConfigurationManual (XML or Java)Auto-configuration
ServerExternal server requiredEmbedded server (Tomcat)
DependenciesManaged individuallyPre-configured starters
StartupComplexmain() + @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:

  • @Controller returns view names (HTML templates). To return JSON, you need to add @ResponseBody to each method.
  • @RestController = @Controller + @ResponseBody. Each method directly returns data serialized in JSON.

Q5. What are the different bean scopes in Spring?​

Expected Answer:

ScopeDescription
singletonA single instance per container (default)
prototypeNew instance for each injection
requestOne instance per HTTP request
sessionOne instance per HTTP session
applicationOne 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(), returns List instead of Iterable

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:

  1. If spring-boot-starter-data-jpa is on the classpath AND a DataSource is configured → auto-configures Hibernate, EntityManager, etc.
  2. If spring-boot-starter-web is on the classpath → auto-configures Tomcat, Jackson, DispatcherServlet
  3. @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:

  1. @ExceptionHandler in a controller (local scope)
  2. @RestControllerAdvice with @ExceptionHandler (global scope)
  3. @ResponseStatus on 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 FETCH in 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:

  1. Creating objects (beans)
  2. Configuring objects
  3. Assembling dependencies
  4. 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:

PropagationBehavior
REQUIRED (default)Joins existing transaction or creates a new one
REQUIRES_NEWAlways creates a new transaction (suspends existing)
SUPPORTSJoins if existing, otherwise executes without transaction
NOT_SUPPORTEDAlways executes without transaction (suspends existing)
MANDATORYRequires existing transaction, otherwise exception
NEVERNo transaction, otherwise exception
NESTEDNested 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:

  1. JPA/Hibernate:

    • Avoid N+1 problem (JOIN FETCH, EntityGraph)
    • Use @Transactional(readOnly = true) for reads
    • DTO projections instead of full entities
    • Systematic pagination
  2. Cache:

    • @Cacheable with Spring Cache (Redis, Caffeine)
    • HTTP Cache (ETag, Cache-Control)
  3. Configuration:

    • Connection pooling (properly configured HikariCP)
    • GZIP compression
    • Profiles optimized for production
  4. Architecture:

    • Asynchronous operations (@Async)
    • Proper DB indexing
    • Lazy loading of relationships

Q21. What is Spring Actuator and what useful endpoints does it provide?​

Expected Answer:

Spring Actuator provides monitoring and management endpoints:

EndpointDescription
/actuator/healthApplication status (UP/DOWN)
/actuator/infoApplication information
/actuator/metricsMetrics (memory, CPU, requests)
/actuator/envEnvironment variables
/actuator/beansList of all beans
/actuator/mappingsAll REST endpoints
/actuator/loggersLogger configuration
/actuator/prometheusMetrics 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:

  1. Actuator metrics: check /actuator/metrics/http.server.requests to identify slow endpoints
  2. Logs: enable logging.level.org.hibernate.SQL=DEBUG to see SQL queries
  3. N+1 problem: check the number of queries with spring.jpa.show-sql=true
  4. Connection pool: check HikariCP metrics (hikaricp.connections.active)
  5. Profiling: VisualVM or JFR (Java Flight Recorder)
  6. DB Index: analyze slow queries with EXPLAIN ANALYZE
  7. 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

⬅️ Back to home