00:00

Spring Boot Interview Questions with Answers

Last updated:

These Spring Boot interview questions with answers cover what interviewers actually ask Java developers: how Spring Boot starts and configures itself, how to build and test REST APIs, how transactions and data access behave, and how to run applications in production. Good answers show that you understand why something works, not just which annotation to type.

The questions are grouped by topic, from basics to production, and every answer is up to date for Spring Boot 4.1 and Java 21. Where code helps, it comes from one small product API, with real output. A final section covers what changed in Spring Boot 4, which interviewers increasingly ask about.

1. How to Use These Spring Boot Interview Questions

Each answer starts with a short version you can say in one or two sentences, then adds the detail a follow-up question might need. Practise answering out loud before reading the answer. Questions in sections 2 to 5 come up for almost every role. Sections 6 to 9 separate developers with 1 to 3 years of experience from beginners.

2. Spring Boot Basics

2.1 What Is Spring Boot, and How Is It Different from the Spring Framework?

The Spring Framework provides the core features: dependency injection, transactions, web MVC and more. Spring Boot sits on top of it and removes the setup work. It brings auto-configuration (sensible beans created from what is on your classpath), starters (curated dependency sets), an embedded web server so the app runs as a plain java -jar, and production features through Actuator. In short: Spring is the engine, and Spring Boot is the engine already installed, tuned and ready to drive.

2.2 What Does @SpringBootApplication Do?

It combines three annotations:

  • @SpringBootConfiguration marks the class as a configuration class.
  • @EnableAutoConfiguration turns on auto-configuration.
  • @ComponentScan scans the class's package and all sub-packages for components.
ShopApplication.java
package com.javabytechie.shop;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;

@SpringBootApplication
@ConfigurationPropertiesScan
public class ShopApplication {

    public static void main(String[] args) {
        SpringApplication.run(ShopApplication.class, args);
    }
}

Because of the component scan, keep this class in the root package (here com.javabytechie.shop). Classes outside that package tree are not found.

2.3 What Is a Spring Boot Starter?

A starter is a dependency that brings a tested set of libraries for one capability. spring-boot-starter-webmvc, for example, pulls in Spring MVC, Jackson and Tomcat. Versions come from Spring Boot's dependency management, so you rarely write version numbers yourself, and the libraries are known to work together.

2.4 Which Embedded Servers Does Spring Boot Support?

Tomcat is the default for Spring MVC apps (Tomcat 11 in Spring Boot 4.1), and Jetty is the alternative. For reactive WebFlux apps, Reactor Netty is the default. Undertow was supported up to Spring Boot 3.5 but was dropped in Spring Boot 4. To switch servers, exclude spring-boot-starter-tomcat from the web starter and add the Jetty starter.

2.5 How Do You Change the Server Port?

Set server.port=9090 in application.properties, pass --server.port=9090 on the command line, or set the SERVER_PORT environment variable. server.port=0 picks a random free port, which is useful in tests.

2.6 @Component vs @Bean: What Is the Difference?

@Component (and @Service, @Repository, @Controller)@Bean
Placed onYour own classA method in a @Configuration class
Found byComponent scanningCalling the method
Typical useClasses you writeThird-party classes, or beans that need custom creation logic

2.7 Why Is Constructor Injection Preferred?

Dependencies passed through the constructor can be final, so the object is never half-built. Missing beans fail at startup, tests can create the class with new, and a long constructor is an honest warning that the class does too much. Since Spring 4.3, a class with a single constructor needs no @Autowired at all. Field injection hides dependencies and makes testing harder.

3. Auto-Configuration and Starters

3.1 How Does Spring Boot Auto-Configuration Work?

At startup, Spring Boot reads a list of candidate configuration classes from META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports in every jar on the classpath. Each candidate is guarded by conditions, such as "this class is on the classpath" or "no bean of this type exists yet". Only candidates whose conditions pass are applied, and your own beans are registered first, so auto-configuration backs off when you define a bean yourself.

