Spring Boot

Practice commonly asked Spring Boot interview questions with clear answers and explanations.

30 Interview Questions

Spring Boot Interview Questions

30 Questions
Q 31

How does Spring Boot 3.2+ integrate with Java 21 Virtual Threads?

Hard
Answer
By setting spring.threads.virtual.enabled=true in Spring Boot 3.2+ (on JDK 21+), Tomcat/Undertow and @Async TaskExecutors automatically use Virtual Threads (Executors.newVirtualThreadPerTaskExecutor()), enabling massive request concurrency for blocking I/O applications without rewriting code to reactive streams.
Explanation
A single property switch allows standard imperative Spring MVC applications to handle tens of thousands of concurrent requests seamlessly.
Code Example Java
# application.properties (Spring Boot 3.2+ on Java 21+)
spring.threads.virtual.enabled=true
Reference: Spring Boot
Q 32

How do you implement Global API Validation in Spring Boot using spring-boot-starter-validation?

Medium
Answer
Add spring-boot-starter-validation, annotate DTO fields with Jakarta validation annotations (@NotNull, @Size, @Email), annotate controller parameters with @Valid, and handle MethodArgumentNotValidException in a @RestControllerAdvice global exception handler.
Explanation
MethodArgumentNotValidException contains the BindingResult holding all field validation failure messages.
Code Example Java
public record UserRequest(
    @NotBlank(message = "Name required") String name,
    @Email(message = "Invalid email") String email
) {}

@RestControllerAdvice
public class ValidationHandler {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Map<String, String> handleErrors(MethodArgumentNotValidException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getFieldErrors().forEach(e -> errors.put(e.getField(), e.getDefaultMessage()));
        return errors;
    }
}
Reference: Spring Boot
Q 33

What is Spring Boot Testcontainers and how does it revolutionize integration testing?

Hard
Answer
Testcontainers provides lightweight, throwaway Docker instances of real databases (PostgreSQL, MySQL), message brokers (Kafka, RabbitMQ), or caches (Redis) during integration tests. Spring Boot 3.1+ provides @ServiceConnection for automated zero-config container property wiring.
Explanation
@ServiceConnection automatically configures Spring Boot DataSource/Kafka connection properties from the dynamic Docker port mapping.
Code Example Java
@SpringBootTest
@Testcontainers
class UserIntegrationTest {
    @Container
    @ServiceConnection // Boot 3.1+ auto-wires PostgreSQL connection settings
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:15-alpine");

    @Test
    void testDbOperation() { /* Tests run against real isolated PostgreSQL Docker instance */ }
}
Reference: Spring Boot
Q 34

What is the role of @EnableScheduling and @Scheduled in Spring Boot?

Medium
Answer
@EnableScheduling enables background task scheduling in the Spring context. Methods annotated with @Scheduled run on a background thread pool according to fixedRate, fixedDelay, or standard cron expressions.
Explanation
By default, Spring Boot uses a single-threaded TaskScheduler; configure a ThreadPoolTaskScheduler for concurrent schedule executions.
Code Example Java
@Configuration
@EnableScheduling
public class SchedulerConfig {}

@Component
public class ReportJob {
    // Runs at 2:00 AM every day
    @Scheduled(cron = "0 0 2 * * ?")
    public void generateDailyReport() {
        System.out.println("Daily report generated.");
    }
}
Reference: Spring Boot
Q 35

What is the difference between CrudRepository, PagingAndSortingRepository, and JpaRepository in Spring Boot?

Easy
Answer
CrudRepository provides basic CRUD operations. PagingAndSortingRepository extends CrudRepository, adding methods for pagination (Pageable) and sorting (Sort). JpaRepository extends PagingAndSortingRepository, adding JPA-specific batch operations (flush(), saveAllAndFlush(), deleteInBatch()).
Explanation
In modern Spring Data, JpaRepository is the standard choice as it inherits all paging, sorting, and CRUD features.
Code Example Java
public interface ProductRepository extends JpaRepository<Product, Long> {
    // Inherits findAll(Pageable), flush(), and saveAll()
}
Reference: Spring Boot
Q 36

How does Spring Boot 3+ support GraalVM Native Images (Ahead-of-Time / AOT compilation)?

