Spring Boot Interview Questions — Junior to Senior
50 Spring Boot and Java interview questions covering IoC/DI, JPA, Spring Security, transaction management, and system design patterns.
50 questions from junior to senior. These cover what Java interviewers actually ask — Spring internals, JPA gotchas, transaction behaviour, and design decisions.
Spring Core & IoC
1. What is Inversion of Control (IoC) in Spring?
Instead of objects creating their own dependencies, Spring creates and manages them. You declare what you need (@Autowired, constructor injection), and Spring provides it. The "control" of object creation is "inverted" from the class to the framework.
2. What is the Spring IoC container?
The ApplicationContext — it reads @Component, @Service, @Repository, @Controller, @Bean definitions, instantiates objects, injects dependencies, and manages their lifecycle.
3. What is the difference between @Component, @Service, @Repository, and @Controller?
All four are specialisations of @Component. They create Spring beans. The distinctions are semantic and functional: @Repository adds exception translation (JPA exceptions → Spring data exceptions). @Controller / @RestController marks MVC controllers. @Service is a marker for business logic. Use the most specific one that applies.
4. What is Spring Boot auto-configuration?
Spring Boot reads your dependencies and configures beans automatically. Add spring-boot-starter-data-jpa and Spring configures EntityManagerFactory, DataSource, and TransactionManager automatically. Add spring-boot-starter-security and basic security is enabled. You can override any auto-configuration with your own beans.
5. What is the difference between constructor injection and field injection? Which should you prefer?
Constructor injection (@RequiredArgsConstructor or explicit constructor) is preferred because: dependencies are explicit, the class is testable without Spring (just call the constructor), and required dependencies can be final. Field injection (@Autowired on a field) hides dependencies and requires reflection for testing.
6. What is a Spring Bean scope?
The lifecycle of a bean instance. Common scopes:
Singleton(default) — one instance per IoC containerPrototype— new instance every time requestedRequest— one instance per HTTP request (web-aware)Session— one instance per HTTP session
7. What is the difference between @SpringBootApplication and @EnableAutoConfiguration?
@SpringBootApplication is a combination of three annotations: @Configuration (Java config), @ComponentScan (scan for components), and @EnableAutoConfiguration (auto-configure based on classpath).
8. How does Spring Boot handle properties?
Through application.properties or application.yml. Values injected with @Value("${key}") or through @ConfigurationProperties classes. Spring Boot supports profiles — application-dev.properties, application-prod.properties — activated with spring.profiles.active.
Spring MVC & REST
9. What is the difference between @Controller and @RestController?
@RestController is @Controller + @ResponseBody. @ResponseBody tells Spring to serialise the return value to JSON (via Jackson) instead of resolving it as a view name.
10. How do you handle exceptions globally in Spring?
@RestControllerAdvice with @ExceptionHandler methods. Spring 6+ recommends returning ProblemDetail (RFC 9457) for standardised error responses.
11. What is @Valid vs @Validated?
@Valid triggers Bean Validation (JSR-380) on the annotated parameter. @Validated is Spring's variant that also supports validation groups and can be used on class level (for method-level validation).
12. How does Spring MVC handle content negotiation?
Based on the Accept header. Add produces = MediaType.APPLICATION_JSON_VALUE to @GetMapping to restrict to JSON. Add XML support with jackson-dataformat-xml. The ContentNegotiationStrategy selects the formatter.
13. What is Pageable in Spring Data?
A request abstraction for pagination and sorting — passed as a method parameter. Clients use ?page=0&size=20&sort=name,asc. Spring automatically maps this to a Pageable object. Returns a Page<T> with total count and page metadata.
Spring Data JPA
14. What is the difference between findById and getOne (now getReferenceById)?
findById returns Optional<T> and performs an immediate SQL SELECT. getReferenceById returns a proxy without hitting the database — a LazyLoadingException is thrown if you access a property outside a transaction. Use findById for most cases.
15. What are the JPA relationship types?
@OneToOne, @OneToMany, @ManyToOne, @ManyToMany. Define them with @JoinColumn (for FK) or @JoinTable (for many-to-many). Set cascade and orphanRemoval as needed.
16. What is the N+1 query problem in JPA?
Fetching a list of entities and then lazily loading a collection for each one:
List<Order> orders = orderRepository.findAll();
orders.forEach(o -> System.out.println(o.getItems().size())); // 1 + N queries!Fix: use JOIN FETCH in JPQL, @EntityGraph, or @Query with FETCH JOIN.
17. What is the difference between EAGER and LAZY loading?
LAZY (default for collections) loads data only when first accessed. EAGER loads data immediately in the same query. Always start with LAZY and use explicit JOIN FETCH when needed — EAGER causes unexpected queries.
18. What does @Transactional(readOnly = true) do?
Tells Hibernate it's a read-only transaction — it can skip dirty checking (no need to track entity changes), use read replicas, and flush is disabled. Use on all read-only service methods for better performance.
19. What happens if you call a @Transactional method from within the same class?
The transaction is bypassed. Spring's @Transactional uses a proxy — calling a method from within the same object bypasses the proxy. Fix: inject the bean into itself (@Autowired ApplicationContext), extract the method to a separate bean, or use @Transactional at class level.
20. What is optimistic locking in JPA?
Prevents lost updates when multiple transactions modify the same entity concurrently. Add a @Version field — JPA includes it in the WHERE clause of updates. If another transaction already updated the row, the version won't match and a OptimisticLockingFailureException is thrown.
21. What is the difference between save() and saveAndFlush()?
save() adds the entity to the persistence context — it may not be written to DB until the transaction commits or Hibernate decides to flush. saveAndFlush() forces an immediate write to DB within the same transaction. Use saveAndFlush() when you need the DB to reflect the change before the transaction ends (e.g., to check a unique constraint).
22. What is a JPQL query and how is it different from SQL?
JPQL (Java Persistence Query Language) operates on entity objects, not tables. FROM Product p WHERE p.category = :cat — Product is the entity class name, not the table name. JPQL is portable across databases; native SQL is not.
23. What is Specification in Spring Data JPA?
A pattern for building dynamic queries programmatically. Instead of a method per filter combination, you compose Specification<T> objects. Uses the JPA Criteria API under the hood. Good for complex search endpoints where the filter combination isn't known at compile time.
Spring Security
24. What is the Spring Security filter chain?
A series of Filter implementations that process every HTTP request before it reaches your controllers. Handles authentication (who are you?), authorisation (what can you do?), CSRF protection, session management, and more.
25. How do you configure JWT authentication in Spring Boot 3?
Define a SecurityFilterChain bean, add a custom JwtAuthFilter extends OncePerRequestFilter to the chain, and configure authorizeHttpRequests() with .requestMatchers():
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(AbstractHttpConfigurer::disable)
.sessionManagement(s -> s.sessionCreationPolicy(STATELESS))
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.build();
}26. What is UserDetailsService?
An interface with one method: loadUserByUsername(String username). Spring Security calls it during authentication to load user details (password, roles) from your database.
27. What is method-level security?
@EnableMethodSecurity enables annotations like @PreAuthorize("hasRole('ADMIN')") directly on service/controller methods — more granular than URL-level rules.
Performance & Design
28. What is connection pooling in Spring Boot?
Spring Boot uses HikariCP by default — a high-performance JDBC connection pool. Configure with spring.datasource.hikari.maximum-pool-size=20 (match your Postgres max_connections).
29. What is the difference between @Cacheable and @CacheEvict?
@Cacheable caches the return value of a method. On subsequent calls with the same arguments, the cached value is returned without executing the method. @CacheEvict removes entries from the cache — use it on create/update/delete methods to prevent stale cache.
30. How do you implement pagination efficiently?
Use Spring Data's Pageable — it generates LIMIT and OFFSET SQL. For very large datasets, cursor-based pagination is more performant: WHERE id > lastId ORDER BY id LIMIT 20 avoids the expensive OFFSET scan.
31. What is @Async and when should you use it?
Marks a method to run in a separate thread. Spring wraps it in a CompletableFuture. Use for fire-and-forget operations (sending email, pushing notifications) where the caller doesn't need to wait. Requires @EnableAsync on a config class.
32. What is a Spring Boot Actuator?
Production-ready endpoints: /actuator/health, /actuator/metrics, /actuator/info. Expose JVM metrics, database health, custom health indicators. Integrates with Prometheus/Grafana for monitoring.
Architecture & Best Practices
33. What is the difference between anemic domain model and rich domain model?
Anemic: entities are data bags with getters/setters; all logic is in service classes. Rich: entities contain business logic (e.g., order.ship() validates and changes state). Rich domain models are better for complex business logic; anemic is fine for simple CRUD.
34. When would you use @Transactional at the class level vs method level?
Class level marks all public methods as transactional — use in repositories or services where all methods need it. Method level is more targeted. Override class-level with @Transactional(readOnly = false) on specific write methods.
35. What is the difference between Spring Data REST and Spring MVC controllers?
Spring Data REST auto-exposes repositories as REST endpoints (HATEOAS style). Spring MVC controllers give you full control over response format, business logic, and validation. Prefer explicit controllers for production APIs — Spring Data REST is convenient for prototypes.
36. What is Flyway and why use it instead of spring.jpa.hibernate.ddl-auto=create?
Flyway manages database schema migrations with versioned SQL scripts. ddl-auto=create drops and recreates the schema on startup — never use in production (destroys data). Flyway tracks applied migrations and only runs new ones.
37. What is Spring's @Qualifier annotation?
When multiple beans of the same type exist, @Qualifier("beanName") specifies which one to inject. Alternatively, use @Primary on the preferred bean.
38. What is an ApplicationEvent and when would you use it?
Spring's internal event system. Publish events with ApplicationEventPublisher.publishEvent(event). Listeners use @EventListener. Good for decoupling — the payment service publishes OrderPaidEvent; the email service listens and sends a confirmation without the payment service knowing about email.
39. How do you write a unit test for a Spring service?
Don't load the full Spring context — mock dependencies:
@ExtendWith(MockitoExtension.class)
class ProductServiceTest {
@Mock ProductRepository productRepository;
@InjectMocks ProductService productService;
@Test void findById_returns_product() {
when(productRepository.findByIdAndActiveTrue(1L))
.thenReturn(Optional.of(new Product()));
assertNotNull(productService.findById(1L));
}
}40. What is @SpringBootTest and when should you use it?
Loads the full application context for integration testing. Slower than unit tests — use for testing the full stack (controller → service → repository → database). Use @WebMvcTest for controller-only tests, @DataJpaTest for repository tests.
Quick Study Guide
Must know cold:
@RestController, @RequestMapping, HTTP methods
@Valid + Bean Validation annotations
@Service, @Repository, @Transactional
@Transactional(readOnly=true) on reads
N+1 problem + JOIN FETCH fix
LAZY vs EAGER loading
Constructor injection (preferred over field injection)
@ExceptionHandler + @RestControllerAdvice
SecurityFilterChain + JWT auth filter
@Cacheable, @CacheEvict
Pageable + Page
Flyway over ddl-auto Found this helpful?
Leave a comment
Have a question, correction, or just found this helpful? Leave a note below.