Skip to content
Tutorials Center
My learning

Topics

Lesson 65 of 66 ยท Practice and Review

Spring Boot Interview Questions

40 Spring Boot interview questions with concise answers on beans, auto-configuration, REST, JPA, security, testing and production, plus two predict-the-output examples.

Spring Boot interviews rarely ask you to recite an annotation list. They ask you to explain what happens: why constructor injection is preferred, how auto-configuration decides what to create, why a @Transactional method sometimes does nothing, and what you would check before putting a service into production. This page collects 40 questions that come up again and again, grouped by topic, with short and accurate answers you can put into your own words.

Try to answer each question aloud before you open it. If you cannot explain an idea in two or three sentences, follow the link to its lesson and review it. Two small programs ask you to predict the output of a bean scope and a property-precedence question; guess first, then press Run. They are plain-Java stand-ins for container behaviour, because Spring itself cannot run on this site. Related practice: Practice Exercises with Solutions and Common Mistakes and Debugging Startup Failures.

Tip: a strong answer has three parts: the definition, a tiny concrete example, and a trade-off or pitfall ("constructor injection makes dependencies explicit, but a long constructor is a hint that the class does too much"). The pitfall is what separates a good answer from a memorized one.

Forty questions, seven areas

Beans Container, scopes, lifecycle.
Auto-config Starters, properties, profiles.
REST Controllers, validation, errors.
JPA Queries, N+1, transactions.
1 / 2

Beans and dependency injection

1. What are inversion of control and dependency injection?

With inversion of control, your classes do not create or look up the objects they depend on; the framework does, and hands them in. Dependency injection is the technique: the container reads what a class needs (usually from its constructor), builds the objects in the right order and passes them in. The benefit is loose coupling: a class depends on an interface, and tests can pass a fake. See IoC and Dependency Injection.

2. Why is constructor injection preferred over field injection?

Constructor injection makes dependencies explicit and required, lets fields be final, and allows creating the class with plain new in a unit test without Spring or reflection. Field injection (@Autowired on a field) hides dependencies, cannot be final and fails with a NullPointerException outside the container. With a single constructor you do not even need @Autowired. A constructor with many parameters is a useful smell: the class probably has too many responsibilities.

3. What is the difference between @Component, @Service, @Repository and @Controller?

All four register a class as a bean through component scanning. @Component is the generic one; the others are specializations that document the layer. @Repository also enables translation of persistence exceptions into Spring's DataAccessException hierarchy, and @Controller marks a web handler. @Service adds no behaviour today, only meaning. See Component Scanning and Stereotypes.

4. When do you use @Bean instead of @Component?

