Spring Boot interview questions (2026): 20 answers from auto-configuration to production

· · 9 min read

A Spring Boot interview tests three things: how the container wires and proxies beans, why transactions or JPA queries misbehave under load, and how a service starts, reports health and shuts down in containers. Below are 20 questions grouped by level, with short answers you can say aloud and concise Java snippets. Facts were verified in November 2026 against the Spring Boot project page (where Spring Boot 4.2 is current alongside widely deployed Spring Boot 3.x services on Java 17 and 21+), the Spring Boot Reference and the Spring Framework Reference.

On this page

How Spring Boot questions are asked in 2026

Interviewers usually embed Spring Boot questions inside code reviews, debugging tasks or service design rounds. Pair this guide with Java interview questions, JUnit interview questions, SQL interview questions and Docker interview questions. Keep baselines straight: Spring Boot 3.0 moved to Java 17 and Jakarta EE jakarta.*; Spring Boot 4.x runs on Spring Framework 7 and Jakarta EE 11. Naming the right test slice early signals real project experience:

Spring Boot test slices compared against the official testing reference.
AnnotationBeans loadedDB transactionBest for
@WebMvcTestControllers, advice, filters, MockMvcNoneRouting, validation and JSON contracts with @MockitoBean
@DataJpaTestRepositories, EntityManager, DataSourceRolls back per testJPQL, @EntityGraph and SQL via Testcontainers
@RestClientTestRestClient/RestTemplate, Jackson, MockRestServiceServerNoneOutbound HTTP serialization and status handling
@SpringBootTestFull ApplicationContext (optional embedded server)Not rolled back on real portEnd-to-end wiring across security, DB and messaging

Junior Spring Boot interview questions

1. What does @SpringBootApplication combine, and why does its package matter?

It combines @SpringBootConfiguration, @EnableAutoConfiguration and @ComponentScan. Because component and entity scanning start from the main class's package downward, placing the application class outside your root package causes sibling packages to be silently ignored.

2. How does auto-configuration decide which beans to register?

Spring Boot loads candidates from META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports (replacing spring.factories since 2.7/3.0) and evaluates @ConditionalOnClass, @ConditionalOnMissingBean and @ConditionalOnProperty (Auto-configuration). Defining your own DataSource makes the default back off; --debug prints the conditions report.

3. Why is constructor injection preferred over @Autowired field injection?

Dependencies can be private final, circular dependencies fail at startup, and unit tests instantiate the class with new without booting Spring. Single-constructor beans do not need @Autowired.

@Service
public class PayoutService {
    private final LedgerRepository ledger;
    private final PaymentGateway gateway;

    public PayoutService(LedgerRepository ledger, PaymentGateway gateway) {
        this.ledger = ledger;
        this.gateway = gateway;
    }
}

4. What do Spring Boot starters and the BOM solve?

Starters like spring-boot-starter-web bundle compatible libraries (Spring MVC, Jackson, Tomcat), while spring-boot-dependencies pins tested transitive versions so upgrades do not trigger classpath conflicts.

5. When should you use @ConfigurationProperties instead of @Value?

@Value injects single expressions without relaxed binding or grouped validation. @ConfigurationProperties binds a prefix onto an immutable Java record and validates it with @Validated at startup (Externalized Configuration).

@Validated
@ConfigurationProperties(prefix = "app.http")
public record PartnerHttpProperties(
        @NotNull URI baseUrl,
        @NotNull Duration connectTimeout,
        @Positive int maxRetries
) {}

6. How do profiles and property precedence work?

spring.profiles.active (or SPRING_PROFILES_ACTIVE) activates profile-specific beans and application-{profile}.yml files. Command-line flags override OS environment variables, which override packaged config files — letting one immutable image run in every environment.

7. What changed in the javax.* to jakarta.* transition?

Spring Boot 3+ switched Java EE packages (javax.servlet, javax.persistence, javax.validation, javax.annotation) to jakarta.* (Jakarta EE 11 in Spring Boot 4). JDK packages like javax.sql.DataSource remain javax.*.

Mid-level Spring Boot interview questions

8. What are Spring's bean scopes, and what happens if a singleton injects a prototype?

Spring defines singleton (default), prototype, request, session, application and websocket (Bean Scopes). Direct constructor injection resolves a prototype once when the singleton is created; inject ObjectProvider<T> or a scoped proxy to obtain a new instance per call.

9. How does the bean lifecycle run, and where should startup logic live?