Hard
Answer
Spring Boot 3 natively supports GraalVM Native Image compilation using Spring AOT engine. During build time, Spring AOT evaluates bean definitions, generates reflection/proxy hint metadata, and compiles Java bytecode into a standalone native OS binary with sub-50ms startup times and minimal memory footprint.
Explanation
Native images do not use a JVM at runtime and execute instantly, ideal for serverless function deployments.
Code Example Java
# Build native executable using Native Build Tools plugin:
# ./mvnw native:compile -Pnative
# Run compiled native binary:
# ./target/myapp
Reference: Spring Boot
Q 37

What is Distributed Tracing in Spring Boot 3+ (Micrometer Tracing & OpenTelemetry)?

Hard
Answer
In Spring Boot 3+, Spring Cloud Sleuth was replaced by Micrometer Tracing. It automatically propagates Trace ID (unique request identifier) and Span ID (operation unit) across distributed microservices via W3C/B3 headers and exports telemetry data to Zipkin or OpenTelemetry/Jaeger collectors.
Explanation
Micrometer Tracing correlates logs across multiple microservices by injecting traceId and spanId into the SLF4J MDC.
Code Example Java
# application.properties
management.tracing.sampling.probability=1.0
management.zipkin.tracing.endpoint=http://zipkin:9411/api/v2/spans
Reference: Spring Boot
Q 38

How do you create a Custom Spring Boot Starter?

Hard
Answer
A custom starter typically consists of two modules: 1. autoconfigure module containing auto-configuration classes, properties POJOs, and META-INF imports registration, and 2. starter module providing a single empty dependency descriptor POM that bundles required libraries.
Explanation
Custom starter naming convention: use foo-spring-boot-starter (third-party) rather than spring-boot-starter-foo (reserved for official Spring).
Code Example Java
// 1. Auto-configuration class
@AutoConfiguration
@EnableConfigurationProperties(MyProps.class)
public class MyAutoConfig {
    @Bean @ConditionalOnMissingBean
    public MyClient myClient(MyProps props) { return new MyClient(props.getApiKey()); }
}
// 2. Registered in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
Reference: Spring Boot
Q 39

How do you implement Spring Boot Graceful Shutdown?

Medium
Answer
Setting server.shutdown=graceful allows the embedded web server (Tomcat/Undertow) to stop accepting new requests during SIGTERM and wait for actively processing in-flight requests to finish up to spring.lifecycle.timeout-per-shutdown-phase.
Explanation
Graceful shutdown prevents HTTP 502/503 errors during rolling deployments in Kubernetes clusters.
Code Example Java
# application.properties
server.shutdown=graceful
spring.lifecycle.timeout-per-shutdown-phase=30s
Reference: Spring Boot
Q 40

How do you build Cloud-Native OCI container images using Spring Boot without a Dockerfile?

Medium
Answer
Spring Boot integrates with Cloud Native Buildpacks via Spring Boot Maven/Gradle plugins (mvn spring-boot:build-image). It generates optimized, layered Docker/OCI images with security best practices, JVM tuning, and layer caching without requiring a custom Dockerfile.
Explanation
Layered JARs separate dependencies, Spring Boot loader, and application code into distinct container image layers to minimize build time and transfer sizes.
Code Example Java
# Command to build production container image directly:
# mvn spring-boot:build-image -Dspring-boot.build-image.imageName=myapp:v1
Reference: Spring Boot
Q 41

What is an Executable Fat JAR in Spring Boot and how does LaunchedURLClassLoader run it?

Hard
Answer
An Executable Fat JAR packs application classes (BOOT-INF/classes) and nested dependency JARs (BOOT-INF/lib) into a single archive. The manifest sets Main-Class to org.springframework.boot.loader.JarLauncher, which initializes LaunchedURLClassLoader to load nested JARs without extraction.
Explanation
Standard Java classloaders cannot load classes directly from nested JARs inside JARs without unpacking; Spring Boot's custom loader solves this.
Code Example Java
# Manifest.MF entry inside Fat JAR
# Main-Class: org.springframework.boot.loader.launch.JarLauncher
# Start-Class: com.example.Application
Reference: Spring Boot
Q 42

What is Spring Boot DevTools and what features does it provide for developers?

Easy
Answer
spring-boot-devtools accelerates developer inner-loops by providing automatic application restarts upon classpath modifications (using dual classloaders: base and restart), LiveReload browser refresh, and automatic disabling of template caches (Thymeleaf).
Explanation
DevTools dependencies are automatically disabled when building production JAR packages (java -jar).
Code Example Java
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
    <optional>true</optional>