@Component goes on your own classes, discovered by scanning. @Bean goes on a method inside a @Configuration class and returns an object, so it works for types you cannot annotate (a JDK Clock, a library's ObjectMapper) and for objects that need construction logic or conditions. The bean name defaults to the method name. See @Configuration and @Bean.

5. What are the bean scopes, and what is the default?

The default is singleton: one shared instance per container. Prototype creates a new instance on every request for the bean. Web scopes (request, session, application) tie a bean to an HTTP request, session or servlet context. Because a singleton is shared by all threads, it must be stateless or thread-safe; keeping per-user data in a singleton field is a classic bug. See Bean Scopes and Lifecycle.

6. What happens if you inject a prototype bean into a singleton?

The singleton is created once, so it receives one prototype instance at that moment and keeps it forever; the prototype behaviour is lost. To get a fresh instance each time, inject an ObjectProvider<T> (or Supplier) and call getObject() when needed, or use a scoped proxy. The first example below shows the effect.

7. What is the difference between @Primary and @Qualifier?

When several beans match a type, Spring needs a tie-breaker. @Primary marks one bean as the default choice for every injection point. @Qualifier("name") selects a specific bean at one injection point and overrides the default. Use @Primary for "normally this one", @Qualifier for the exceptions. Without either, startup fails with NoUniqueBeanDefinitionException. See Qualifiers, @Primary and Collections.

8. Describe the lifecycle of a singleton bean.

The container instantiates the bean (calling the constructor), injects its dependencies, applies Aware callbacks and bean post-processors, then calls initialization callbacks: @PostConstruct, InitializingBean.afterPropertiesSet, and any initMethod. The bean is now ready for use. On shutdown, @PreDestroy and DisposableBean.destroy run. Proxies for features like @Transactional are created by post-processors around initialization. Prototype beans are not destroyed by the container.

9. What is a circular dependency, and how do you fix it?

Bean A needs B and B needs A, so with constructor injection neither can be built first. Since Boot 2.6 the application fails to start instead of working around it. The right fix is a design change: move shared logic into a third class, replace one direction with an event, or ask whether one class owns the other. Setting spring.main.allow-circular-references=true or injecting @Lazy only hides the problem.

Auto-configuration and configuration

10. What does @SpringBootApplication do?

It is a meta-annotation combining @SpringBootConfiguration (the class is a configuration class), @EnableAutoConfiguration (turn on auto-configuration) and @ComponentScan (scan the package of this class and its sub-packages). That is why the main class should sit in the root package of the application: classes outside its package tree are not found.

11. What is a starter?

A starter is a dependency that pulls in a coherent set of libraries for a purpose, for example spring-boot-starter-web (Spring MVC, Jackson, embedded Tomcat) or spring-boot-starter-data-jpa (Hibernate, Spring Data, JDBC pool). Boot's BOM manages compatible versions, so you rarely write them. A starter contains almost no code of its own. See Starters and Dependency Management.

12. How does auto-configuration work?

Boot reads the list of auto-configuration classes from META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports in each jar. Each class is full of @Bean methods guarded by conditions such as @ConditionalOnClass (is the library on the classpath?), @ConditionalOnProperty and @ConditionalOnMissingBean (did the user define their own?). The ones whose conditions pass create beans. See How Auto-Configuration Works.

13. How do you replace or back off an auto-configured bean?

Define your own bean of the same type; most auto-configured beans use @ConditionalOnMissingBean, so they back off. To disable a whole auto-configuration, use @SpringBootApplication(exclude = X.class) or spring.autoconfigure.exclude. Prefer a property when one exists (such as spring.jackson.*), then your own bean, and exclusion last.

14. How can you find out what was auto-configured, and why?

Start the app with --debug (or debug=true) to print the conditions evaluation report: positive matches, negative matches with the failed condition, exclusions. A running app exposes the same through /actuator/conditions, and /actuator/beans lists all beans. See Common Mistakes and Debugging Startup Failures.

15. In what order are configuration sources applied?

Roughly from highest to lowest priority: command-line arguments, Java system properties, OS environment variables, profile-specific files (application-prod.yml), then application.yml, then defaults in code. A higher source overrides a lower one for the same key. Environment variables use relaxed naming, so APP_MAIL_FROM sets app.mail.from. The second example below lets you predict the winner. See Properties, YAML and Externalized Config.

16. What is the difference between @Value and @ConfigurationProperties?

@Value("${app.mail.from}") injects one value and has no structure or validation. @ConfigurationProperties(prefix = "app.mail") binds a whole group of properties to a typed class or record, with nesting, defaults, durations, relaxed names and @Validated constraints, and startup fails if a value is invalid. Use @Value for one-off values, @ConfigurationProperties for anything with more than two or three settings. See Type-Safe @ConfigurationProperties.

17. What are profiles, and how do you activate one?

A profile is a named set of beans and properties for an environment: dev, test, prod. Beans can be tied to profiles with @Profile, and files named application-{profile}.yml apply only when the profile is active. Activate with spring.profiles.active=prod, the SPRING_PROFILES_ACTIVE environment variable or --spring.profiles.active. Keep secrets out of the files; read them from the environment. See Profiles and Environment-Specific Config.

Building REST APIs

18. What is the difference between @Controller and @RestController?

@Controller handler methods return view names by default, which a template engine such as Thymeleaf renders. @RestController is @Controller plus @ResponseBody: return values are written straight to the response body, converted to JSON by Jackson. Use @RestController for APIs and @Controller for server-rendered pages. See REST Controllers.

19. What do @PathVariable, @RequestParam and @RequestBody bind?

@PathVariable binds a part of the URL path (/books/{id}), @RequestParam binds a query parameter or form field (?page=2), and @RequestBody deserializes the whole request body (usually JSON) into an object. Path variables identify a resource; query parameters filter, sort or page; the body carries the data to create or change.

20. How does validation work, and what is the difference between @Valid and @Validated?

Constraint annotations (@NotBlank, @Size, @Min) on a DTO are checked when the parameter is annotated with @Valid; failures raise MethodArgumentNotValidException, which becomes a 400. @Valid is the standard Jakarta annotation and cascades into nested objects. @Validated is Spring's variant: it supports validation groups and, on a class, turns on method-level validation for simple parameters such as @RequestParam @Min(1) int size. See Bean Validation.

21. How do you handle errors globally?

A class annotated @RestControllerAdvice with @ExceptionHandler methods maps exceptions to responses in one place, so controllers stay free of try/catch. Return a ProblemDetail (RFC 9457, application/problem+json) with status, title, detail and extra properties. Never leak stack traces or internal class names. ResponseStatusException is handy for one-off cases. See Error Handling and Problem Details.

22. What is the difference between a servlet filter and a Spring interceptor?

A filter is part of the servlet container: it wraps every request before Spring MVC sees it, so it suits cross-cutting concerns such as security, CORS and request logging. A HandlerInterceptor is part of Spring MVC: it runs around a matched controller method (preHandle, postHandle, afterCompletion) and knows which handler was chosen. Spring Security itself is a chain of filters. See Filters, Interceptors and Argument Resolvers.

23. Why return DTOs instead of entities from controllers?

An entity is a persistence model: it may contain lazy associations (causing LazyInitializationException or accidental queries during serialization), internal fields such as password hashes, and bidirectional links that loop forever in JSON. A DTO (often a record) is the public contract: you choose exactly what is exposed, and the database can change without breaking clients. See Request and Response Bodies with Jackson.

24. Which status codes should a REST API use for create, update and delete?

Creating with POST returns 201 Created plus a Location header. A successful PUT or PATCH returns 200 with the resource or 204 No Content. DELETE returns 204. Validation errors are 400 (or 422), unknown resources 404, conflicts such as duplicate emails or stale versions 409, missing login 401 and missing permission 403. PUT and DELETE should be idempotent: repeating them leaves the same result.

Data access and transactions

25. How does a Spring Data repository work without an implementation?

You declare an interface that extends JpaRepository. At startup, Spring Data creates a proxy that implements it, parses derived method names (findByAuthorNameOrderByTitleAsc) or @Query annotations into queries, and delegates to the EntityManager. Standard methods such as save and findById come from a shared base implementation. See Spring Data JPA Repositories.

26. What is the N+1 problem, and how do you fix it?

You load N parents with one query, then touching a lazy association of each parent triggers one extra query per parent: N+1 queries. Fix it by fetching the association in the same query with join fetch or @EntityGraph, by selecting a DTO projection with exactly the needed columns, or by batch fetching (hibernate.default_batch_fetch_size). Detect it by logging SQL, or counting statements in a test. See Entity Relationships and the N+1 Problem.

27. How does @Transactional work, and why does it sometimes do nothing?

Spring wraps the bean in a proxy. When a method is called through the proxy, it starts a transaction, calls your method, and commits or rolls back. It does nothing when the call bypasses the proxy: calling this.otherMethod() (self-invocation), annotating a private method, or using an object created with new. Move the method to another bean, or use TransactionTemplate. See Transactions with @Transactional.

28. What are the default rollback rules and propagation?

By default a transaction rolls back on runtime exceptions and errors, but commits on checked exceptions unless you set rollbackFor. The default propagation is REQUIRED: join the caller's transaction if there is one, otherwise start a new one. REQUIRES_NEW suspends the caller's transaction and starts an independent one, which is useful for audit logging that must survive a rollback. readOnly = true is a hint that can skip flush work and route to replicas.

29. What is open-in-view, and should it be on?

spring.jpa.open-in-view (default true) keeps the persistence session open during the whole web request, so lazy loading works even in the controller or view. The cost: a database connection is held while rendering and serializing, and queries can hide in the web layer. Most teams set it to false and fetch what they need in the service, mapping to DTOs.

30. Why use Flyway instead of ddl-auto=update?

ddl-auto=update lets Hibernate guess schema changes: it never drops or renames, cannot migrate data and gives no history. Flyway applies versioned SQL scripts exactly once, in order, records them with checksums and fails startup if an applied script changed. Use Flyway for real databases with ddl-auto=validate so entities and schema stay in agreement. See Database Migrations with Flyway.

Security

31. How does Spring Security work in a Boot application?

It installs a chain of servlet filters in front of your controllers. Each request passes through filters for authentication, session or token handling, CSRF checks, header writing and finally authorization rules. You configure the chain with a SecurityFilterChain bean and authorizeHttpRequests. By default, adding the starter protects every endpoint and generates a login form and a random password. See Spring Security Fundamentals.

32. What is the difference between authentication and authorization?

Authentication answers "who are you?" (checking a password, token or certificate). Authorization answers "what may you do?" (roles, authorities, ownership rules). A 401 means the caller is not authenticated; a 403 means they are authenticated but not allowed. Authorization is enforced by URL rules and by method security such as @PreAuthorize.

33. What is CSRF, and when can you disable protection?

Cross-site request forgery tricks a logged-in user's browser into sending a state-changing request, relying on the browser to attach cookies automatically. Spring Security requires a token with unsafe methods to stop it. You may disable it for a stateless API that authenticates with a header token (such as a bearer JWT) and uses no cookie-based session, because the browser never attaches that header on its own. Never disable it for cookie-based logins. See CSRF, CORS and Secure Defaults.

34. How should passwords and tokens be handled?

Store passwords only as salted, slow hashes (bcrypt, Argon2) through a PasswordEncoder; DelegatingPasswordEncoder stores the algorithm id so you can upgrade later. For stateless APIs, a signed token such as a JWT lets a resource server verify the caller without a session lookup; keep lifetimes short, validate issuer, audience and expiry, and remember a JWT is signed, not encrypted. Revoking one before expiry needs a deny list or short lifetimes plus refresh tokens. See JWT and OAuth 2 Resource Server.

Testing

35. What is the difference between @SpringBootTest and test slices?

@SpringBootTest loads the full application context, so it is realistic but slow. A slice loads only one layer: @WebMvcTest (controllers, MockMvc), @DataJpaTest (entities and repositories on an embedded or container database, rolled back after each test), @JsonTest, @RestClientTest. Use slices for most tests and a few @SpringBootTest tests for end-to-end wiring. See Testing Spring Boot Applications.

36. How do you replace a bean with a mock in a Spring test?

Annotate a field with @MockitoBean (Spring Framework 6.2 and later; @MockBean is the older, deprecated Boot variant). Spring puts a Mockito mock into the context in place of the real bean, so a @WebMvcTest can mock the service. Plain unit tests need no Spring at all: use @ExtendWith(MockitoExtension.class) with @Mock. Every distinct mock setup creates a different context, which affects test speed. See Test Slices, Context Caching and Test Speed.

37. Why use Testcontainers instead of H2 for repository tests?

H2 is not your production database. SQL dialect, locking, JSON types, sequences and migration scripts can behave differently, so a test can pass on H2 and fail on PostgreSQL. Testcontainers starts a real PostgreSQL in Docker for the test run, and @ServiceConnection wires it into Boot automatically. The price is Docker and a few seconds of startup, softened by reusing one container per test class or run. See Integration Tests with Testcontainers.

Production

38. What is Actuator, and how do you keep it safe?

Actuator adds production endpoints: health, metrics, info, environment, beans, loggers, thread dumps and more. By default only health is exposed over HTTP. Expose others deliberately with management.endpoints.web.exposure.include, put sensitive ones behind authentication, and consider a separate management port. Exposing env, heapdump or beans publicly is a serious vulnerability. See Actuator: Health, Metrics and Info.

39. How do you shut down gracefully and support Kubernetes probes?

Set server.shutdown=graceful and spring.lifecycle.timeout-per-shutdown-phase=30s: on SIGTERM the server stops accepting new requests and lets in-flight ones finish. Actuator provides liveness and readiness health groups (/actuator/health/liveness, /actuator/health/readiness); Kubernetes uses readiness to stop routing traffic during startup and shutdown, and liveness to restart a stuck process. Together they allow zero-downtime rolling updates.

40. What do virtual threads change in a Boot application?

On Java 21 and later, spring.threads.virtual.enabled=true makes Boot run request handling and many background tasks on virtual threads. A blocking call (database, HTTP) then costs almost nothing while waiting, so a simple blocking style scales to many concurrent requests without reactive code. They do not speed up CPU-bound work, they do not remove the limit of the database connection pool, and they need care with synchronized blocks that hold a lock during blocking calls. See Performance Tuning.

Predict the output

The first program is a tiny bean factory with a singleton and a prototype scope, plus a singleton that holds a prototype and one that asks a provider every time (question 6). Before you run it, decide what number each describe line will print.

Java Singleton, prototype and the shared ticket

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The prototype produces a new number on every get, but HoldingService is a singleton, so it received ticket 3 once, when it was created, and prints 3 forever. ProviderService asks again for each call and sees 4 and then 5.

The second program is question 15: four configuration sources are searched from highest to lowest priority, and environment variables use relaxed names. Predict which source supplies each key.

Java Which source wins?

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

server.port comes from the command line even though the environment and the file also define it. app.mail.from comes from the environment because APP_MAIL_FROM is the relaxed form of the key and ranks above the profile file. app.mail.timeout falls through to the base file, and app.mail.sender is not defined anywhere.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A prototype bean is injected into a singleton through its constructor. How many instances does the singleton see?

    Injection happens once. Use ObjectProvider or a Supplier if you need a fresh prototype each time.
  2. 2. A stateless API authenticates with a bearer token in a header and has no cookie sessions. What about CSRF protection?

    CSRF abuses automatically attached credentials such as cookies. A manually added Authorization header is not sent by the attacker's page.
  3. 3. Which sentence about @Transactional is correct?

    The transaction logic lives in a proxy around the bean. Checked exceptions commit by default, and private methods or this-calls bypass the proxy.
  4. 4. Which is the best answer to 'why Testcontainers instead of H2?'

    The goal is realism. H2 is fine for fast checks, but it can behave differently from PostgreSQL or MySQL.
  5. 5. What does --debug print at startup?

    The report lists positive and negative matches with their conditions, which explains why a bean exists or is missing.

Summary

  • Bean questions test whether you understand the container: constructor injection, scopes (and the prototype-in-singleton trap), lifecycle and why cycles are a design problem.
  • Auto-configuration questions come down to conditions, back-off with @ConditionalOnMissingBean, the --debug report and the order of configuration sources.
  • REST questions test status codes, validation, global error handling with Problem Details and keeping entities out of the API.
  • JPA questions center on proxies: @Transactional rules and self-invocation, lazy loading, N+1 and schema management with Flyway.
  • Security, testing and production questions reward trade-offs: when CSRF can be disabled, slices versus full contexts, real databases in tests, exposed Actuator endpoints, graceful shutdown and virtual threads.

Next: Spring Boot Cheat Sheet.