Constructor -> dependency injection -> BeanPostProcessor before-init -> @PostConstruct -> BeanPostProcessor after-init (where AOP proxies wrap the bean) -> @PreDestroy on close. Run startup I/O in ApplicationRunner rather than @PostConstruct so proxies are active (SpringApplication).

10. Why does @Transactional fail on self-invocation or checked exceptions?

Default Spring AOP uses proxies, so calling this.saveIsolated() inside the same bean bypasses the proxy and skips transaction advice (Using @Transactional). Also, Spring rolls back by default only on RuntimeException and Error; add rollbackFor = Exception.class for checked exceptions, and extract a collaborator bean or use TransactionTemplate.

@Service
public class InvoiceImportService {
    private final InvoiceWriter writer;
    public InvoiceImportService(InvoiceWriter writer) { this.writer = writer; }

    public void importAll(List<InvoiceCmd> batch) throws IOException {
        for (InvoiceCmd cmd : batch) writer.saveIsolated(cmd); // goes via proxy
    }
}

@Component
class InvoiceWriter {
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void saveIsolated(InvoiceCmd cmd) throws IOException { /* isolated tx */ }
}

11. How do you fix N+1 queries and Open-in-View issues in Spring Data JPA?

Loading N orders and lazily reading order.getItems() triggers N extra queries, while default spring.jpa.open-in-view=true holds DB connections open during JSON rendering. Set spring.jpa.open-in-view=false and load needed relations via @EntityGraph, JOIN FETCH or DTO projections (JPA Query Methods).

public interface OrderRepository extends JpaRepository<Order, UUID> {
    @EntityGraph(attributePaths = {"items", "customer"})
    Optional<Order> findWithDetailsById(UUID id);

    @Query("select o from Order o left join fetch o.items where o.status = :status")
    List<Order> findAllWithItemsByStatus(@Param("status") OrderStatus status);
}

12. Should new services use RestClient, WebClient, RestTemplate or JdbcClient?

Per REST Clients, RestClient is the fluent synchronous HTTP client and RestTemplate is now deprecated in Spring Framework 7 / Spring Boot 4; reserve WebClient for reactive streaming. For SQL without ORM overhead, JdbcClient unifies JdbcTemplate and named parameters fluently.

@Component
public class InventoryClient {
    private final RestClient rest;
    public InventoryClient(RestClient.Builder builder) {
        this.rest = builder.baseUrl("https://inventory.internal").build();
    }
    public StockDto fetchStock(String sku) {
        return rest.get().uri("/v1/stock/{sku}", sku).retrieve()
                .onStatus(HttpStatusCode::is4xxClientError, (q, r) -> { throw new SkuNotFoundException(sku); })
                .body(StockDto.class);
    }
}

13. How do you standardize API errors with @RestControllerAdvice and ProblemDetail?

Return RFC 9457 ProblemDetail from @RestControllerAdvice (or enable spring.mvc.problemdetails.enabled=true) so 404, 409 and validation failures emit consistent status, title and detail fields without leaking stack traces.

14. How do you combine slice tests with Testcontainers?

Test domain rules in plain JUnit, controllers in @WebMvcTest with @MockitoBean (which replaced @MockBean, deprecated in Boot 3.4; Testing reference), and SQL/migrations in @DataJpaTest or @SpringBootTest backed by real PostgreSQL via Testcontainers @ServiceConnection.

Senior Spring Boot interview questions

15. What does spring.threads.virtual.enabled=true change on Java 21+, and what can still break?

It switches Tomcat/Jetty request handling, @Async, @Scheduled and supported broker listeners onto JVM virtual threads so blocking JDBC or RestClient calls unmount cheaply. Watch three limits: CPU-bound tasks gain nothing, downstream DB pools need semaphores or rate limits so thousands of virtual threads do not pile onto 10 Hikari connections, and large ThreadLocal caches multiply per virtual thread.

spring:
  threads:
    virtual:
      enabled: true
  jpa:
    open-in-view: false
  lifecycle:
    timeout-per-shutdown-phase: 25s
management:
  endpoint:
    health:
      probes:
        enabled: true

16. How do Actuator liveness and readiness probes protect Kubernetes rollouts?

/actuator/health/readiness gates Service traffic during warmup or overload; /actuator/health/liveness tells kubelet whether to restart a wedged pod (Actuator Endpoints). Keep external DB and partner API checks out of liveness so a downstream blip never triggers cluster-wide pod restarts.

17. How does graceful shutdown work during rolling deployments?

Enabled by default in Spring Boot 3.4+ and 4.2 (older 2.3–3.3 releases needed server.shutdown=graceful), SIGTERM stops new network requests in early SmartLifecycle shutdown and lets active requests drain up to spring.lifecycle.timeout-per-shutdown-phase (default 30s; Graceful Shutdown). Set Kubernetes terminationGracePeriodSeconds higher than that timeout.