How Spring Boot auto-configuration decides which beans to createSpringApplication.run first registers your own beans from component scanning and @Bean methods, then loads candidate configurations from the AutoConfiguration.imports files in every jar. Each candidate is checked against its conditions, such as whether a class is present, a bean is missing or a property is set. Matched candidates register their beans; unmatched ones are skipped, which is how auto-configuration backs off when you define your own bean. Finally the embedded server, Tomcat on port 8080 by default, starts. SpringApplication .run(...) 1. Your beans component scan and @Bean methods 2. Candidates AutoConfiguration.imports in every jar 3. Check conditions class present? bean missing? property set? Matched beans registered Not matched: skipped e.g. you defined the bean, so it backs off 4. Embedded server starts Tomcat on port 8080
Figure 1: auto-configuration candidates are applied only when their conditions match, so your own beans always take priority.
Version note: before Spring Boot 2.7, auto-configurations were listed in META-INF/spring.factories. That location stopped working for auto-configuration in Spring Boot 3.0.

3.2 Which Conditional Annotations Should You Know?

AnnotationApplies the configuration when
@ConditionalOnClassA class is on the classpath
@ConditionalOnMissingBeanNo bean of the type exists yet (this is how backing off works)
@ConditionalOnBeanA bean of the type exists
@ConditionalOnPropertyA property has a given value
@ConditionalOnWebApplicationThe app is a web application

You can use the same annotations on your own beans. This one is created only when shop.notifications.enabled=true:

NotificationConfig.java
package com.javabytechie.shop;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class NotificationConfig {

    private static final Logger log = LoggerFactory.getLogger(NotificationConfig.class);

    // Created only when shop.notifications.enabled=true
    @Bean
    @ConditionalOnProperty(name = "shop.notifications.enabled", havingValue = "true")
    public Runnable lowStockNotifier() {
        return () -> log.info("Sending low-stock alerts");
    }
}

3.3 How Do You See Which Auto-Configurations Were Applied?

Start the app with --debug (or debug=true), and Spring Boot prints a conditions evaluation report listing every candidate and why it matched or not, including your own conditional beans:

Console (./mvnw spring-boot:run -Dspring-boot.run.arguments=--debug, shortened)
Positive matches:
-----------------

   JacksonAutoConfiguration matched:
      - @ConditionalOnClass found required class 'tools.jackson.databind.json.JsonMapper' (OnClassCondition)

Negative matches:
-----------------

   AopAutoConfiguration.AspectJAutoProxyingConfiguration:
      Did not match:
         - @ConditionalOnClass did not find required class 'org.aspectj.weaver.Advice' (OnClassCondition)

   NotificationConfig#lowStockNotifier:
      Did not match:
         - @ConditionalOnProperty (shop.notifications.enabled=true) did not find property 'shop.notifications.enabled' (OnPropertyCondition)

In a running app, the Actuator conditions endpoint shows the same report, once you expose it.

3.4 How Do You Turn Off a Specific Auto-Configuration?

Usually you don't need to: define your own bean and the auto-configured one backs off. To remove one completely, use @SpringBootApplication(exclude = SomeAutoConfiguration.class) or the spring.autoconfigure.exclude property.

4. Configuration and Profiles

4.1 In What Order Does Spring Boot Read Configuration?

Later sources override earlier ones. The ones that matter day to day, from lowest to highest: application.properties inside the jar, profile-specific files such as application-prod.properties, files outside the jar, environment variables, Java system properties, and command-line arguments. So SERVER_PORT=9090 beats the port written in the jar.

4.2 @Value vs @ConfigurationProperties

@Value@ConfigurationProperties
BindsOne valueA whole group under a prefix
Type safetyBasic conversionFull binding to records, lists, maps, Duration
Relaxed binding (low-stock-threshold to lowStockThreshold)LimitedYes
ValidationNoYes, with @Validated
ShopProperties.java and application.properties
package com.javabytechie.shop;

