
Spring Boot has revolutionized Java development by eliminating boilerplate code and providing opinionated defaults. For experienced developers, interviews go beyond basic @RestController annotations; interviewers expect a deep understanding of internal mechanisms, performance tuning, security, and microservices architecture.
In this guide, we dive into the most challenging Spring Boot interview questions tailored for senior engineers. Let's explore the intricacies of this powerful framework.
1. How does Spring Boot Auto-Configuration work under the hood?
Auto-configuration is the magic behind Spring Boot, but experienced developers need to explain the "how."
Spring Boot looks at the classpath, existing beans, and various property settings to conditionally configure beans. This is driven by the @EnableAutoConfiguration annotation, which imports AutoConfigurationImportSelector.
This selector reads the META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports (in Spring Boot 2.7+) or META-INF/spring.factories (in older versions) to find auto-configuration classes. These classes use @Conditional annotations (like @ConditionalOnClass, @ConditionalOnMissingBean, @ConditionalOnProperty) to determine if their beans should be created.
Follow-up Question: How can you disable a specific auto-configuration?
Answer: You can use the exclude attribute on @SpringBootApplication or @EnableAutoConfiguration, or use the spring.autoconfigure.exclude property in your application.properties/application.yml.

2. Explain the difference between @Component, @Service, @Repository, and @Controller. When should you use which?
While they all make a class a Spring-managed bean, they serve different semantic purposes and offer specific features.
@Component: The generic stereotype for any Spring-managed component. Use it when a class doesn't fall into the other specific categories.@Repository: Indicates that the class provides the mechanism for storage, retrieval, search, update, and delete operation on objects. Crucially, it enables automatic translation of vendor-specific data access exceptions into Spring's unifiedDataAccessExceptionhierarchy.@Service: Indicates that an annotated class is a "Service", originally defined by Domain-Driven Design as "an operation offered as an interface that stands alone in the model, with no encapsulated state." Currently, it doesn't provide additional behavior over@Componentbut clarifies intent.@Controller: Indicates that the annotated class is a web controller, typically used with@RequestMapping. Spring's component scanner automatically detects these.
3. What is the Spring IoC Container and how does Dependency Injection work?
Inversion of Control (IoC) is a principle where the control of object creation and lifecycle is transferred from the application code to a framework (the container). Spring's IoC container is responsible for instantiating, configuring, and assembling beans based on configuration metadata (XML, annotations, or Java code).
Dependency Injection (DI) is the pattern used to implement IoC. Instead of an object creating its dependencies, the container "injects" them at runtime.
Types of Dependency Injection:
- Constructor Injection: Dependencies are provided through the class constructor. (Recommended for mandatory dependencies).
- Setter Injection: Dependencies are provided through setter methods. (Useful for optional dependencies).
- Field Injection: Dependencies are injected directly into fields using
@Autowired. (Generally discouraged as it makes unit testing harder without a Spring context).