</dependency>
Reference: Spring Boot
Q 43

How does Spring Boot support Spring WebFlux for Reactive Asynchronous Microservices?

Hard
Answer
Spring Boot provides spring-boot-starter-webflux based on Project Reactor (Mono and Flux) and Netty server by default. It enables non-blocking, event-loop execution that handles massive concurrent connections with minimal threads and low memory footprint.
Explanation
WebFlux uses Netty instead of Tomcat and avoids blocking threads on downstream I/O.
Code Example Java
@RestController
@RequestMapping("/stream")
public class StreamController {
    @GetMapping(produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamEvents() {
        return Flux.interval(Duration.ofSeconds(1))
                   .map(seq -> "Event #" + seq);
    }
}
Reference: Spring Boot
Q 44

What is the role of @MockBean in Spring Boot tests?

Medium
Answer
@MockBean creates a Mockito mock instance of a specified bean and places it directly into the Spring ApplicationContext, replacing any existing real bean of that type for the duration of the test execution.
Explanation
Using @MockBean alters the ApplicationContext configuration, which can cause Spring TestContext framework to create a new cached context.
Code Example Java
@SpringBootTest
class OrderIntegrationTest {
    @Autowired private OrderService orderService;
    @MockBean private PaymentGateway paymentGateway; // Replaces real external gateway

    @Test
    void testCheckout() {
        Mockito.when(paymentGateway.charge(100.0)).thenReturn(true);
        assertTrue(orderService.checkout(100.0));
    }
}
Reference: Spring Boot
Q 45

What is the difference between @WebMvcTest, @DataJpaTest, and @SpringBootTest in Spring Boot testing?

Hard
Answer
@SpringBootTest loads the complete ApplicationContext for end-to-end integration tests. @WebMvcTest slices the web layer only (MockMvc, Controllers, Advice), mocking services with @MockBean. @DataJpaTest slices the persistence layer only, using an in-memory database and transactional test rollbacks.
Explanation
Test slicing (@WebMvcTest, @DataJpaTest) speeds up build pipelines significantly by skipping unnecessary context initialization.
Code Example Java
@WebMvcTest(UserController.class)
class UserControllerTest {
    @Autowired private MockMvc mockMvc;
    @MockBean private UserService userService;

    @Test
    void testGetUser() throws Exception {
        Mockito.when(userService.findById(1L)).thenReturn(new User(1L, "Alice"));
        mockMvc.perform(get("/users/1")).andExpect(status().isOk());
    }
}
Reference: Spring Boot
Q 46

How do you switch the Embedded Web Server in Spring Boot (e.g. Tomcat to Undertow or Jetty)?

Easy
Answer
Exclude spring-boot-starter-tomcat from the spring-boot-starter-web dependency and add spring-boot-starter-undertow or spring-boot-starter-jetty in your build file (pom.xml or build.gradle).
Explanation
Undertow is known for low memory footprint and high concurrent throughput in blocking I/O applications.
Code Example Java
<!-- pom.xml -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
Reference: Spring Boot
Q 47

What is Flyway / Liquibase database migration integration in Spring Boot?

Medium
Answer
Spring Boot integrates with Flyway and Liquibase for versioned database schema migrations. When spring-boot-starter-data-jpa is combined with Flyway, migration scripts (e.g. V1__init.sql in db/migration) run automatically on application startup before the DataSource/Hibernate initializes.
Explanation
Using database migration tools eliminates reliance on dangerous production ddl-auto=update.
Code Example Java
# Disable Hibernate schema creation, let Flyway manage DDL:
spring.jpa.hibernate.ddl-auto=validate
spring.flyway.enabled=true
# Scripts placed in: src/main/resources/db/migration/V1__create_tables.sql
Reference: Spring Boot
Q 48

What is the default Database Connection Pool in Spring Boot and how is HikariCP configured?

Medium
Answer
HikariCP is the default high-performance connection pool in Spring Boot (spring-boot-starter-data-jpa). It is tuned via spring.datasource.hikari properties (maximum-pool-size, minimum-idle, idle-timeout, connection-timeout).
Explanation
HikariCP is favored for its bytecode-level micro-optimizations and minimal lock contention.
Code Example Java
# application.properties
spring.datasource.hikari.maximum-pool-size=20
spring.datasource.hikari.minimum-idle=5
spring.datasource.hikari.idle-timeout=30000
spring.datasource.hikari.connection-timeout=20000
Reference: Spring Boot
Q 49

What is the N+1 Query Problem in Spring Data JPA / Hibernate and how is it solved?

Hard
Answer
The N+1 problem occurs when fetching parent entities (1 query) triggers separate queries (N queries) to fetch child relationships for each parent in lazy/eager loading loops. It is solved using JOIN FETCH queries, @EntityGraph, or Hibernate Batch Fetching (@BatchSize).
Explanation
@EntityGraph generates an outer join query to fetch lazy associations eagerly in a single database round-trip.
Code Example Java
public interface OrderRepository extends JpaRepository<Order, Long> {
    // Solution 1: JPQL JOIN FETCH
    @Query("SELECT o FROM Order o JOIN FETCH o.items WHERE o.status = :status")
    List<Order> findWithItems(@Param("status") String status);