import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "shop")
public record ShopProperties(String currency, int lowStockThreshold) {
}

// application.properties
// shop.currency=INR
// shop.low-stock-threshold=5

// Registered by @ConfigurationPropertiesScan on ShopApplication, then injected:
// public InventoryService(ShopProperties shop) { ... shop.lowStockThreshold() ... }

The configuration properties tutorial covers binding in depth.

4.3 What Are Profiles?

A profile is a named set of configuration, such as dev or prod. Activate one with spring.profiles.active=prod (or the SPRING_PROFILES_ACTIVE variable), and Spring Boot loads application-prod.properties on top of the defaults. Beans can also be limited to a profile with @Profile("prod").

5. Building REST APIs

5.1 @Controller vs @RestController

@RestController is @Controller plus @ResponseBody: every method's return value is written to the response body as JSON. With plain @Controller, return values are treated as view names for a template engine unless the method has @ResponseBody.

5.2 @PathVariable vs @RequestParam

@PathVariable reads part of the path (/api/products/KB-100) and identifies a resource. @RequestParam reads the query string (/api/products?category=keyboards) and usually filters, sorts or pages.

5.3 How Do You Validate a Request Body?

Add spring-boot-starter-validation, put Jakarta Validation constraints on the request record, and mark the parameter with @Valid. Invalid input is rejected with 400 Bad Request before your code runs:

package com.javabytechie.shop.product;

import java.math.BigDecimal;

import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Positive;
import jakarta.validation.constraints.PositiveOrZero;

public record CreateProductRequest(
        @NotBlank String sku,
        @NotBlank String name,
        @NotNull @Positive BigDecimal price,
        @PositiveOrZero int stock) {
}
Terminal
curl -i -X POST http://localhost:8080/api/products \
  -H "Content-Type: application/json" \
  -d '{"sku":"","name":"Desk Lamp","price":-5,"stock":3}'

HTTP/1.1 400
Content-Type: application/problem+json
{"detail":"Invalid request content.","instance":"/api/products","status":400,"title":"Bad Request"}

5.4 How Do You Handle Exceptions Globally?

A @RestControllerAdvice class with @ExceptionHandler methods handles exceptions from all controllers in one place. Returning a ProblemDetail produces the standard RFC 9457 error format (application/problem+json):

package com.javabytechie.shop.product;

import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
public class ApiExceptionHandler {

    @ExceptionHandler(ProductNotFoundException.class)
    public ProblemDetail handleNotFound(ProductNotFoundException ex) {
        return ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
    }
}
Terminal
curl -i http://localhost:8080/api/products/XX-1

HTTP/1.1 404
Content-Type: application/problem+json
{"detail":"Product not found: XX-1","instance":"/api/products/XX-1","status":404,"title":"Not Found"}

spring.mvc.problemdetails.enabled=true makes Spring's own errors, such as the validation failure in 5.3, use the same format. It is false by default. The exception handling tutorial covers this in detail.

5.5 How Do You Version a REST API in Spring Boot 4?

Spring Framework 7 added built-in API versioning. Declare where the version comes from, such as a header, and add version to the mappings:

PriceController.java, application.properties and Terminal
// application.properties
// spring.mvc.apiversion.use.header=API-Version
// spring.mvc.apiversion.default=1.0

@RestController
@RequestMapping("/api/prices")
public class PriceController {

    @GetMapping(path = "/{sku}", version = "1.0")
    public Map<String, Object> priceV1() {
        return Map.of("sku", "KB-100", "price", 89.00);
    }

    @GetMapping(path = "/{sku}", version = "2.0")
    public Map<String, Object> priceV2() {
        return Map.of("sku", "KB-100", "amount", 89.00, "currency", "INR");
    }
}

