Spring Boot interview questions: auto-configuration, JPA, transactions and Boot 3
Spring Boot interview questions test whether you know what the framework does for you and what it hides: auto-configuration and starters, dependency injection and bean scopes, externalized configuration and profiles, Actuator, Spring Data JPA and how @Transactional really works. Experienced rounds add debugging questions (a bean that is not created, a transaction that does not roll back, an N+1 query) and the move to Spring Boot 3 with Java 17 and the jakarta namespace. Explain the mechanism behind each annotation, not just its name.
By Evin JohnPublished 8 min read
How Spring Boot shows up in interviews
Java backend interviews in many companies are, in practice, Spring Boot interviews. A typical loop opens with core Java, then moves to framework questions: what happens at startup, how a request reaches your controller, how configuration is resolved. Then come JPA and transactions, where most production bugs live, then testing. Many interviews include a short practical task such as building a small REST endpoint with validation and a repository, or reviewing a service class with a hidden transaction bug. Senior candidates are asked to justify choices: why this starter, why this transaction boundary, why not a different framework.
Fundamentals: Boot, starters and auto-configuration
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Spring versus Spring Boot? | Positioning | Spring Framework provides dependency injection, MVC, data access and more. Spring Boot is an opinionated layer on top: starters, auto-configuration, an embedded server and production features, so an app runs with very little setup. |
What does @SpringBootApplication combine? | Annotations | @SpringBootConfiguration (a @Configuration), @EnableAutoConfiguration and @ComponentScan of the annotated class's package and its subpackages. |
| What is a starter? | Dependencies | A dependency that pulls in a curated, version-aligned set of libraries for one purpose, such as spring-boot-starter-web or spring-boot-starter-data-jpa. Versions come from Boot's dependency management. |
| How does auto-configuration decide what to create? | Mechanism | Boot loads auto-configuration classes listed in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. Each is guarded by conditions such as @ConditionalOnClass, @ConditionalOnProperty and @ConditionalOnMissingBean, so it backs off when you define your own bean. |
| How do you see why an auto-configuration did or did not apply? | Debugging | Run with --debug to print the conditions evaluation report, or use the Actuator conditions endpoint. |
| How do you exclude an auto-configuration? | Control | @SpringBootApplication(exclude = ...) or the spring.autoconfigure.exclude property. |
| Which embedded server is used, and can you change it? | Runtime | Tomcat by default with the web starter. Exclude it and add the Jetty starter to switch (Spring Boot 3 also offers an Undertow starter); the reactive web starter uses Netty. |
| What happens when a Spring Boot app starts? | Startup | SpringApplication.run creates the environment (properties, profiles), creates the application context, runs component scanning and auto-configuration, instantiates singleton beans, starts the embedded server and calls runners such as CommandLineRunner. |
@AutoConfiguration
@ConditionalOnClass(PricingClient.class)
@EnableConfigurationProperties(PricingProperties.class)
public class PricingAutoConfiguration {
@Bean
@ConditionalOnMissingBean
PricingClient pricingClient(PricingProperties props) {
return new PricingClient(props.baseUrl(), props.timeout());
}
}
// Registered in:
// src/main/resources/META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
// com.example.pricing.PricingAutoConfigurationDependency injection, beans and scopes
- What is inversion of control, and how does Spring do it? Objects do not create their dependencies; the container builds them and passes them in. Spring's
ApplicationContextreads bean definitions, resolves dependencies and manages lifecycles. - Constructor, setter or field injection? Constructor injection is preferred: dependencies can be final, the class is easy to test without Spring, and missing dependencies fail at startup. With a single constructor, no
@Autowiredis needed. - `@Component` versus `@Bean`?
@Component(and@Service,@Repository,@Controller) marks your own classes for scanning.@Beanmethods in a@Configurationclass create beans you construct yourself, often for third-party classes. - Two beans of the same type: how does Spring pick? It fails with an ambiguity error unless one is
@Primary, the injection point uses@Qualifier, or the parameter name matches a bean name. You can also inject aListof all of them. - What bean scopes exist? Singleton (default, one per context), prototype (new instance per injection or lookup), and the web scopes request, session and application, plus websocket.
- What happens when a singleton depends on a prototype? The prototype is injected once, so the singleton keeps the same instance. Use an
ObjectProvider, a lookup method or a scoped proxy to get a fresh one each time. - Are singleton beans thread safe? Not automatically. One instance serves every request thread, so mutable fields are shared state. Keep beans stateless or protect the state.
- What is the bean lifecycle? Instantiation, dependency injection, aware callbacks,
BeanPostProcessorbefore-init,@PostConstruct(fromjakarta.annotationin Boot 3), after-init processing (where proxies such as transactional ones are created), use, and@PreDestroyon shutdown. - How does Spring Boot treat circular dependencies? Since Spring Boot 2.6 they are prohibited by default and startup fails with a cycle report. Fix the design (extract a third bean, use events) rather than setting
spring.main.allow-circular-references.
Configuration, profiles and Actuator
| Question | What it tests | What a strong answer shows |
|---|---|---|
| Where can configuration come from, and which wins? | Externalized config | Command line arguments override environment variables, which override profile-specific files, which override application.properties or application.yml inside the jar. Knowing that environment variables beat packaged files is the practical point. |
@Value or @ConfigurationProperties? | Binding | @Value injects single values. @ConfigurationProperties binds a whole prefix into a typed class or record, supports validation and relaxed binding (MY_APP_TIMEOUT maps to my-app.timeout), and is easier to test. |
| What are profiles for? | Environments | Activating beans and property files per environment with spring.profiles.active, such as dev, test and prod. Keep secrets out of profile files and inject them from the environment or a secret store. |
| What does Actuator give you? | Production readiness | Endpoints for health, metrics, info, environment, loggers, thread dumps and more. Only health is exposed over HTTP by default; expose others deliberately and secure them. |
| What are liveness and readiness probes in Boot? | Kubernetes | Health groups at /actuator/health/liveness and /actuator/health/readiness. Liveness says the app is not broken beyond repair; readiness says it can take traffic. Do not put downstream dependencies in liveness. |
| How are metrics collected? | Observability | Micrometer, a vendor-neutral facade, records timers, counters and gauges and exports them to Prometheus or other backends. Boot 3 adds Micrometer Tracing for distributed traces. |
@Validated
@ConfigurationProperties(prefix = "pricing")
public record PricingProperties(
@NotBlank String baseUrl,
@DefaultValue("2s") Duration timeout,
@DefaultValue("3") @Min(0) int retries) {
}
// application.yml
// pricing:
// base-url: https://pricing.internal
// timeout: 500ms
//
// Environment variable override in production: PRICING_TIMEOUT=1sSpring Data JPA and transactions
| Question | What it tests | What a strong answer shows |
|---|---|---|
| How do Spring Data repositories work without an implementation? | Mechanism | Spring generates a proxy at startup. Method names such as findByEmailAndStatus are parsed into queries; @Query covers the rest. |
| What is the N+1 query problem in JPA? | Performance | Loading n parents and then lazily loading each one's children with one extra query each. Fix it with a fetch join, an entity graph, or batch fetching, and spot it by logging SQL in tests. |
| Lazy versus eager loading? | Fetching | Lazy loads associations on first access; eager loads them immediately. Default to lazy and fetch what each use case needs; eager everywhere loads far too much. |
What is LazyInitializationException? | Session scope | A lazy association is touched after the persistence context closed, often in a controller or JSON serializer. Fetch it inside the transaction or map to a DTO there. |
What does spring.jpa.open-in-view do? | Defaults | It keeps the persistence context open through the web request so lazy loading works in views. Boot enables it by default and logs a warning; many teams turn it off to keep database access inside the service layer. |
How does @Transactional work? | Proxies | Spring wraps the bean in a proxy that starts a transaction before the method and commits or rolls back after it. Only calls that go through the proxy are transactional. |
Why doesn't my @Transactional method roll back? | Classic bug | By default only unchecked exceptions (and errors) trigger rollback. Checked exceptions commit unless you set rollbackFor. Catching the exception inside the method also hides it from the proxy. |
Why is @Transactional ignored on a method called from the same class? | Self-invocation | The call uses this, not the proxy, so no transaction starts. Move the method to another bean or restructure the call. |
| Explain REQUIRED versus REQUIRES_NEW. | Propagation | REQUIRED joins an existing transaction or starts one. REQUIRES_NEW suspends the current one and starts an independent transaction, useful for audit logs that must survive a rollback, at the cost of a second connection. |
What does readOnly = true do? | Optimization | It hints the persistence provider and driver that no writes happen, which can skip dirty checking and route to replicas in some setups. It is not a security control. |
@Service
public class OrderService {
private final OrderRepository orders;
private final AuditRepository audits;
public OrderService(OrderRepository orders, AuditRepository audits) {
this.orders = orders;
this.audits = audits;
}
@Transactional
public void placeOrder(Order order) {
orders.save(order);
saveAudit(order); // plain this.saveAudit(): no proxy, no new transaction
if (order.total() < 0) {
throw new IllegalStateException("bad total"); // rolls back the audit row too
}
}
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void saveAudit(Order order) {
audits.save(new AuditEntry(order.id(), "placed"));
}
}Web layer, errors and testing
- `@Controller` versus `@RestController`?
@RestControlleradds@ResponseBodyto every method, so return values are written as JSON (through Jackson) instead of resolved as view names. - How does a request reach your method? The
DispatcherServletasks handler mappings for the matching method, argument resolvers bind path variables, query parameters and the body, the method runs, and message converters write the response. - How do you handle errors consistently? A
@RestControllerAdvicewith@ExceptionHandlermethods. Spring Framework 6 supports RFC 7807 problem details throughProblemDetail, which gives a standard error body. - How do you validate input? Bean Validation annotations (
@NotNull,@Size,@Email) on a DTO and@Validon the parameter; failures become 400 responses you can shape in the advice. - `@SpringBootTest` or a test slice?
@SpringBootTeststarts the whole context and suits a few end-to-end tests. Slices such as@WebMvcTest(controllers only) and@DataJpaTest(repositories with a test database) start faster and fail more precisely. - How do you replace a bean in a test? From Spring Boot 3.4,
@MockitoBean(part of Spring Framework 6.2) replaces@MockBean, which is deprecated. Plain unit tests with constructor injection need no Spring at all. - How do you test against a real database? Testcontainers starts a throwaway database in Docker; since Spring Boot 3.1,
@ServiceConnectionwires its connection details without manual properties.
@WebMvcTest(OrderController.class)
class OrderControllerTest {
@Autowired MockMvc mvc;
@MockitoBean OrderService service;
@Test
void returnsOrderAsJson() throws Exception {
when(service.find(42L)).thenReturn(new OrderView(42L, "PAID"));
mvc.perform(get("/orders/42"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.status").value("PAID"));
}
}Spring Boot 3 and what changed
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What changed in Spring Boot 3? | Currency | Released in November 2022 on Spring Framework 6: Java 17 as the minimum, Jakarta EE 9+ APIs, AOT processing and GraalVM native image support, and Micrometer-based observability. |
| Why did imports change from javax to jakarta? | Namespace shift | Java EE moved to the Eclipse Foundation as Jakarta EE, and from Jakarta EE 9 the packages were renamed from javax.* to jakarta.* (persistence, servlet, validation, annotation). Libraries built on the old names must be upgraded too. |
| How would you migrate a Spring Boot 2.7 app? | Planning | Move to Java 17, clear deprecation warnings on 2.7 first, update to 3.x, rename imports (tools such as OpenRewrite automate much of it), check third-party library versions, then re-run the full test suite and the Spring Security configuration, which changed style. |
| What does a native image give you, and what does it cost? | Trade-offs | Fast startup and lower memory, useful for scale-to-zero. It costs long builds, a closed-world assumption that needs hints for reflection and proxies, and some libraries that do not support it. |
| How do you enable virtual threads? | Recent features | On Java 21 or later with Spring Boot 3.2 or later, set spring.threads.virtual.enabled=true, and the embedded server and task executors use virtual threads for blocking work. |
| Is there a version after 3? | Awareness | Spring Boot 4, on Spring Framework 7, followed in late 2025. Interviewers mostly care that you know which major version your team runs and what upgrading would involve. |
Fictional example
- Interviewer
- A method annotated with @Transactional saves a payment, then calls a fraud check that throws a checked FraudCheckException. The payment row is still in the database. What is going on?
- Candidate
- Two things to check. First, Spring's default rule only rolls back on unchecked exceptions and errors, so a checked exception lets the transaction commit; the fix is rollbackFor = FraudCheckException.class, or making the exception unchecked if that fits the codebase. Second, I would confirm the transaction is real at all: if this method is called from another method in the same class, the call skips the proxy and the save runs in whatever transaction the repository creates for itself, which commits immediately. I would turn on transaction debug logging for org.springframework.transaction to see where the transaction begins and ends, and add an integration test with a real database that throws the exception and asserts no payment row exists. Longer term, I would question doing the fraud check inside the same transaction, since a slow remote call holds a database connection the whole time.
How to prepare for Spring Boot interview questions
- Build one small service from scratchA REST API with validation, a JPA repository, error handling with problem details, configuration properties, Actuator and tests at each layer. Interviewers can tell who has done this.
- Read the auto-configuration reportStart your app with
--debugand read why each auto-configuration matched or did not. It turns "Boot is magic" into an explanation. - Break transactions on purposeWrite the self-invocation bug, the checked exception bug and an N+1 query, then fix each with a test that proves it. These three come up constantly.
- Know your versionBe ready to say which Spring Boot and Java versions you have used, what changed in 3.x, and how you would upgrade.
- Prepare a production storyA startup failure, a slow endpoint, a connection pool exhausted or a memory leak, and how Actuator, logs or metrics helped you find it.
Spring Boot questions often lead into neighboring topics. Multithreading interview questions covers the thread pools, virtual threads and shared state behind every request, OAuth and JWT interview questions covers what Spring Security's resource server actually validates, and Kafka interview questions covers the messaging that Spring for Apache Kafka wraps. Backend developer interview questions shows where all of it sits in a full loop.
Framework answers sound convincing until a follow-up asks for the mechanism, so rehearse them against follow-ups. Natively, an AI interview assistant for Mac and Windows, transcribes your mock Spring Boot round, can suggest answers and code fixes, and reads a stack trace or a service class from a screenshot so you can compare its diagnosis with yours. On Pro or the free trial it can also use the résumé and job description you add, and you keep the transcript and notes of every session.
Questions people ask
What are the most common Spring Boot interview questions?
What @SpringBootApplication does, how auto-configuration works, starters, dependency injection and bean scopes, profiles and configuration properties, Actuator, Spring Data JPA, @Transactional behavior and testing slices.
How does Spring Boot auto-configuration work?
Boot loads auto-configuration classes listed in an imports file on the classpath. Each is guarded by conditions such as @ConditionalOnClass and @ConditionalOnMissingBean, so it only applies when its libraries are present and you have not defined the bean yourself.
Why does @Transactional sometimes not work?
It works through a proxy, so calls from another method in the same class skip it. Also, by default only unchecked exceptions trigger rollback, so a checked exception commits unless rollbackFor is set.
What changed in Spring Boot 3?
It requires Java 17, runs on Spring Framework 6, moved from javax to jakarta package names, and added AOT processing for GraalVM native images and Micrometer-based observability.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
