Spring Boot Interview Questions and Answers
A complete list of 427+ Spring Boot interview questions and answers, organized by topic. Click any question to jump straight to its detailed answer with code examples.
8 topics 427 questions
Spring Boot Core
Auto-Configuration
- What is auto-configuration in Spring Boot?
- How does @EnableAutoConfiguration find the auto-configuration classes to apply?
- What three annotations does @SpringBootApplication combine?
- What are the main @Conditional annotations used in auto-configuration?
- How does @ConditionalOnMissingBean let you override an auto-configured bean?
- What is a Spring Boot starter and how does it relate to auto-configuration?
- How do you see which auto-configurations were applied and which backed off?
- How do you exclude a specific auto-configuration?
- What is the difference between @AutoConfiguration and @Configuration?
- How do you control the order in which auto-configurations run?
- When are auto-configuration conditions evaluated, and why does that matter?
- How do you write your own auto-configuration for a shared library?
- How does auto-configuration use @ConfigurationProperties to stay configurable?
- What is a FailureAnalyzer and how does it relate to startup configuration?
- How would you swap the auto-configured embedded Tomcat for Jetty or Undertow?
- Why is proxyBeanMethods=false common in auto-configuration classes?
Properties & Profiles
- What is externalized configuration in Spring Boot?
- What is the order of precedence for Spring Boot property sources?
- What is the difference between @ConfigurationProperties and @Value?
- What is a Spring profile?
- What are the ways to activate a Spring profile?
- How do profile-specific property files work?
- What is relaxed binding in Spring Boot?
- What are the trade-offs between YAML and .properties configuration?
- How do you validate @ConfigurationProperties at startup?
- How does constructor binding work for immutable @ConfigurationProperties?
- How do profile expressions and grouping work?
- What is the difference between spring.profiles.active and the "default" profile?
- How should you handle secrets and credentials in Spring Boot configuration?
- What does @EnableConfigurationProperties do and when do you need it?
- How do property placeholders and default values work?
- What is spring.config.import and how does it extend configuration loading?
Application Lifecycle
- What happens when you call SpringApplication.run()?
- What is the ApplicationContext?
- What are the main bean lifecycle callbacks?
- What is the difference between CommandLineRunner and ApplicationRunner?
- What are the key application lifecycle events Spring Boot fires?
- What happens during ApplicationContext refresh()?
- How does graceful shutdown work in Spring Boot?
- What is SmartLifecycle and when would you use it?
- How does lazy initialization affect the application lifecycle?
- How do you control bean initialization order?
- How can you customize SpringApplication before it runs?
- When should you use @PostConstruct versus a CommandLineRunner?
- How do you control the exit code of a Spring Boot application?
- How does Spring Boot register a shutdown hook and when do destroy callbacks run?
- What is the Spring Boot banner and how do you customize it?
- What happens if a bean fails to initialize during startup?
Spring Boot Dependency Injection
IoC Container
- What is Inversion of Control (IoC) and how does Spring implement it?
- What is the difference between IoC and dependency injection?
- What is a Spring bean?
- What is the difference between BeanFactory and ApplicationContext?
- How does the ApplicationContext discover which beans to create?
- What are the main phases of a Spring bean's lifecycle?
- What is the default bean scope and what does it mean?
- What is the difference between singleton and prototype scope?
- What are request and session scopes used for?
- Why do you need a scoped proxy when injecting a shorter-lived bean into a singleton?
- What does @Lazy do and when would you use it?
- Why is constructor injection preferred over calling context.getBean()?
- What is a BeanPostProcessor and what is it used for?
- How does Spring handle circular dependencies?
- How are bean names assigned and how do you customize them?
- What is the sequence of events when the IoC container starts up?
Component Annotations
- What does @Component do?
- What is the difference between @Component, @Service, @Repository, and @Controller?
- What is @RestController and how does it differ from @Controller?
- What does @Autowired do?
- What are the three types of dependency injection in Spring?
- Why is constructor injection recommended over field injection?
- How does component scanning work?
- How do you include or exclude specific classes from component scanning?
- What is the difference between @Configuration and @Component for defining beans?
- When should you use @Bean instead of @Component?
- How do you autowire all beans of a given type?
- How do you handle an optional or possibly-missing dependency?
- What does @DependsOn do?
- What does @Primary do when multiple candidate beans exist?
- How does @Profile control whether a component becomes a bean?
- Why can field injection cause problems in tests and with immutability?
Qualifiers & Resolution
- How does Spring decide which bean to inject?
- What does @Qualifier do?
- When should you use @Qualifier versus @Primary?
- What causes NoUniqueBeanDefinitionException and how do you fix it?
- How do you create a custom qualifier annotation?
- How can a custom qualifier carry an attribute value?
- How do you qualify beans defined by @Bean methods?
- What is the difference between @Autowired and @Resource for injection?
- How does the JSR-330 @Inject annotation relate to @Autowired?
- How do you control the order of beans injected as a collection?
- How does ObjectProvider help with optional or multiple candidate beans?
- How can generic type parameters act as an implicit qualifier?
- Can you combine @Qualifier with collection injection to inject a subset of beans?
- What is a @Fallback bean and how does it differ from @Primary?
- How do you debug why the wrong bean (or no bean) was injected?
Bean Configuration
- What are @Configuration and @Bean used for?
- How does a @Bean method receive its own dependencies?
- How do you specify init and destroy methods for a @Bean?
- What does @Value do?
- When should you use @ConfigurationProperties instead of @Value?
- How do you make a bean conditional on a property?
- How do you write a custom @Conditional?
- How do you set a non-default scope on a bean?
- What does @Import do?
- What happens when two beans are defined with the same name?
- How do you use SpEL expressions in bean configuration?
- What is the trade-off between Java @Bean config and component scanning?
- How do you validate @ConfigurationProperties values at startup?
- What is a FactoryBean and when would you use one?
- How can you customize the names Spring generates for scanned beans?
Spring Boot Web MVC
REST Controllers
- What is @RestController?
- What is the difference between @RequestMapping and @GetMapping/@PostMapping?
- How do you read a value from the URL path?
- How do you read query string parameters?
- When should you use @PathVariable versus @RequestParam?
- How do you receive a JSON request body?
- What is ResponseEntity and when do you need it?
- How do you set the HTTP status code for a successful response?
- What is the DispatcherServlet and how does it route a request?
- How does Spring decide between JSON and XML for a response?
- What do the consumes and produces attributes do?
- Are Spring MVC controllers thread-safe? How are they scoped?
- How do you read an HTTP header in a controller?
- Can one controller method handle more than one URL or HTTP method?
- What are the conventions for designing RESTful controller endpoints?
Request & Response Handling
- What are HttpMessageConverters?
- What do @RequestBody and @ResponseBody do?
- How do you set response headers?
- How do you read and write cookies?
- How do you handle file uploads?
- What is the Location header and when should you set it?
- How do you enable CORS in Spring MVC?
- What is the difference between a HandlerInterceptor and a Servlet Filter?
- How do you keep per-request state when controllers are singletons?
- How do you return a response asynchronously?
- How do you access the raw HttpServletRequest or response?
- How do you stream a large response without loading it all into memory?
- How do you send a redirect from a controller?
- What does Spring return by default when request binding fails?
- How does Spring decide the character encoding and content type of a response?
Exception Handling
- What is @ExceptionHandler?
- What is @RestControllerAdvice and why use it?
- How does @ResponseStatus on an exception class work?
- What does Spring Boot do with an unhandled exception by default?
- If multiple @ExceptionHandlers could match, which one wins?
- What is ResponseEntityExceptionHandler?
- What is ProblemDetail (RFC 7807)?
- How do you design a consistent error response for an API?
- Should you throw checked or unchecked exceptions from controllers and services?
- How do you turn bean-validation failures into a clean error response?
- How should you log exceptions in a global handler without spamming logs?
- Does @ExceptionHandler catch exceptions from @Async methods or filters?
- Should a service catch a low-level exception and rethrow a domain one?
- How do you return a custom 404 for an unknown URL (no matching handler)?
- What's the trade-off between @ResponseStatus, ResponseEntity, and ProblemDetail in handlers?
Validation & Serialization
- What is the difference between @Valid and @Validated?
- What are the common Bean Validation constraints?
- How do you write a custom validation constraint?
- What are validation groups and when do you need them?
- How do you validate nested objects and collections?
- How does Spring Boot serialize objects to JSON?
- What do @JsonProperty, @JsonIgnore, and @JsonInclude do?
- How do you control how dates are serialized?
- Why should you serialize DTOs instead of JPA entities?
- How do you make Jackson use snake_case JSON?
- How do you customize the global ObjectMapper?
- What happens when JSON has fields your object doesn't?
- How do you validate @RequestParam and @PathVariable values?
- How does Jackson deserialize immutable objects and records?
- What exception is thrown when @Valid fails, and how do you shape the 400?
Spring Boot Data Access
JPA Entities
- What is a JPA entity?
- What are the @GeneratedValue strategies and which should you use?
- What does @Column configure and when do you need it?
- How do you map an entity to a specific table name?
- What is the difference between field and property access in JPA?
- How do you exclude a field from persistence?
- What are @Embeddable and @Embedded used for?
- How should you map an enum field, and why does @Enumerated(STRING) matter?
- What are the JPA entity lifecycle states?
- What is dirty checking?
- How should you implement equals() and hashCode() on a JPA entity?
- What does spring.jpa.hibernate.ddl-auto control?
- How do you map dates and large objects?
- What is @MappedSuperclass and how does auditing use it?
- What is the Open Session in View pattern and why is it controversial?
Relationships & Fetching
- What are the four JPA association types?
- What is the difference between the owning and inverse side of a relationship?
- Why do you need helper methods on bidirectional associations?
- What are the default fetch types and why prefer LAZY?
- What is the N+1 select problem?
- How does JOIN FETCH solve N+1?
- What is an @EntityGraph and how does it differ from JOIN FETCH?
- What do cascade types do?
- What is orphanRemoval and how does it differ from cascade REMOVE?
- How do you map a @ManyToMany and customize the join table?
- Why replace @ManyToMany with an explicit join entity?
- What causes a LazyInitializationException and how do you fix it?
- How does Hibernate batch fetching reduce N+1?
- Why is FetchType only a hint for EAGER?
- How do DTO projections avoid loading full entity graphs?
Spring Data Repositories
- What is a Spring Data repository?
- What is the Spring Data repository hierarchy?
- How do derived query methods work?
- When and how do you use @Query?
- How do you write a native SQL query?
- Why do update/delete queries need @Modifying?
- How do paging and sorting work?
- What return types can repository methods have?
- What are interface and class projections?
- How does Spring generate the repository implementation?
- How do you add custom behavior to a repository?
- What is the difference between save, saveAndFlush, and saveAll?
- What is Query by Example?
- How does Spring Boot find and register repositories?
- When would you use getReferenceById instead of findById?
Transactions
- What does @Transactional do?
- At which layer should @Transactional go?
- Which exceptions trigger a rollback by default?
- What is the default propagation, REQUIRED, and how does it behave?
- When would you use Propagation.REQUIRES_NEW?
- What do the other propagation levels do?
- What are transaction isolation levels?
- What does @Transactional(readOnly = true) do?
- Why does @Transactional fail when calling a method on the same class?
- Why doesn't @Transactional work on private or final methods?
- What is the difference between flush and commit?
- What is optimistic locking and how does @Version work?
- When would you use pessimistic locking instead?
- Why don't transactions propagate to @Async methods or new threads?
Spring Boot Security
Security Basics
- What is Spring Security and how does it plug into a Spring Boot app?
- How does Spring Security work under the hood — the filter chain?
- What is the difference between authentication and authorization?
- How do you configure security with a SecurityFilterChain bean?
- Where does the default login user and password come from?
- What is the SecurityContext and SecurityContextHolder?
- Why must you use a PasswordEncoder, and which one?
- What is the difference between a role and an authority?
- What is CSRF protection and when should you disable it?
- How does CORS relate to Spring Security?
- What is the difference between stateless and session-based security?
- What is the difference between permitAll and authenticated, and what is the anonymous user?
- What is the difference between URL-based and method-level security?
- How and why would you define multiple SecurityFilterChain beans?
- What are common Spring Security configuration mistakes?
Authentication
- How does the authentication process work in Spring Security?
- What is UserDetailsService and how do you implement it?
- What is the UserDetails interface?
- What is the AuthenticationManager and AuthenticationProvider?
- What does DaoAuthenticationProvider do?
- What is the difference between form login and HTTP Basic authentication?
- How do you access the currently authenticated user in a controller?
- How do you set up in-memory authentication?
- How do you implement a custom AuthenticationProvider?
- Why does Spring throw BadCredentialsException even when the username doesn't exist?
- How does Spring Security handle disabled, locked, or expired accounts?
- How can you react to login success and failure?
- How does logout work in Spring Security?
- What is remember-me authentication?
- What are the principal, credentials, and authorities on an Authentication?
Authorization
- How do you configure URL-based authorization rules?
- What are request matchers and how do you target paths and methods?
- How do you enable method-level security?
- What is the difference between @PreAuthorize and @PostAuthorize?
- What is the difference between @Secured, @RolesAllowed, and @PreAuthorize?
- What can you express in SpEL access expressions?
- What do @PreFilter and @PostFilter do?
- What happens on an authorization failure, and how do you customize the 403?
- How do you set up a role hierarchy?
- Should you secure the URL layer, the method layer, or both?
- Why is it better to secure the service layer than the controller?
- How do you implement domain-object (instance-level) authorization?
- What is the AuthorizationManager in modern Spring Security?
- How do you allow public access to some endpoints while securing the rest?
- How do you test authorization rules?
JWT & OAuth2
- What is a JWT and what is it made of?
- Why are JWTs well suited to stateless authentication?
- How do you configure Spring Boot as an OAuth2 resource server validating JWTs?
- What does Spring validate when it receives a JWT?
- What is the difference between OAuth2 and OpenID Connect?
- How do you add social/SSO login with oauth2Login?
- What is the OAuth2 authorization-code flow?
- How do JWT scopes and claims become Spring Security authorities?
- What is the difference between an access token and a refresh token?
- How do you revoke or invalidate a JWT before it expires?
- Where should a browser client store a JWT?
- Should a JWT be signed with a symmetric or asymmetric key?
- When should you choose JWTs over server-side sessions?
- What are common JWT security pitfalls?
Spring Boot Testing
Unit Testing
- What is a unit test in a Spring Boot app, and what should it NOT load?
- What are the core JUnit 5 annotations you use in unit tests?
- Why avoid loading the Spring context in unit tests?
- How do you use Mockito to mock a collaborator?
- What does @ExtendWith(MockitoExtension.class) with @Mock and @InjectMocks do?
- What is the difference between @Mock and @MockBean?
- How do you verify that a method was called with Mockito?
- What is an ArgumentCaptor and when do you use one?
- Why does Spring Boot favor AssertJ over plain JUnit assertions?
- How do you assert that code throws an exception?
- How does constructor injection make a class easier to unit test?
- How do you stub a void method or make a mock throw?
- Should you unit test private methods directly?
- What is an UnnecessaryStubbingException and how do you handle it?
- How do you unit test code that depends on the current time or random values?
Slice Testing
- What is a test slice in Spring Boot?
- What does @WebMvcTest load and how do you use it?
- What is MockMvc and how does it differ from a real HTTP call?
- Why does @WebMvcTest not pick up your @Service beans?
- What does @DataJpaTest set up?
- What is TestEntityManager and why use it over the repository under test?
- How do you make @DataJpaTest run against your real database instead of H2?
- What is @JsonTest for?
- What does @RestClientTest do?
- How does @MockBean work inside a slice test?
- When should you use a slice instead of @SpringBootTest?
- How do you handle security in a @WebMvcTest?
- How do you assert on the JSON body in a MockMvc test?
- What are common mistakes when writing slice tests?
- How do you add extra auto-configuration to a slice that excludes it by default?
Integration Testing
- What is an integration test in Spring Boot and how does it differ from a slice test?
- What does the webEnvironment attribute of @SpringBootTest control?
- How do you make real HTTP calls in an integration test?
- What are Testcontainers and why use them for integration tests?
- How does @ServiceConnection simplify wiring Testcontainers to Spring Boot?
- How does Spring's test context caching work and why does it matter?
- What does @DirtiesContext do and when should you use it?
- Why are @SpringBootTest tests with @Transactional rolled back, and what's the catch?
- How do you use a dedicated test profile and configuration?
- How do you set up and tear down test data in an integration test?
- When do you choose @SpringBootTest over @WebMvcTest for testing a controller?
- How do you test asynchronous behavior in an integration test?
- How do you get the actual port when using RANDOM_PORT?
- What are common integration-testing mistakes?
- How are integration tests typically named and run separately from unit tests?
Spring Boot Actuator & Observability
Actuator Endpoints
- What is Spring Boot Actuator and why does it matter for production?
- How do you add Actuator to a Spring Boot project?
- What are the most important built-in Actuator endpoints?
- What is the difference between enabling and exposing an Actuator endpoint?
- Why is only /health exposed over HTTP by default, and how do you expose more?
- What is the /actuator base path and how do you change it?
- How does the /health endpoint work and what does show-details control?
- What are health groups and why are they useful in Kubernetes?
- How do you expose Actuator on a separate management port?
- How do you secure Actuator endpoints, and why is exposing everything dangerous?
- How does JMX exposure differ from web exposure for Actuator endpoints?
- What populates the /info endpoint and how do you add build and git details?
- Which Actuator endpoints are most sensitive and what's the risk?
- How do you view and change log levels at runtime with the /loggers endpoint?
- How do you write a custom Actuator endpoint?
Custom Health & Metrics
- What is a HealthIndicator in Spring Boot Actuator?
- What are the built-in Status values a Health object can report?
- How does one DOWN indicator make the whole /health endpoint report DOWN?
- What built-in health indicators does Spring Boot auto-configure?
- What are health groups and why are they useful?
- How do health groups map to Kubernetes liveness and readiness probes?
- How do you control which HTTP status code a health status returns?
- How is health implemented in a reactive (WebFlux) application?
- What is Micrometer and how does it relate to Spring Boot Actuator?
- What are the main meter types in Micrometer?
- How do you create a custom metric by injecting MeterRegistry?
- What do the @Timed and @Counted annotations do?
- What are tags on a metric and why does cardinality matter?
- How do you export Micrometer metrics to Prometheus?
- What is a MeterBinder and when would you use one?
Logging
- What is Spring Boot's default logging stack?
- Why does Spring Boot log through a facade (SLF4J) instead of a concrete library?
- How does Spring Framework itself log, given it depends on Commons Logging?
- How do you change log levels in Spring Boot?
- What are logging groups and why are they useful?
- How do you make Spring Boot write logs to a file?
- How do you customize the log message pattern?
- How is log file rotation configured in Spring Boot?
- How and why would you switch from Logback to Log4j2?
- What's the difference between logback.xml and logback-spring.xml?
- What do <springProfile> and <springProperty> do in logback-spring.xml?
- How do you enable structured (JSON) logging in Spring Boot?
- How do you change a log level at runtime without a restart?
- Why use parameterized logging instead of string concatenation?
- What is MDC and how does it help with request tracing?
- What do the --debug/debug=true flags do, and how does Lombok's @Slf4j help?
Spring Boot Async & Messaging
Async & Scheduled Tasks
- What does @Async do and how do you turn it on?
- What can an @Async method return?
- Why does calling an @Async method from within the same class run synchronously?
- Which executor runs @Async methods by default, and why is that a problem?
- How do you make @Async use a specific executor?
- How are exceptions from @Async methods handled?
- How do you schedule recurring tasks in Spring Boot?
- What is the difference between fixedRate and fixedDelay?
- How do you schedule a task with a cron expression?
- How do you make a schedule configurable without recompiling?
- How many threads run scheduled tasks by default, and why does it matter?
- What happens if a @Scheduled method throws an exception?
- When would you use @Async versus @Scheduled?
- Can you combine @Scheduled and @Async on the same method?
- Why is @Scheduled dangerous when you run multiple application instances?
- How do you ensure in-flight async tasks finish during shutdown?
Application Events
- What is the Spring application event mechanism?
- How do you publish an event?
- How do you listen for an event?
- Are event listeners synchronous or asynchronous by default?
- How do you make an event listener asynchronous?
- How do you listen only for events that match a condition?
- What happens if an @EventListener returns a value?
- How do you control the order multiple listeners run in?
- What is @TransactionalEventListener and why use it?
- What happens to a @TransactionalEventListener if there is no active transaction?
- How do you publish and listen for generic (typed) events?
- What built-in application events does Spring Boot publish?
- When should you use events instead of just calling a method?
- What happens if a synchronous listener throws an exception?
- Can application events replace a message broker like Kafka or RabbitMQ?
- Why might an @Async listener not see the publisher's transaction or security context?
Messaging Basics
- Why use a message broker instead of a direct REST call between services?
- How do JMS, AMQP, and Kafka differ?
- What is the difference between a queue and a topic?
- Which Spring Boot starters enable messaging, and what auto-configures?
- How do you send and receive with JMS in Spring?
- How does RabbitMQ routing work with exchanges and bindings?
- How do you produce and consume with Kafka in Spring?
- What ordering guarantees does Kafka provide?
- What are acknowledgement modes and why do they matter?
- What is the difference between at-least-once and at-most-once delivery?
- Why must consumers usually be idempotent, and how do you achieve it?
- What is a dead-letter queue and when is it used?
- How do objects become messages — what is a MessageConverter?
- What is the dual-write problem and how do you handle it?
- How do you scale message consumption?
- What is a poison message and how do you stop it from blocking a queue?
More ways to practice
The self-quiz is live. Join our channel for updates, new content & tech tips.