18. How do you wire Micrometer metrics and OpenTelemetry tracing cleanly?

Actuator auto-configures Micrometer and Micrometer Tracing with OTLP export. Always build HTTP clients from the injected RestClient.Builder so W3C traceparent headers propagate automatically, keep metric tags low-cardinality (never raw UUIDs), and tune management.tracing.sampling.probability from its 0.10 default.

@Service
public class CheckoutMetrics {
    private final MeterRegistry registry;
    public CheckoutMetrics(MeterRegistry registry) { this.registry = registry; }

    public void recordAttempt(String method, String outcome) {
        Counter.builder("checkout.attempts")
                .tag("method", method).tag("outcome", outcome)
                .register(registry).increment();
    }
}

19. How do you size HikariCP and prevent connection pool exhaustion?

HikariCP defaults to 10 connections per pod; multiplying large pools across replicas thrashes DB CPU and locks. Keep @Transactional strictly around fast SQL (never across RestClient calls), disable open-in-view, set query timeouts and alert on hikaricp.connections.pending.

20. When do Spring AOT and GraalVM native images beat the standard JVM?

Build-time AOT and GraalVM native-image deliver sub-100 ms startup and small RSS for scale-to-zero functions or CLIs, at the cost of slow builds, reflection RuntimeHints and lower peak throughput than HotSpot JIT. For long-lived services on Java 21–25, AppCDS or Leyden AOT caches trim startup while preserving full JVM profiling.

Where Interview Copilot fits

Interview Copilot is our desktop tool for mock practice and permitted live interviews. During practice calls it transcribes spoken Spring Boot questions and shows concise talking points — or serves as an AI coding interview assistant on coding tasks — so you can rehearse crisp 60-second answers. Always ask the recruiter before a live round what tools or notes are permitted, and use it only where allowed. The free tier includes 5 minutes of live recognition and 3 screenshot solutions, and Pro costs $25 for one month as a one-time payment with no subscription.

Sources

FAQ

What Spring Boot version do interviewers expect in 2026?

As of November 2026, Spring Boot 4.2 is the current release line on spring.io, while many production teams run Spring Boot 3.x on Java 17 or Java 21+. Know the Jakarta EE jakarta.* namespace baseline introduced in 3.0, virtual threads via spring.threads.virtual.enabled=true, RestClient replacing RestTemplate, and @MockitoBean replacing @MockBean.

Why does @Transactional not work when calling another method in the same class?

By default Spring implements @Transactional with runtime AOP proxies. Only calls entering through the proxy run the transaction interceptor; calling this.otherMethod() inside the same bean invokes the target instance directly and skips transaction advice. Move the transactional method into a separate collaborator bean or use TransactionTemplate.

Should I use RestClient, WebClient or RestTemplate in Spring Boot?

Use RestClient for synchronous HTTP calls: it offers WebClient's fluent style over standard blocking I/O (including Java virtual threads), and Spring Framework 7 officially deprecates RestTemplate in favor of RestClient. Choose WebClient when you need reactive streams or non-blocking backpressure.

What is the difference between @WebMvcTest and @SpringBootTest?

@WebMvcTest loads only the MVC web slice (controllers, advice, filters and MockMvc) so you stub services with @MockitoBean and verify HTTP contracts in milliseconds. @SpringBootTest starts the full ApplicationContext and is reserved for integration tests that verify real wiring across layers, often paired with Testcontainers.

Does enabling Java virtual threads in Spring Boot replace reactive WebFlux?

For most I/O-bound CRUD and microservice workloads on Java 21+, setting spring.threads.virtual.enabled=true delivers high concurrency with imperative blocking code and readable stack traces. WebFlux remains valuable for streaming pipelines, backpressure-aware event processing and reactive gateways.

Why should external database or API checks stay out of Kubernetes liveness probes?

Kubernetes restarts a pod when its liveness probe fails. If a transient database slowdown or downstream API outage fails liveness, Kubernetes restarts healthy pods across the cluster at once and amplifies the outage. Put traffic-gating checks in readiness and reserve liveness for unrecoverable internal deadlocks.

Related articles

More guides

Related articles

Read next

Interview Copilot is a desktop app

It's a desktop app for macOS, Windows and Linux — a phone cannot capture the interviewer's audio or hide a window from screen share. Open this page on your computer to install it.

And during the interview this phone can be your screen: scan the QR code in the laptop app and the answers appear right here. How phone mode works →