Spring Boot Interview Questions and Answers (Spring Boot 3)
Last updated 2026-11-19
Spring Boot interviews for Java roles go well past "what is @SpringBootApplication". Interviewers want to know whether you understand what auto-configuration does, why a transactional method sometimes does not roll back, how a request travels through security filters and how you would expose health and metrics in production. This page covers those questions for Spring Boot 3.
Boot 3 sets the baseline at Java 17 and moves from the javax to the jakarta namespace, which shows up in imports for validation and persistence. For related persistence questions see Hibernate and JPA interview questions, and for the language side read how to crack a Java interview.
| Version covered | Spring Boot 3.x, Spring Framework 6, Java 17 and later |
|---|---|
| Core topics | Auto-configuration, DI, REST, transactions, Security 6, Actuator, testing |
| Questions here | 18 |
What changed in Boot 3
- Java 17 minimum, with Java 21 supported and virtual threads available from Boot 3.2.
- Jakarta EE 9 and later: javax.persistence becomes jakarta.persistence, and so on.
- Spring Security 6: configure a SecurityFilterChain bean, because WebSecurityConfigurerAdapter was removed.
- ProblemDetail support for RFC 9457 style error responses.
- RestClient, a modern synchronous client, was added in 6.1 and Boot 3.2.
- Native image support through GraalVM and Micrometer-based observability.
How to talk about Spring in an interview
Describe Spring as a container that creates objects and wires their dependencies, with Boot adding opinionated defaults. Most gotchas come from the proxy mechanism behind transactions, caching and security annotations. If you can explain proxies and the bean lifecycle simply, you will answer a large share of the follow-up questions correctly.
Spring Boot Interview Questions and Answers (Spring Boot 3): questions with worked answers
1 What does @SpringBootApplication do?
easyIt combines three annotations: @SpringBootConfiguration, which marks the class as a source of bean definitions, @EnableAutoConfiguration, which turns on auto-configuration, and @ComponentScan, which scans the package of the class and its sub-packages for components. That is why the main class should sit in a root package above your other packages.
2 What is a Spring starter?
easyA starter is a dependency descriptor that pulls in a curated, version-compatible set of libraries for a purpose. spring-boot-starter-web brings Spring MVC, Jackson and embedded Tomcat, and spring-boot-starter-data-jpa brings Hibernate and Spring Data JPA. The Boot parent or BOM manages versions, so you rarely specify them.
3 How does auto-configuration work?
mediumBoot reads the list of auto-configuration classes from META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports in each jar. Each class is guarded by conditions such as @ConditionalOnClass, @ConditionalOnMissingBean and @ConditionalOnProperty, so a DataSource is created only if a driver is on the classpath and you have not defined your own. Your own beans back off the defaults. Run with --debug to see the conditions report.
4 Constructor, setter or field injection?
mediumPrefer constructor injection. It makes dependencies explicit and final, allows the object to be created in tests without Spring, and makes circular dependencies fail fast. A single constructor needs no @Autowired. Field injection hides dependencies and requires reflection in tests, and setter injection suits optional dependencies only.
java@Service public class OrderService { private final OrderRepository repo; private final PaymentClient payments; public OrderService(OrderRepository repo, PaymentClient payments) { this.repo = repo; this.payments = payments; } }5 How do you build a REST controller with validation?
mediumUse @RestController with mapping annotations, bind and validate the body with @Valid and Jakarta Bean Validation constraints, and return ResponseEntity or a status annotation. Validation failures throw MethodArgumentNotValidException, which you translate into a 400 response in a @RestControllerAdvice. Prefer records for request DTOs instead of exposing entities.
javapublic record CreateUser(@NotBlank String name, @Email String email) {} @RestController @RequestMapping("/api/users") class UserController { @PostMapping ResponseEntity<UserDto> create(@Valid @RequestBody CreateUser req) { UserDto saved = service.create(req); return ResponseEntity.created(URI.create("/api/users/" + saved.id())).body(saved); } }6 How do you handle exceptions globally?
mediumUse @RestControllerAdvice with @ExceptionHandler methods. Boot 3 supports ProblemDetail, an RFC 9457 structure with type, title, status and detail, and setting spring.mvc.problemdetails.enabled=true gives standard handling for common Spring exceptions. Map domain exceptions to proper status codes, and never leak stack traces or SQL errors to the client.
java@RestControllerAdvice class ApiErrors { @ExceptionHandler(NotFoundException.class) ProblemDetail notFound(NotFoundException e) { return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, e.getMessage()); } }7 How does @Transactional work, and why might it not roll back?
mediumSpring wraps the bean in a proxy that begins a transaction before the method and commits or rolls back after it. By default only unchecked exceptions (RuntimeException and Error) trigger rollback, so a checked exception commits unless you set rollbackFor. Self-invocation, calling a transactional method from another method in the same class, bypasses the proxy so no transaction starts. Also, the method must be public on a Spring-managed bean.
java@Transactional(rollbackFor = Exception.class) public void transfer(long from, long to, BigDecimal amount) throws InsufficientFundsException { accounts.debit(from, amount); accounts.credit(to, amount); }8 What are bean scopes?
mediumsingleton is the default: one instance per container. prototype creates a new instance on every request for the bean. Web scopes are request, session and application. Singletons must be stateless or thread-safe because many requests share them. Injecting a prototype or request-scoped bean into a singleton needs a scoped proxy or ObjectProvider, otherwise it is injected only once.
9 How do profiles and externalised configuration work?
mediumapplication.properties or application.yaml holds defaults, and application-prod.yaml overrides them when the prod profile is active, set through spring.profiles.active or SPRING_PROFILES_ACTIVE. Environment variables and command-line arguments override files. Bind groups of properties to a typed class with @ConfigurationProperties, which can be validated and works well with records. Keep secrets out of the repo.
java@ConfigurationProperties(prefix = "app.mail") public record MailProps(@NotBlank String host, @Min(1) int port) {}10 What does Spring Boot Actuator provide?
mediumActuator adds production endpoints: /actuator/health with liveness and readiness probes for Kubernetes, /actuator/metrics, info, loggers and more. Only health is exposed over HTTP by default, so expose others deliberately with management.endpoints.web.exposure.include and secure them. Micrometer collects metrics, and registries export them to Prometheus and other systems.
11 How do you configure Spring Security 6?
hardDefine a SecurityFilterChain bean and configure HttpSecurity with the lambda DSL. WebSecurityConfigurerAdapter was removed. Declare authorisation rules, session policy and the authentication mechanism. For a stateless API disable sessions and use JWT resource server support. Add a PasswordEncoder bean such as BCryptPasswordEncoder. CSRF protection is on by default and is usually disabled only for stateless token APIs.
java@Bean SecurityFilterChain api(HttpSecurity http) throws Exception { http.csrf(csrf -> csrf.disable()) .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)) .authorizeHttpRequests(a -> a .requestMatchers("/actuator/health").permitAll() .requestMatchers("/api/admin/**").hasRole("ADMIN") .anyRequest().authenticated()) .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())); return http.build(); }12 What is the N+1 problem in Spring Data JPA and how do you fix it?
hardLoading a list of entities and then touching a lazy association on each one issues one extra query per entity. Fix it with a fetch join in a JPQL query, an @EntityGraph on the repository method, or batch fetching with hibernate.default_batch_fetch_size. Prefer DTO projections for read-only lists. Detect it by logging SQL or using a datasource proxy in tests.
javapublic interface OrderRepository extends JpaRepository<Order, Long> { @EntityGraph(attributePaths = "items") List<Order> findByCustomerId(Long customerId); }13 What is a circular dependency and how do you resolve it?
hardTwo beans that need each other through constructors cannot be created, and since Boot 2.6 circular references are prohibited by default and fail at startup. The real fix is a design change: extract the shared logic into a third bean, or publish an event instead of calling directly. @Lazy on one injection point or setter injection are workarounds, and the spring.main.allow-circular-references property is a last resort.
14 How do you test a Spring Boot application?
hardUse plain unit tests with Mockito for services. @WebMvcTest loads only the web layer and uses MockMvc with @MockBean, or @MockitoBean from Boot 3.4, for collaborators. @DataJpaTest loads repositories with an embedded or Testcontainers database. @SpringBootTest loads the full context for integration tests, and Testcontainers gives a real PostgreSQL or Kafka. Keep slices small, because full-context tests are slow.
java@WebMvcTest(UserController.class) class UserControllerTest { @Autowired MockMvc mvc; @MockitoBean UserService service; @Test void returns404() throws Exception { when(service.find(1L)).thenThrow(new NotFoundException("no user")); mvc.perform(get("/api/users/1")).andExpect(status().isNotFound()); } }15 What are virtual threads and how do you use them in Boot 3.2 and later?
hardVirtual threads, final in Java 21, are lightweight threads scheduled by the JVM, so a blocking call parks the virtual thread instead of a platform thread. On Java 21 set spring.threads.virtual.enabled=true and Boot runs Tomcat request handling and async tasks on virtual threads. It lets thread-per-request code scale for blocking I/O, but it does not speed up CPU-bound work, and pinned threads in synchronized blocks need attention.
16 How does Spring Boot start an embedded server and how do you change it?
hardBoot detects a web application and creates a servlet web server factory from the starter on the classpath. Tomcat is the default through spring-boot-starter-web, and the jar runs with java -jar. To use Jetty or Undertow, exclude the Tomcat starter and add the other one. Tune the port, thread pool and timeouts through server.* properties.
17 How do you secure and document an API for production release?
hardRequire authentication and authorisation on every route with deny by default, validate input, use HTTPS, restrict CORS to known origins, and add rate limiting at the gateway. Expose OpenAPI documentation with springdoc-openapi, keep Actuator endpoints private, and set up structured logging with correlation IDs. Add health probes, resource limits and graceful shutdown with server.shutdown=graceful.
Frequently asked questions
Is Spring Boot 3 different enough from 2 to matter in interviews?
Yes. Java 17, the jakarta namespace and the Security 6 configuration style all come up, and interviewers use them to see whether you work on current code.
What Java knowledge goes with Spring Boot?
Collections, streams, records, concurrency basics, exceptions and JVM memory, because Spring rounds usually include core Java too.
Are microservices questions part of Spring Boot interviews?
For experienced roles, yes: service discovery, API gateways, resilience patterns such as circuit breakers, and distributed tracing.
How do I practise Spring Boot for interviews?
Build one REST service with a database, validation, security, tests and Docker, and be ready to explain each annotation you used and why.
Related guides
More in Role-wise Interview Questions by Job and Tech Stack
- Statistics for Data Science Interview Questions and Answers
- Tableau Interview Questions and Answers
- Terraform Interview Questions and Answers
- Web Performance Interview Questions and Answers
- Web Security and OWASP Interview Questions and Answers
- A/B Testing Interview Questions and Answers
- Android Developer Interview Questions and Answers
- Angular Interview Questions and Answers (Angular 18 and Later)
- Ansible Interview Questions and Answers
- API Testing and Postman Interview Questions
- Automation Testing Interview Questions and Answers
- AWS Interview Questions and Answers