Spring Boot Interview Questions (and Answers That Show You've Shipped)
- #Java
- #Spring Boot
- #Interviews
- #Career
Most Spring Boot interview questions can be answered from the reference
docs. "What does @SpringBootApplication do?" has a one-line answer, and
anyone can learn it the night before. The follow-up is where it gets
interesting: "so why didn't your @Transactional method roll back?" You only
know that one if you've debugged it, or if you understand the mechanism well
enough to predict it.
That's the gap this list is about. These are 20 questions grouped by the part of Spring they probe, and for each one you get a weak answer, a strong answer, and the signal the interviewer is actually looking for. They're the questions where having run Spring in production shows. There's no point in a 100-question dump, since you'd end up memorising definitions again.
Every code example below was compiled and run on Spring Boot 4.2.0 with Hibernate 7.4 and H2, on Java 25 (Corretto 25.0.4.1). Where a number shows up, like a query count, it came out of those runs.
What a strong answer sounds like
A weak answer names the annotation. A strong one explains the mechanism and then says where it breaks. "Spring wraps the bean in a proxy" is the mechanism. "So a call from inside the same class never goes through the proxy, and the transaction silently isn't there" is the part that shows you've been burned by it, or that you'd see it coming.
If you're stuck in an interview, that's also the way out: describe the mechanism you're sure of and reason forward from it out loud. Interviewers usually give more credit for that than for a confident guess.
Auto-configuration and starters
1. What does @SpringBootApplication actually do?
Weak answer: "It starts the Spring Boot application."
Strong answer: It's three annotations in one. @SpringBootConfiguration
marks the class as a configuration source, @ComponentScan scans its package
and everything below it, and @EnableAutoConfiguration turns on
auto-configuration. The package part matters in practice: put the main class
in com.acme.app and a controller in com.acme.web, and the controller is
never found. There's no error, you just get a 404.
The signal: whether you know what's happening behind the annotation, or treat it as a magic word.
2. How does auto-configuration decide what to create?
Weak answer: "Spring Boot configures things automatically based on your dependencies."
Strong answer: Each auto-configuration class is listed in a
META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
file and guarded by conditions: @ConditionalOnClass (is Hibernate on the
classpath?), @ConditionalOnProperty, @ConditionalOnMissingBean (did the
user already define one?) and so on. The classes are ordinary @Configuration
classes that only run when their conditions match. In Spring Boot 4 they're
split across modules too: the JPA repository auto-configuration lives in
spring-boot-data-jpa, with its own imports file, instead of one giant
spring-boot-autoconfigure jar.
The signal: whether you can reason about why something got configured instead of hoping it did. The What Is Spring Boot post walks through this with a real example.
3. A bean you expected isn't there. How do you find out why?
Weak answer: "I'd search Stack Overflow," or "I'd add the bean manually."
Strong answer: Start the app with --debug. Spring Boot prints a
CONDITIONS EVALUATION REPORT with Positive matches and Negative
matches, and the negative side tells you which condition failed for each
auto-configuration. In a running app, the Actuator conditions endpoint
shows the same report, once you've exposed it. For example, the report for the sample app used for
this post shows why open-in-view was turned on:
- @ConditionalOnBooleanProperty (spring.jpa.open-in-view=true) matched (OnPropertyCondition)
The signal: debugging from evidence. Anyone who has stared at a missing
DataSource for an hour and then found this report remembers it.
4. How do you replace an auto-configured bean?
Weak answer: "Exclude the auto-configuration."
Strong answer: Usually you don't need to do either. First check whether a
property does what you want, because most auto-configurations are tuned
through spring.* properties. If that's not enough, define your own bean of
the same type: most auto-configured beans are @ConditionalOnMissingBean, so
Spring Boot backs off when it sees yours. Excluding a whole auto-configuration
with @SpringBootApplication(exclude = ...) is the last resort, because you
lose everything else it set up too.
The signal: whether you work with the framework or fight it.
Beans and dependency injection
5. Constructor injection or field injection?
Weak answer: "@Autowired on fields, it's shorter."
Strong answer: Constructor injection. The dependencies are explicit, the
fields can be final, the class can be built in a plain unit test with new,
and a constructor with nine parameters is a visible sign that the class does
too much. With a single constructor you don't even need @Autowired. Field
injection hides all of that and makes the class impossible to create without
Spring or reflection.
The signal: whether you design classes to be tested and read, not just to compile.
6. Two beans implement the same interface. What happens?
Weak answer: "Spring picks one."
Strong answer: If you inject a single one, startup fails with a
NoUniqueBeanDefinitionException, which is the good outcome because you find
out immediately. You fix it with @Primary for the default, @Qualifier at
the injection point when the choice matters, or by injecting List<PaymentGateway>
(or a Map<String, PaymentGateway> keyed by bean name) when you actually want
all of them, for example in a strategy pattern.
The signal: whether you know the container's rules and when ambiguity is a design choice rather than an accident.
7. What happens when you inject a prototype bean into a singleton?
Weak answer: "You get a new instance every time, that's what prototype means."
Strong answer: You get a new instance every time the container is asked
for one, and a singleton only asks once, when it's built. So the prototype
behaves like a singleton inside it. In the sample app, a prototype
ShoppingCart injected into a singleton CheckoutService was the same object
on every call. Asking through an ObjectProvider gave a new one each time:
@Service
public class CheckoutService {
private final ShoppingCart cart; // injected once
private final ObjectProvider<ShoppingCart> carts; // asks for a new one
public CheckoutService(ShoppingCart cart, ObjectProvider<ShoppingCart> carts) {
this.cart = cart;
this.carts = carts;
}
public ShoppingCart injectedCart() { return cart; }
public ShoppingCart freshCart() { return carts.getObject(); }
}
// injectedCart() == injectedCart() -> true
// freshCart() == freshCart() -> false
A strong candidate adds that the same trap exists for request-scoped beans, which is why Spring injects a scoped proxy for them.
The signal: whether you understand scope as "when does the container create one", not as a label.
8. When does @PostConstruct run, and when is it the wrong hook?
Weak answer: "After the bean is created, so you can initialise things."
Strong answer: It runs after dependency injection, during context
startup, on the raw object, before Spring wraps the bean in its proxies. So
transactions, caching and other proxy-based features don't apply to what it
calls on itself. In the sample app, a @Transactional method called from
@PostConstruct ran with no transaction. The same check in an
ApplicationReadyEvent listener found one:
@Component
public class CacheWarmer {
@PostConstruct
void init() {
boolean tx = warm(); // false: no transaction here
}
@EventListener(ApplicationReadyEvent.class)
@Transactional
public void onReady() {
// transaction active, and the whole app has started
}
@Transactional
public boolean warm() {
return TransactionSynchronizationManager.isActualTransactionActive();
}
}
@PostConstruct is also the wrong place for slow work like warming a cache
from a remote API, because it blocks startup and a failure there takes down
the whole context.
The signal: whether you know the order things happen in when the app starts.
Proxies and transactions
9. Why doesn't @Transactional work when you call the method from the same class?
Weak answer: "It should work, maybe the annotation is missing."
Strong answer: @Transactional works through a proxy that Spring puts in
front of the bean. A call from another bean goes through the proxy, which
opens the transaction. A call from inside the class is this.generate(), a
plain method call on the real object, so the proxy never sees it:
@Service
public class ReportService {
public boolean generateFromSchedule() {
return generate(); // this.generate(): skips the proxy
}
@Transactional
public boolean generate() {
return TransactionSynchronizationManager.isActualTransactionActive();
}
}
// reportService.generate() -> true
// reportService.generateFromSchedule() -> false
The fixes, from best to worst: move the transactional method to another bean,
put @Transactional on the outer public method instead, or use a
TransactionTemplate when you need a transaction around just a few lines.
Injecting the bean into itself works but is a sign the class wants to be
split. A good answer also mentions that the same applies to @Async and
@Cacheable.
The signal: this is probably the most reliable question for spotting real Spring experience. People who have shipped Spring code have usually hit it.
10. Does a checked exception roll back the transaction?
Weak answer: "Yes, any exception rolls back."
Strong answer: No. By default Spring rolls back on unchecked exceptions
(RuntimeException and Error) and commits on checked ones. In the sample
app, this method threw a checked PaymentDeclinedException after saving, and
the order was still in the database afterwards:
@Transactional
public void placeOrder(String item) throws PaymentDeclinedException {
orders.save(new PurchaseOrder(item));
throw new PaymentDeclinedException("card declined");
}
// orders.count() afterwards -> 1
@Transactional(rollbackFor = PaymentDeclinedException.class)
public void placeOrderSafely(String item) throws PaymentDeclinedException {
orders.save(new PurchaseOrder(item));
throw new PaymentDeclinedException("card declined");
}
// orders.count() afterwards -> 0
A strong candidate adds the related trap: catching an exception inside the transactional method and logging it means the proxy never sees it, so the transaction commits whatever was written before the failure.
The signal: whether you know the default, rather than assuming the framework does what feels natural.
11. What does Propagation.REQUIRES_NEW do, and when does it hurt?
Weak answer: "It creates a new transaction."
Strong answer: It suspends the current transaction and starts an independent one, which commits or rolls back on its own. That's what you want for an audit record that must survive even if the business operation fails. It has two costs people miss. The inner transaction needs a second database connection while the outer one holds its first, so under load a small pool can run out with every thread holding one connection and waiting for another. And because the two transactions are independent, the inner one can't see uncommitted rows the outer one wrote.
The signal: whether you think about what a transaction costs in connections and locks, not just what it guarantees.
Configuration
12. Where can a property come from, and which value wins?
Weak answer: "From application.properties."
Strong answer: From a list of sources with a fixed order: command-line
arguments beat environment variables, which beat profile-specific files like
application-prod.yml, which beat the base application.yml. That's why
SPRING_DATASOURCE_URL in a container overrides what's in the jar. Profiles
should change values, not code paths: if you find if (env.equals("prod"))
in a service, the behaviour should be a property instead. The
configuration post
shows the order with real output.
The signal: whether you can explain why production got a value you didn't expect.
13. @Value or @ConfigurationProperties?
Weak answer: "@Value, it's simpler."
Strong answer: @Value is fine for one value. For a group of related
settings, a typed @ConfigurationProperties record is better: one place to
read, IDE completion, relaxed binding, and validation at startup. A missing
URL fails the deploy instead of the first request that needs it:
@Validated
@ConfigurationProperties("payments")
public record PaymentProperties(@NotBlank String apiUrl, @Min(1) int retries) {}
Starting the sample app without payments.api-url failed immediately with
Binding validation errors on payments, before any request was served.
The signal: whether you prefer bad config to fail loudly and early.
JPA traps
14. What is the N+1 problem, and how do you fix it?
Weak answer: "It's when you make too many queries. Use EAGER."
Strong answer: You load N rows with one query, then touch a lazy
association on each, and Hibernate runs one more query per row. With five
authors and two books each, findAll() followed by getBooks().size() in a
loop ran 6 statements in the sample app (counted with Hibernate
statistics). An entity graph loaded the same data in 1:
public interface AuthorRepository extends JpaRepository<Author, Long> {
@EntityGraph(attributePaths = "books")
@Query("select a from Author a")
List<Author> findAllWithBooks();
}
FetchType.EAGER is the wrong fix: it loads the association everywhere,
including the many places that don't need it, and often still does it with
extra queries. A strong answer also covers the trade-offs of the fixes. Join
fetching two collections at once multiplies rows, and join fetching a
collection with pagination makes Hibernate paginate in memory. For read-only
screens, a DTO projection is often better than loading entities at all. And
you catch it in a test by asserting the statement count, which is what turns
a fix into a regression guard.
The signal: whether you know what SQL your code really runs.
15. What causes LazyInitializationException, and what is open-in-view?
Weak answer: "Make the relationship eager," or "add
enable_lazy_load_no_trans."
Strong answer: A lazy association was touched after the persistence
context that loaded the entity was closed. In the sample app, reading
author.getBooks() outside a transaction failed with
Cannot lazily initialize collection of role 'dev.demo.Author.books' ... (no session).
The fix is to load what you need inside the transaction, with a fetch join, an
entity graph or a DTO.
Open-in-view hides this in web apps. Spring Boot keeps the persistence context open for the whole HTTP request by default, so lazy loads in a controller or during JSON serialisation "just work", by running queries outside your service layer and holding a connection for the whole request. Spring Boot warns about it at startup:
spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
Setting spring.jpa.open-in-view=false on a new project makes these problems
show up in development instead of as slow pages under load.
The signal: whether you know where your transactions start and end.
16. Would you use ddl-auto in production?
Weak answer: "Yes, update keeps the schema in sync."
Strong answer: No. update only adds things, never renames or drops, it
doesn't version anything, and two developers' local databases drift apart. In
production the schema should change through versioned migrations with Flyway
or Liquibase, reviewed like code, and the app should run with
ddl-auto=validate or none. The
Spring Data JPA post shows what
the switch to Flyway looks like.
The signal: whether you treat the schema as something you deploy.
Testing
17. @SpringBootTest or a test slice?
Weak answer: "@SpringBootTest for everything, so it's realistic."
Strong answer: It depends on what the test is about. A slice like
@WebMvcTest loads only the web layer, so it's fast and focused on HTTP:
status codes, JSON, validation. You mock the layer below with @MockitoBean:
@WebMvcTest(GreetingController.class)
class GreetingControllerTest {
@Autowired MockMvc mvc;
@MockitoBean GreetingService service;
@Test
void greets() throws Exception {
given(service.greet("Ana")).willReturn("Hi, Ana");
mvc.perform(get("/greet/Ana"))
.andExpect(status().isOk())
.andExpect(content().string("Hi, Ana"));
}
}
@DataJpaTest does the same for repositories. @SpringBootTest is for a few
tests that check the pieces work together. Two details show you're current:
@MockBean is gone in Spring Boot 4 (@MockitoBean from Spring Framework
replaces it), and in Boot 4 the slice annotations moved into per-technology
test modules, so @WebMvcTest comes from spring-boot-starter-webmvc-test.
More in Testing Your Spring Boot Application.
The signal: whether you pick the smallest test that answers the question.
18. Why is a Spring test suite slow, and how do you speed it up?
Weak answer: "Spring is slow to start."
Strong answer: Spring caches the application context between tests and
reuses it when the configuration is the same. Every difference creates a new
context: a different set of @MockitoBean fields, a different
@TestPropertySource, @DirtiesContext. A suite with 40 slightly different
@SpringBootTest classes can start 40 contexts. The fix is to standardise:
a few shared base configurations, fewer one-off mocks, @DirtiesContext only
when a test really leaves the context broken. The test logs show when a new
context starts, so you can see where the time goes.
The signal: whether you've worked on a test suite that had to stay fast as the codebase grew.
Security and production readiness
19. How does a request get through Spring Security to your controller?
Weak answer: "Spring Security checks the user's role."
Strong answer: Spring Security is a chain of servlet filters that runs
before the DispatcherServlet. You configure it with a SecurityFilterChain
bean: which paths need authentication, how users authenticate (session,
HTTP Basic, JWT), and what each role can do. Authentication answers "who are
you?" and puts the result in the SecurityContext. Authorisation answers
"may you do this?" afterwards. A strong answer also explains CSRF: protection
matters when the browser sends credentials automatically, as with session
cookies, and is commonly disabled for stateless APIs that use bearer tokens.
Disabling it because a POST returned 403 in development is the wrong reason.
See Spring Security Fundamentals.
The signal: whether you understand security as a request pipeline you can reason about, not annotations you copy.
20. What does a Spring Boot service need before it goes to production?
Weak answer: "Add Actuator so it has a health endpoint."
Strong answer: Actuator is the start. Then come the decisions. Only
health is exposed over HTTP by default, so you expose more as an allow
list rather than *, and you don't put it on the public port without
security. Liveness and readiness are different probes: liveness should only
check the app's own state, because a database outage in a liveness check
makes Kubernetes restart every pod at once. Graceful shutdown lets in-flight
requests finish on deploy. Metrics go to Prometheus through Micrometer, and
logs are structured so you can search them. The
Actuator and health checks post
covers each of these in detail.
The signal: whether you've been responsible for what happens after the merge.
How to prepare with this list
Don't memorise the answers. Build a small app with one entity that has a lazy
collection, one service with @Transactional, and one controller, then break
it on purpose. Call a transactional method from the same class. Throw a
checked exception after a save. Loop over a lazy collection with Hibernate
statistics on. It takes an afternoon and you'll remember what you saw much
better than what you read.
Then link each topic to something you've built. "I know about N+1" is weaker than "a page was slow, I turned on SQL logging, found 200 queries and fixed it with an entity graph", and the STAR method helps you tell that story in a structured way. The Spring round is usually only one part of the interview, so pair this with the senior Java interview questions for the language and JVM side.
And if you don't know something, say what you do know and reason from there.
"I haven't used REQUIRES_NEW in production, but since it suspends the outer
transaction I'd expect it to need a second connection" is a good answer. A
confident guess that falls apart on the follow-up isn't.