4. How do you handle exceptions globally in a Spring Boot REST API?
Senior developers are expected to implement clean, consistent error handling.
The standard approach is using @ControllerAdvice (or @RestControllerAdvice) along with @ExceptionHandler.
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorResponse> handleResourceNotFound(ResourceNotFoundException ex, WebRequest request) {
ErrorResponse error = new ErrorResponse(
HttpStatus.NOT_FOUND.value(),
ex.getMessage(),
LocalDateTime.now()
);
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorResponse> handleGlobalException(Exception ex, WebRequest request) {
ErrorResponse error = new ErrorResponse(
HttpStatus.INTERNAL_SERVER_ERROR.value(),
"An unexpected error occurred",
LocalDateTime.now()
);
return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
This creates a centralized point for handling specific exceptions and returning structured JSON error responses.
5. What are Spring Boot Actuator endpoints and how do you secure them?
Spring Boot Actuator provides built-in endpoints for monitoring and managing your application (e.g., /actuator/health, /actuator/metrics, /actuator/env, /actuator/beans).
Because these endpoints expose sensitive application data and operations, securing them is paramount.
How to secure them:
- Expose selectively: By default, only
/healthand/infoare exposed over HTTP. You must explicitly expose others usingmanagement.endpoints.web.exposure.include=*(or specific ones). - Spring Security: Use Spring Security to restrict access to actuator endpoints based on roles.
- Different Port: Configure actuator endpoints to run on a different HTTP port than the main application (
management.server.port), which can be firewalled off from public access.
Senior Spring Boot Scenarios: @Transactional Pitfalls, N+1 Queries & Actuator Readiness
For experienced backend engineers (4+ years), Spring Boot interviews focus heavily on proxy mechanics, JPA persistence bottlenecks, and Kubernetes cloud-native lifecycle management:
6. Why does calling a @Transactional method from another method inside the same class silently ignore the transaction?
Answer: Spring's declarative @Transactional (and @Async / @Cacheable) works by wrapping your bean in a runtime AOP Proxy (JDK Dynamic Proxy or CGLIB subclass). When an external bean calls orderService.createOrder(), the call passes through the proxy interceptor, which opens and commits the database transaction. However, when a method inside OrderService calls this.saveAuditLog() directly (self-invocation), this refers to the raw target instance, completely bypassing the Spring proxy!
- Fixes: Extract the transactional method into a separate collaborating
@Servicebean, or inject the self-proxy / useTransactionTemplateprogrammatically.
7. How do you detect and eliminate the Hibernate/JPA N+1 Select problem in production?
Answer: The N+1 problem occurs when 1 query fetches N parent entities (e.g., SELECT * FROM orders LIMIT 50) with FetchType.LAZY child collections, and iterating over order.getItems() fires N additional SELECT * FROM order_items WHERE order_id = ? queries.
- Fixes:
- Use JPQL
JOIN FETCH(SELECT o FROM Order o LEFT JOIN FETCH o.items) or declarative@EntityGraph(attributePaths = {"items"})on the Spring Data repository method. - For paginated queries (where
JOIN FETCHon collections forces Hibernate to paginate in memory withHHH90003004), use@BatchSize(size = 50)or Spring Data Projections (DTOs) so collections are fetched in a singleWHERE order_id IN (?, ?, ...)query.
- Use JPQL
8. Why does @Transactional NOT roll back on Checked Exceptions by default, and how do you configure Kubernetes Liveness vs. Readiness probes with Spring Boot Actuator?
Answer: By default, Spring's @Transactional only triggers an automatic database rollback on unchecked runtime exceptions (RuntimeException and Error), committing the transaction if a checked exception (such as IOException or a custom business Exception) is thrown! Always specify @Transactional(rollbackFor = Exception.class) when handling checked exceptions. In Kubernetes deployments, expose /actuator/health/liveness (which checks only whether the JVM/Spring context is wedged and needs a pod restart) separately from /actuator/health/readiness (which checks downstream DB/Kafka connectivity and temporarily removes the pod from Service load balancing without killing in-flight requests). Separating liveness from readiness prevents cascading cluster restarts whenever a shared downstream database experiences a brief network blip.
Conclusion
Mastering Spring Boot for senior roles requires looking under the hood. Understanding auto-configuration, robust exception handling, application monitoring, and the nuances of the IoC container will set you apart.
If you are preparing for your next big technical interview, practice these concepts thoroughly. For more interview preparation resources and mock interviews, check out totop.app, where you can simulate real interview environments and get immediate feedback. Good luck!
Practice Staff Backend Engineer Questions Live with AI Mock Interviews
Turn any job description across Engineering, DevOps, Data, Marketing, Sales, Finance, or HR into a personalized test and live voice or text AI mock interview on totop.app, or test your speed right now in the 60-Second Staff Backend Engineer Blitz.
Play 60s Staff Backend Engineer Blitz (Free, No Login) | Start 14-Day Free Trial | Browse All Interview Guides