Spring Boot Tutorial
Spring Boot Interview Questions and Answers
Spring Boot is one of the most requested skills in Java backend job descriptions, and interviews test both concepts and practical experience. This lesson collects the questions that come up most often — from fresher to senior level — with concise answers and, where useful, code. Use it for revision after completing the course; each answer links back to a topic you have studied in depth.
Try answering each question aloud before reading the answer. Interviewers value clear explanations of why and when as much as knowing what.
Fundamentals
Core questions asked in almost every Spring Boot interview:
- What is Spring Boot and how is it different from Spring? Spring is the framework (IoC, AOP, MVC, data); Spring Boot is an opinionated layer that adds starters, auto-configuration, embedded servers and production features so a Spring app runs with minimal configuration.
- What does @SpringBootApplication do? It combines @SpringBootConfiguration, @EnableAutoConfiguration and @ComponentScan of the class's package and sub-packages.
- How does auto-configuration work? Spring Boot loads auto-configuration classes listed in META-INF/spring/...AutoConfiguration.imports; each uses conditions (@ConditionalOnClass, @ConditionalOnMissingBean, @ConditionalOnProperty) to create beans only when appropriate and only if you have not defined your own.
- What are starters? Dependency descriptors (e.g. spring-boot-starter-webmvc) that bring a tested set of libraries for a feature, with versions managed by the Spring Boot BOM.
- How do you change the port? server.port in properties, --server.port on the command line, SERVER_PORT environment variable; 0 for a random port.
- What is the order of property sources? Command-line args > environment variables > profile-specific files > application files; files outside the jar override those inside.
- What are profiles? Named sets of configuration and beans (dev, test, prod) activated with spring.profiles.active; application-{profile}.yml overrides defaults.
- Which embedded servers are supported? Tomcat (default) and Jetty; Spring Boot 4 dropped Undertow; WebFlux uses Reactor Netty.
Dependency Injection and Beans
Container questions:
- Constructor vs field injection? Constructor injection is recommended: dependencies are explicit and final, objects are always fully initialised, and classes are easy to unit-test without Spring.
- @Component vs @Service vs @Repository vs @Controller? All are components for scanning; the names document the layer, and @Repository also translates persistence exceptions into DataAccessException.
- @Bean vs @Component? @Component marks your own classes for scanning; @Bean methods in @Configuration classes create beans from code you do not own or that need custom construction.
- How do you resolve two beans of the same type? @Primary for a default, @Qualifier("name") at the injection point, or inject a List/Map of all implementations.
- What are bean scopes? singleton (default), prototype, and web scopes request, session, application.
- What is a circular dependency and how do you fix it? Two beans needing each other in constructors; Spring Boot fails by default. Fix the design: extract a third component, use events, or rethink responsibilities.
Web, Data and Transactions
Everyday backend questions:
- @Controller vs @RestController? @RestController = @Controller + @ResponseBody, returning data (JSON) instead of view names.
- How do you handle exceptions globally? @RestControllerAdvice with @ExceptionHandler methods returning ProblemDetail (RFC 9457).
- How do you validate input? Bean Validation annotations on DTOs with @Valid on @RequestBody; errors become 400 responses.
- PUT vs PATCH? PUT replaces the whole resource (idempotent); PATCH applies a partial update.
- What is the N+1 problem? Loading N parents then lazily loading an association per parent. Fix with join fetch, @EntityGraph, batch fetching or DTO projections.
- How does @Transactional work? Through a proxy that begins and commits/rolls back around public method calls from other beans; by default it rolls back on unchecked exceptions only; self-invocation bypasses it.
- What does readOnly = true do? Tells Hibernate to skip dirty checking and lets drivers optimise or route to replicas.
- Why use DTOs? To decouple the API contract from entities, avoid leaking fields and lazy-loading issues, and shape responses per use case.
- Flyway vs ddl-auto=update? Flyway applies reviewed, versioned migrations reproducibly; ddl-auto=update is unsafe for production.
Security
Security questions show whether you can be trusted with production systems:
- Authentication vs authorization? Who you are vs what you may do; 401 vs 403.
- How is Spring Security configured today? With SecurityFilterChain beans and the lambda DSL; WebSecurityConfigurerAdapter was removed.
- How do you store passwords? Hashed with an adaptive algorithm through DelegatingPasswordEncoder (bcrypt/argon2), never encrypted or plain.
- How do you implement JWT authentication? Use the OAuth2 resource server support (oauth2ResourceServer().jwt()), short-lived access tokens, signature/expiry/issuer/audience validation — not a hand-written filter.
- When can CSRF be disabled? When authentication is not sent automatically by the browser (e.g. bearer tokens in headers); keep it for cookie/session-based apps.
- What is method security? @EnableMethodSecurity with @PreAuthorize/@PostAuthorize to protect service methods, including ownership checks.
Production, Testing and Architecture (Experienced Level)
Senior-level questions:
- What is Actuator? Production endpoints for health, metrics, info, loggers and more; expose only what you need, securely.
- Liveness vs readiness? Liveness = restart if broken (internal state only); readiness = whether to route traffic (may include dependencies).
- How do you test a Spring Boot app? Unit tests with Mockito; slices (@WebMvcTest, @DataJpaTest); integration tests with @SpringBootTest and Testcontainers via @ServiceConnection; @MockitoBean replaces removed @MockBean.
- What are virtual threads and when do they help? Lightweight JVM threads (Java 21+) enabled with spring.threads.virtual.enabled; they scale I/O-bound blocking code, not CPU-bound work.
- How do you make calls to other services resilient? Timeouts, @Retryable with back-off for transient failures, @ConcurrencyLimit, circuit breakers, fallbacks, idempotency keys.
- How do you keep data consistent across microservices? Sagas with compensating actions, the transactional outbox, idempotent consumers, eventual consistency.
- Monolith or microservices? Start with a modular monolith (Spring Modulith); split when independent deployment/scaling needs justify the operational cost.
- What is new in Spring Boot 4? Spring Framework 7, modular starters, Jackson 3, API versioning, HTTP service clients, core @Retryable, JSpecify null-safety, RestTestClient, OpenTelemetry starter; 4.1 adds gRPC.
- What is Spring AI? Spring's portable API for LLMs: ChatClient, structured output, chat memory, tool calling, embeddings/vector stores, RAG advisors and MCP support.
Examples
Q: Show how a custom auto-configuration backs off when the user defines a bean
@AutoConfiguration
@ConditionalOnClass(SmsClient.class)
public class SmsAutoConfiguration {
@Bean
@ConditionalOnMissingBean
SmsClient smsClient(@Value("${sms.api-key}") String key) {
return new DefaultSmsClient(key);
}
}
// In the application — this bean wins, the auto-configured one is skipped
@Bean
SmsClient smsClient() {
return new LoggingSmsClient();
}
Conditions evaluation report (--debug):
SmsAutoConfiguration#smsClient:
Did not match: @ConditionalOnMissingBean (types: SmsClient) found beans of type 'SmsClient' smsClient
Q: Why does this @Transactional not roll back? (classic trick question)
@Service
public class TransferService {
public void transfer(long from, long to, BigDecimal amount) {
doTransfer(from, to, amount); // 1. self-invocation: proxy bypassed, no transaction
}
@Transactional
public void doTransfer(long from, long to, BigDecimal amount) throws InsufficientFundsException {
debit(from, amount);
credit(to, amount);
if (balance(from).signum() < 0) {
throw new InsufficientFundsException(); // 2. checked exception: no rollback by default
}
}
}
Answer: two reasons —
1. transfer() calls doTransfer() on "this", so the transactional proxy never runs.
2. InsufficientFundsException is checked; default rollback applies only to RuntimeException/Error.
Fix: call through another bean (or put @Transactional on transfer), and use rollbackFor = Exception.class
or make the exception unchecked.
Q: Write a minimal secure REST endpoint with validation and global error handling
public record CreateCourse(@NotBlank String title, @Positive BigDecimal price) {}
@RestController
@RequestMapping("/api/courses")
class CourseController {
@PostMapping
@PreAuthorize("hasRole('ADMIN')")
ResponseEntity<Map<String, Object>> create(@Valid @RequestBody CreateCourse cmd) {
return ResponseEntity.status(HttpStatus.CREATED).body(Map.of("title", cmd.title()));
}
}
@RestControllerAdvice
class Errors extends ResponseEntityExceptionHandler {} // ProblemDetail for validation errors
@Configuration
@EnableMethodSecurity
class Security {
@Bean
SecurityFilterChain chain(HttpSecurity http) throws Exception {
return http.authorizeHttpRequests(a -> a.anyRequest().authenticated())
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))
.build();
}
}
POST /api/courses (no token) -> 401
POST /api/courses (USER token) -> 403
POST /api/courses (ADMIN, title "") -> 400 application/problem+json with field errors
POST /api/courses (ADMIN, valid body) -> 201 {"title":"Spring AI"}
Common Mistakes
- Memorising definitions without being able to explain trade-offs and when not to use a feature.
- Describing outdated practices (WebSecurityConfigurerAdapter, @MockBean, javax.*) as current.
- Answering "we used microservices" without explaining boundaries, data ownership and consistency.
- Not being able to explain a real bug you fixed — prepare two or three stories from your projects.
- Ignoring testing and production questions; senior roles weigh them heavily.
Key Points to Remember
- Know the fundamentals cold: auto-configuration, starters, @SpringBootApplication, properties and profiles.
- Explain proxies: why @Transactional, @Cacheable, @Async and @PreAuthorize fail on self-invocation.
- Be current: Spring Boot 4, Spring Security 7, Jackson 3, virtual threads, Spring AI.
- Show production thinking: testing strategy, observability, resilience and security.
- Back answers with concrete examples from projects such as the LearnHub capstone.
Practice the examples
Change an input, predict the result, then compare it with the output. Explain why the result changes.
Use your local JDK or project IDE for these examples. Codelab currently runs Python and HTML/CSS/JavaScript; framework examples may need project dependencies.