// curl localhost:8080/api/prices/KB-100                          -> {"sku":"KB-100","price":89.0}
// curl -H "API-Version: 2.0" localhost:8080/api/prices/KB-100    -> {"amount":89.0,"sku":"KB-100","currency":"INR"}
// curl -H "API-Version: 3.0" localhost:8080/api/prices/KB-100    -> 400 "Invalid API version: '3.0.0'."

6. Data Access and Transactions

6.1 What Does Spring Data JPA Give You?

You declare a repository interface such as interface ProductRepository extends JpaRepository<Product, Long>, and Spring generates the implementation at runtime. It provides CRUD methods, paging and sorting, queries derived from method names (findBySku) and custom queries with @Query, all on top of JPA and Hibernate.

6.2 How Does @Transactional Work?

Spring wraps the bean in a proxy. The proxy starts a transaction before the method, commits it after a normal return, and rolls back when the method throws a runtime exception or Error. Checked exceptions do not roll back unless you add rollbackFor. The transaction management tutorial explains propagation and isolation.

6.3 Why Is My @Transactional Method Not Working?

The most common reasons:

  • Self-invocation. A call from one method to another in the same class doesn't go through the proxy, so the annotation on the called method is ignored.
  • Private methods. A proxy can't intercept a private method, so @Transactional on it has no effect.
  • Caught exceptions. If the method catches the exception itself, the proxy never sees it and commits.
  • Checked exceptions. They commit by default, as described in 6.2.

6.4 What Is the N+1 Problem?

Loading a list of entities with one query, then triggering one more query per entity through a lazy relationship. Fix it per use case with a fetch join, an entity graph or a DTO projection, rather than switching relationships to EAGER.

6.5 What Is Open Session in View, and Should You Disable It?

spring.jpa.open-in-view is true by default and keeps the database session open until the web response is written, so lazy relationships can load in controllers and during JSON serialization. Spring Boot logs a warning about it at startup. Many teams set it to false, so all data access stays in the service layer and hidden queries can't happen in the view.

7. Testing Spring Boot Applications

7.1 @SpringBootTest vs @WebMvcTest vs @DataJpaTest

AnnotationLoadsUse for
@SpringBootTestThe whole application contextIntegration tests across layers
@WebMvcTestOnly the web layer: controllers, advice, converters, MockMvcController tests, with services mocked
@DataJpaTestOnly JPA: entities, repositories, an embedded databaseRepository and query tests, rolled back after each test

These "test slices" start in a fraction of the time a full context needs. See the Spring Boot testing tutorial for more.

7.2 What Replaced @MockBean?

@MockBean was deprecated in Spring Boot 3.4 and removed in Spring Boot 4. Use Spring Framework's @MockitoBean (and @MockitoSpyBean instead of @SpyBean). This @WebMvcTest mocks the service and checks the success, 404 and validation cases:

ProductControllerTest.java
package com.javabytechie.shop.product;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import java.math.BigDecimal;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.bean.override.mockito.MockitoBean;
import org.springframework.test.web.servlet.MockMvc;

@WebMvcTest(ProductController.class)
class ProductControllerTest {

    @Autowired
    private MockMvc mockMvc;

    @MockitoBean
    private ProductService productService;

