Spring Boot Interview Questions and Answers
A collection of the questions asked most often in Spring Boot interviews, with short and clear answers. Study the linked topics for details.
Basics
| Question | Answer |
|---|
| What is Spring Boot? | A framework on top of Spring that provides auto-configuration, starters, an embedded server and production features so you can build applications with minimal setup. |
| What does @SpringBootApplication do? | It combines @SpringBootConfiguration, @EnableAutoConfiguration and @ComponentScan. |
| What is auto-configuration? | Spring Boot creates beans based on the classpath, properties and existing beans, using @Conditional annotations. It backs off when you define your own bean. |
| What are starters? | Dependency descriptors that bring a set of compatible libraries for one feature, for example spring-boot-starter-web. |
| How does Spring Boot start? | SpringApplication.run creates the ApplicationContext, scans components, applies auto-configuration, starts the embedded server and publishes ApplicationReadyEvent. |
| Which embedded servers are supported? | Tomcat (default), Jetty and Undertow. |
| What is Spring Boot DevTools? | A tool for development: automatic restart, LiveReload and sensible development defaults. |
Core Spring
| Question | Answer |
|---|
| What is dependency injection? | The container gives an object its dependencies instead of the object creating them. It reduces coupling and helps testing. |
| Constructor or field injection? | Constructor injection. Dependencies are explicit and final, and classes are easy to test without Spring. |
| Bean scopes? | singleton (default), prototype, request, session, application. |
| @Component vs @Bean? | @Component is on your own class and found by scanning. @Bean is a factory method in a @Configuration class. |
| What is @Qualifier and @Primary? | Both resolve ambiguity when several beans have the same type. @Primary marks the default, @Qualifier selects by name. |
| Bean lifecycle? | Instantiate, inject, Aware callbacks, BeanPostProcessor before, @PostConstruct, afterPropertiesSet, BeanPostProcessor after, use, @PreDestroy. |
| How does Spring resolve circular dependencies? | Constructor circular references fail. Redesign the beans. Boot 2.6 and newer forbid circular references by default. |
Configuration and profiles
| Question | Answer |
|---|
| properties vs YAML? | Same purpose. YAML is hierarchical and shorter, properties are flat. Both are supported. |
| @Value vs @ConfigurationProperties? | @Value for single values. @ConfigurationProperties binds a group of values into a typed, validated object. |
| What is the order of property sources? | Command line arguments override system properties, then environment variables, then application files, then defaults. |
| How do profiles work? | Beans and configuration files can be tied to profiles and activated with spring.profiles.active. |
Web and REST
| Question | Answer |
|---|
| @Controller vs @RestController? | @RestController = @Controller + @ResponseBody. It writes return values as the response body. |
| How does Spring MVC process a request? | Filter chain, DispatcherServlet, HandlerMapping, HandlerAdapter with argument resolvers and message converters, controller, message converter for the response. |
| How do you handle exceptions globally? | @RestControllerAdvice with @ExceptionHandler methods returning ProblemDetail or a custom error object. |
| How do you validate input? | Bean Validation annotations on DTOs and @Valid on the controller parameter. |
| Filter vs Interceptor? | A filter belongs to the servlet layer and runs before the DispatcherServlet. An interceptor is Spring MVC and wraps controller calls. |
| How do you version REST APIs? | URI (/v1), header or media type. Spring Framework 7 adds built-in API versioning support. |
Data and transactions
| Question | Answer |
|---|
| What is Spring Data JPA? | An abstraction that generates repository implementations from interfaces, with derived queries, paging and @Query. |
| What is the N+1 problem? | One query loads the parents and N extra queries load the children. Fix with join fetch, @EntityGraph or batch fetching. |
| LAZY vs EAGER? | LAZY loads on first access. EAGER loads immediately. Prefer LAZY and fetch explicitly. |
| Default rollback rule of @Transactional? | Rolls back on RuntimeException and Error, not on checked exceptions unless rollbackFor is set. |
| Why does @Transactional fail on self-invocation? | Because the call does not go through the Spring proxy. |
| Propagation REQUIRED vs REQUIRES_NEW? | REQUIRED joins the current transaction. REQUIRES_NEW suspends it and starts an independent one. |
| What is dirty checking? | Hibernate compares managed entities with their loaded state at flush and writes the changes without an explicit save. |
Security, production and testing
| Question | Answer |
|---|
| How does Spring Security work? | A chain of servlet filters authenticates the request and checks authorization rules before the request reaches the controller. |
| How do you secure a REST API? | Stateless security with JWT bearer tokens using the OAuth2 resource server support, HTTPS, and role or scope based rules. |
| How to store passwords? | Hash them with BCrypt or Argon2 using a PasswordEncoder. Never store plain text. |
| What is Actuator? | Production-ready endpoints for health, metrics, environment and more, integrated with Micrometer. |
| @WebMvcTest vs @SpringBootTest? | @WebMvcTest loads only the web layer for fast tests. @SpringBootTest loads the whole context. |
| How do you run Spring Boot in Docker? | Build the executable jar, use a JRE base image or buildpacks, pass config through environment variables, and use health probes. |
| Virtual threads in Spring Boot? | Set spring.threads.virtual.enabled=true on Java 21 or newer so request handling uses virtual threads. |
Tricky questions
- Can we change the default port? Yes: server.port property, or 0 for a random port.
- Can two beans of the same class exist? Yes, with different names and qualifiers.
- Difference between @Autowired required=false and Optional? Both allow a missing bean. Optional and ObjectProvider express it better.
- Why is field injection discouraged? Hidden dependencies, no final fields, and hard unit testing.
- How do you run code at startup? CommandLineRunner, ApplicationRunner or an ApplicationReadyEvent listener.
- What happens if two auto-configurations conflict? Use exclude or provide your own bean, because most auto-configurations use @ConditionalOnMissingBean.
Senior level: internals
| Question | Answer |
|---|
| Walk through SpringApplication.run(). | Create the SpringApplication (deduce web type, load initializers and listeners), prepare the Environment (property sources, config files, profiles), create and prepare the ApplicationContext, refresh it (register bean definitions, post processors, create singletons, start the web server), call runners, publish ApplicationReadyEvent. |
| What does refresh() do? | Twelve steps: prepare, create bean factory, register standard post processors, invoke BeanFactoryPostProcessors (ConfigurationClassPostProcessor registers all bean definitions), register BeanPostProcessors, init message source and event multicaster, create the web server, register listeners, instantiate non-lazy singletons, publish ContextRefreshedEvent and start the server. |
| How does Spring resolve circular dependencies? | Setter or field injection of singletons works with a three-level cache of early references. Constructor injection cannot. Boot forbids it by default. |
| Where is the AOP proxy created? | In a BeanPostProcessor (AbstractAutoProxyCreator) after initialization, or earlier via getEarlyBeanReference for circular references. |
| How does @Transactional work internally? | An advisor with TransactionInterceptor in a proxy. It gets a connection, binds it to the thread through TransactionSynchronizationManager, calls the method, then commits or rolls back. |
| How does Boot decide what to auto-configure? | AutoConfigurationImportSelector loads the imports files, filters by @ConditionalOnClass through metadata, then each class and @Bean method is evaluated with conditions, and @ConditionalOnMissingBean makes them back off. |
| How does Spring Data create repositories? | A JpaRepositoryFactoryBean builds a JDK proxy over SimpleJpaRepository with interceptors for transactions, exception translation and query methods parsed from the names or @Query. |
| What is the difference between BeanFactoryPostProcessor and BeanPostProcessor? | BeanFactoryPostProcessor changes bean definitions before any bean exists. BeanPostProcessor changes bean instances during creation. |
Senior level: design and operations
| Question | Answer |
|---|
| How do you make an API idempotent? | Idempotency-Key header stored with the response for a period, unique constraints, and conditional updates. |
| How do you handle a slow downstream service? | Timeouts, circuit breaker, bulkhead, fallback, and asynchronous processing with a queue when the answer is not needed immediately. |
| How do you avoid N+1 queries? | Fetch joins, entity graphs, batch fetch size, projections, and checking the SQL count in tests. |
| How do you deploy without downtime? | Rolling update, readiness probes, graceful shutdown, backward compatible database migrations (expand and contract). |
| How would you scale a Spring Boot service? | Stateless instances behind a load balancer, external session or token authentication, connection pool sizing, caching, async messaging, database read replicas, and measuring bottlenecks first. |
| Monolith or microservices? | Start with a modular monolith. Split when team size, scaling or release independence demand it, accepting distributed system costs. |
| How do you secure service-to-service calls? | OAuth2 client credentials or mTLS, least privilege scopes, network policies, and no shared static secrets. |
| How do you find a memory leak? | Heap dump on OOM, analyze with Eclipse MAT, look at dominators, static collections, unbounded caches and ThreadLocals; use JFR to watch allocation. |
Scenario questions
- The application starts slowly (90 seconds). What do you check? Startup endpoint timeline, slow beans, Hibernate validation, migrations, remote calls in @PostConstruct, classpath scanning size. Then lazy init, AOT cache or native image.
- You get 'Connection is not available' under load. Why? Pool exhausted by long transactions or slow queries. Check metrics, leak detection and open-in-view. Do not just raise the pool size.
- A @Transactional method is not rolling back. Why? Checked exception, exception caught inside, self invocation, private method, or a wrong transaction manager.
- Your endpoint returns 200 in tests but 403 in production. Why? Different security configuration by profile, missing CSRF token or role prefix, or an @Order problem between filter chains.
- Two instances process the same scheduled job. Fix? Distributed lock (ShedLock), Quartz cluster, or a Kubernetes CronJob.
Common mistake: Learning answers by heart without trying the code. Interviewers ask follow-up questions. Build the CRUD project and test each concept yourself.
Interview questions
Which Spring Boot topics are asked the most?
Auto-configuration, dependency injection, REST controllers, exception handling, JPA and N+1, @Transactional, Spring Security with JWT, and Actuator.
What should I prepare for experienced roles?
Internals (auto-configuration, proxies, transactions), performance (pool sizing, N+1, caching), security design, observability and deployment.
How can I practice?
Build a small project with the layers from the Complete CRUD page, add security, tests and Docker, and explain every decision aloud.
How should I use these tables to prepare?
Answer aloud in your own words with one concrete example each, then open the matching topic page and check the details. Interviewers ask follow-up questions on internals.