    // Solution 2: @EntityGraph
    @EntityGraph(attributePaths = {"items"})
    List<Order> findAll();
}
Reference: Spring Boot
Q 50

How does Spring Data JPA simplify Repository creation in Spring Boot?

Easy
Answer
Spring Data JPA automatically implements repository interfaces at runtime (creating dynamic proxies) when extending JpaRepository<T, ID> or CrudRepository, generating CRUD operations, pagination, sorting, and derived query methods without writing boilerplate DAO implementation code.
Explanation
Derived query methods parse method names (e.g. findByEmailAndStatus) and automatically construct JPQL queries.
Code Example Java
public interface UserRepository extends JpaRepository<User, Long> {
    // Derived query method automatically generated:
    Optional<User> findByEmail(String email);
    List<User> findByAgeGreaterThan(int age, Pageable pageable);
}
Reference: Spring Boot
Q 51

What is the property loading precedence order in Spring Boot?

Hard
Answer
Spring Boot resolves properties in a strict priority order (higher overrides lower): 1. Command-line arguments (--server.port=8081), 2. SPRING_APPLICATION_JSON, 3. OS Environment Variables (SERVER_PORT=8081), 4. Profile-specific files (application-prod.properties), 5. Base config files (application.properties), 6. @PropertySource defaults.
Explanation
Command-line arguments always hold the highest precedence, making them ideal for container environment overrides.
Code Example Java
// Overriding via CLI parameter at startup:
// java -jar app.jar --server.port=9090 --spring.profiles.active=prod
Reference: Spring Boot
Q 52

How does Spring Boot Profile-based configuration work (@Profile, application-{profile}.properties)?

Easy
Answer
Spring Boot Profiles allow segregating environment-specific configurations (e.g. dev, test, prod). Properties defined in application-{profile}.properties override base application.properties when activated via spring.profiles.active or JVM args.
Explanation
Beans can be selectively registered using @Profile('prod') to instantiate specific implementations per environment.
Code Example Java
@Service
@Profile("dev")
public class MockPaymentService implements PaymentService {}

@Service
@Profile("prod")
public class ProductionPaymentService implements PaymentService {}
Reference: Spring Boot
Q 53

What is the difference between @ConfigurationProperties and @Value for binding configuration properties?

Medium
Answer
@Value is suitable for simple single-value injections with SpEL support. @ConfigurationProperties provides type-safe, hierarchical property binding to POJO classes with support for relaxed binding (camelCase, kebab-case), JSR-380 validation (@Validated), and complex nested structures.
Explanation
@ConfigurationProperties is strongly recommended for structured, multi-field application settings.
Code Example Java
@ConfigurationProperties(prefix = "app.mail")
@Validated
public record MailProperties(
    @NotBlank String host,
    @Min(1) int port,
    List<String> defaultRecipients
) {}
Reference: Spring Boot
Q 54

How do Liveness and Readiness state probes work in Spring Boot on Kubernetes?

Hard
Answer
Liveness Probe (/actuator/health/liveness) indicates if the internal application state is alive (if failed, Kubernetes restarts the pod container). Readiness Probe (/actuator/health/readiness) indicates if the application is ready to accept incoming traffic (if failed, Kubernetes removes the pod from service load balancers).
Explanation
AvailabilityChangeEvent can be published at runtime to dynamically mark readiness as OUT_OF_SERVICE during cache warmups or DB disruptions.
Code Example Java
@Autowired
private ApplicationEventPublisher eventPublisher;

public void pauseTraffic() {
    // Marks container unready without killing it
    AvailabilityChangeEvent.publish(eventPublisher, this, ReadinessState.REFUSING_TRAFFIC);
}
Reference: Spring Boot
Q 55

What is Spring Boot Actuator and what key production endpoints does it provide?

Medium
Answer
Spring Boot Actuator provides production-ready operational monitoring and management endpoints over HTTP/JMX. Key endpoints include: /actuator/health (liveness/readiness probes), /actuator/metrics (JVM/HTTP metrics via Micrometer), /actuator/env (environment properties), and /actuator/loggers (dynamic log level tuning).
Explanation
For security, only /health is exposed by default over HTTP; other endpoints must be explicitly enabled via management.endpoints.web.exposure.include.
Code Example Java
# application.properties
management.endpoints.web.exposure.include=health,metrics,info,loggers
management.endpoint.health.show-details=always
Reference: Spring Boot
Q 56

What are Spring Boot Starters and what is their primary purpose?

Easy
Answer
Spring Boot Starters are pre-packaged dependency descriptors (starter POMs) that aggregate commonly used transitively compatible libraries and version-managed dependencies for specific capabilities (e.g. spring-boot-starter-web, spring-boot-starter-data-jpa).
Explanation
Starters prevent dependency version conflicts by leveraging the Spring Boot Dependencies BOM (Bill of Materials).
Code Example Java
<!-- Web Starter includes Spring MVC, Jackson, Tomcat, and Validation -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
Reference: Spring Boot
Q 57

What are Spring Boot Conditional Annotations (@ConditionalOnProperty, @ConditionalOnClass, @ConditionalOnMissingBean)?

Medium
Answer
Conditional annotations control bean registration based on runtime checks: @ConditionalOnClass (registers if class exists on classpath), @ConditionalOnMissingBean (registers fallback bean only if user hasn't defined one), and @ConditionalOnProperty (registers bean based on application.properties values).
Explanation
They are the foundational building blocks of custom Spring Boot starters and auto-configuration classes.
Code Example Java
@Configuration
public class PaymentConfig {
    @Bean
    @ConditionalOnProperty(name = "payment.gateway", havingValue = "stripe", matchIfMissing = true)
    public PaymentGateway stripeGateway() { return new StripeGateway(); }
}
Reference: Spring Boot
Q 58

How does Spring Boot Auto-Configuration work internally and where are auto-configuration classes registered?

Hard
Answer
Auto-configuration scans META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports (or spring.factories in Boot 2.x) at startup via SpringFactoriesLoader. It evaluates conditional annotations (@ConditionalOnClass, @ConditionalOnMissingBean, etc.) and registers matching beans if conditions are satisfied.
Explanation
Auto-configuration is non-invasive: user-defined custom beans always override auto-configured default beans via @ConditionalOnMissingBean.
Code Example Java
@AutoConfiguration
@ConditionalOnClass(DataSource.class)
@ConditionalOnMissingBean(DataSource.class)
public class DataSourceAutoConfiguration {
    @Bean
    public DataSource defaultDataSource() { return new HikariDataSource(); }
}
Reference: Spring Boot
Q 59

What are the three core annotations combined inside @SpringBootApplication?

Easy
Answer
@SpringBootApplication combines: 1. @SpringBootConfiguration (indicates a primary Spring @Configuration class), 2. @EnableAutoConfiguration (enables automatic classpath bean configuration), and 3. @ComponentScan (enables component scanning from the current package and sub-packages).
Explanation
Placing @SpringBootApplication in the root package ensures all sub-packages are automatically scanned for @Component, @Service, and @Repository beans.
Code Example Java
// Equivalent to @SpringBootApplication:
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(basePackages = "com.example.app")
public class CustomApplicationConfig {}
Reference: Spring Boot
Q 60

What is Spring Boot and how does it differ from the core Spring Framework?

Easy
Answer
Spring Boot is an opinionated, convention-over-configuration framework built on top of Spring. It eliminates manual XML/Java configuration boilerplate through Auto-Configuration, provides Starter POM dependencies, and packages applications with Embedded Web Servers (Tomcat, Jetty, Undertow) into executable JARs.
Explanation
Spring Boot does not generate code; it configures Spring Beans automatically based on classpath libraries and property settings.
Code Example Java
@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
Reference: Spring Boot

About This Topic

Prepare for Spring Boot interviews with important concepts and commonly asked questions.