    @Test
    void returnsProductWhenFound() throws Exception {
        given(productService.findBySku("KB-100"))
                .willReturn(new Product("KB-100", "Mechanical Keyboard", new BigDecimal("89.00"), 42));

        mockMvc.perform(get("/api/products/KB-100"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.name").value("Mechanical Keyboard"));
    }

    @Test
    void returns404ProblemDetailWhenMissing() throws Exception {
        given(productService.findBySku("XX-1")).willThrow(new ProductNotFoundException("XX-1"));

        mockMvc.perform(get("/api/products/XX-1"))
                .andExpect(status().isNotFound())
                .andExpect(jsonPath("$.detail").value("Product not found: XX-1"));
    }

    @Test
    void rejectsInvalidProductWithoutCallingTheService() throws Exception {
        mockMvc.perform(post("/api/products")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content("""
                                {"sku":"","name":"Desk Lamp","price":-5,"stock":3}
                                """))
                .andExpect(status().isBadRequest());

        verify(productService, never()).create(any());
    }
}

In Spring Boot 4, @WebMvcTest lives in org.springframework.boot.webmvc.test.autoconfigure and needs the spring-boot-starter-webmvc-test dependency.

8. Production Readiness

8.1 What Is Spring Boot Actuator, and Which Endpoints Are Exposed by Default?

Actuator adds operational endpoints: health, metrics, info, environment, loggers and more. Over HTTP, only health is exposed by default. Everything else must be listed in management.endpoints.web.exposure.include, and sensitive endpoints such as env should stay protected. In the example app:

Terminal
curl http://localhost:8080/actuator/health
{"groups":["liveness","readiness"],"status":"UP"}

curl -o /dev/null -w "%{http_code}" http://localhost:8080/actuator/info
404

curl -o /dev/null -w "%{http_code}" http://localhost:8080/actuator/env
404

The Spring Boot Actuator tutorial covers configuration and security.

8.2 What Happens When a Spring Boot App Is Stopped?

Graceful shutdown is on by default for the embedded web server. On a stop signal, the server stops accepting new requests and waits for in-flight ones, up to spring.lifecycle.timeout-per-shutdown-phase (30 seconds by default), then closes the context. Make sure your platform waits at least that long before killing the process.

8.3 How Do You Enable Virtual Threads?

On Java 21 or later, set spring.threads.virtual.enabled=true (it is false by default). Tomcat then handles each request on a virtual thread, and Spring's task executors use them too. Blocking code then scales to many more concurrent requests without a reactive rewrite.

9. What's New in Spring Boot 4

"What changed in the latest version?" is a favourite question. The key points for Spring Boot 4 (4.1 at the time of writing):

AreaSpring Boot 4
FoundationSpring Framework 7, Jakarta EE 11, Java 17 minimum (Java 21+ recommended)
Modules and startersSplit into smaller modules; the web starter is now spring-boot-starter-webmvc, and test support has per-technology starters such as spring-boot-starter-webmvc-test
JSONJackson 3 by default (package tools.jackson)
TestingJUnit Jupiter 6; @MockBean and @SpyBean removed in favour of @MockitoBean and @MockitoSpyBean
ServersTomcat 11 and Jetty; Undertow support removed
HTTP clientsHTTP service clients with @ImportHttpServices; RestTemplate deprecation announced in favour of RestClient
RESTBuilt-in API versioning (spring.mvc.apiversion.*)
ActuatorLiveness and readiness probes enabled by default
Data and batchHibernate 7 and Spring Batch 6

10. Tips for Answering Spring Boot Interview Questions

  • Lead with a one-sentence answer, then add detail only if the interviewer wants more.
  • Explain the mechanism, such as proxies, conditions and property precedence, not just the annotation name.
  • Mention the trade-off: when you would not use something is often the real question.
  • Use a concrete example from a project, such as "our order service" or "a nightly import", to show real experience.
  • Know the current version, and say which version your answer applies to when behaviour changed (for example @MockBean).
  • Admit what you don't know, and explain how you would find out, for example with --debug or the Actuator endpoints.
  • Practise writing code without an IDE: a controller, a service with constructor injection and a test.

11. Summary

These Spring Boot interview questions with answers cover the topics that come up most: what Spring Boot adds on top of Spring, how auto-configuration uses conditions and backs off for your beans, how configuration and profiles are layered, how to build, validate and version REST APIs with consistent Problem Details errors, how transactions and Spring Data JPA behave, how to test with slices and @MockitoBean, how Actuator, graceful shutdown and virtual threads support production, and what changed in Spring Boot 4. The main recommendation: understand the mechanism behind each feature and practise explaining it in your own words with a short example. That is what interviewers are really testing.