Spring
Top 100 Spring Boot Interview Questions with Concise Answers
Curated list of the top 100 Spring Boot interview questions with short, crisp answers.
Basics & Core Concepts
-
What is Spring Boot?
Spring Boot is an opinionated framework on top of the Spring Framework that simplifies building production-ready, stand-alone Spring applications via auto-configuration, starter dependencies, and embedded servers. -
How is Spring Boot different from the Spring Framework?
Spring provides core features like DI and AOP but requires manual configuration. Spring Boot adds auto-configuration, embedded servers, starters, and Actuator for rapid development with minimal setup. -
What does the @SpringBootApplication annotation do?
It is a meta-annotation combining@SpringBootConfiguration(or@Configuration),@EnableAutoConfiguration, and@ComponentScan. It bootstraps the application and enables auto-configuration and component scanning. -
What is auto-configuration in Spring Boot?
It automatically configures beans based on the classpath, properties, and conditions (e.g.,@ConditionalOnClass,@ConditionalOnMissingBean) so you only override defaults when needed. -
How does Spring Boot find auto-configuration classes?
FromMETA-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports(or the olderspring.factoriesin earlier versions). Classes are loaded conditionally. -
What are Spring Boot starters?
Curated dependency descriptors (POMs) that pull in a compatible set of libraries for a feature, e.g.,spring-boot-starter-webfor MVC + Tomcat + Jackson. -
What is the spring-boot-starter-parent?
A parent POM that manages dependency versions via the Spring Boot BOM and provides sensible defaults for plugins and properties. -
How do you create a Spring Boot project?
Primarily via Spring Initializr (start.spring.io), or manually with Maven/Gradle, or using the Spring Boot CLI for Groovy. -
What is an embedded server in Spring Boot?
A server like Tomcat (default), Jetty, or Undertow bundled inside the application so it runs as a standalone executable JAR without an external container. -
What is the default embedded server and how do you change it?
Tomcat. Excludespring-boot-starter-tomcatand addspring-boot-starter-jetty(or Undertow, though Undertow support was removed in Boot 4).
Configuration & Profiles
-
What is application.properties / application.yml used for?
Externalized configuration for server port, database, logging, custom properties, etc. YAML supports nested structures better. -
What is the order of precedence for configuration properties?
Command-line args > Java system properties > OS environment variables > profile-specific files > defaultapplication.properties/yml> Spring Boot defaults. -
How do you override default properties?
Viaapplication.properties/yml, environment variables, command-line arguments, or@TestPropertySourcein tests. -
What are Spring profiles?
Named sets of configuration and beans for different environments (dev, test, prod). Activate withspring.profiles.active. -
How do you activate a profile?
spring.profiles.active=prodin properties,--spring.profiles.active=prodon the command line, orSPRING_PROFILES_ACTIVEenvironment variable. -
What is @Value annotation?
Injects individual property values from the Environment into fields or parameters. -
What is @ConfigurationProperties?
Binds a group of related properties (with a prefix) to a POJO, supporting nested objects, lists, and validation. Preferred over multiple@Valuefor structured config. -
What is externalized configuration?
Configuration outside the code (files, env vars, args) so the same artifact can run in different environments without recompilation. -
How do you disable auto-configuration for a specific class?
Use@SpringBootApplication(exclude = SomeAutoConfiguration.class)orspring.autoconfigure.excludeproperty. -
What is the purpose of spring.main.web-application-type=none?
Disables the embedded web server for non-web (batch/CLI) applications.
Dependency Injection & Beans
-
Why is constructor injection preferred?
Makes dependencies explicit and immutable (final), fails fast if missing, and is easier to unit-test without the Spring container. Single-constructor classes don't need@Autowired(since Spring 4.3). -
What are the differences between @Component, @Service, @Repository, and @Controller?
All are@Componentstereotypes.@Serviceis for business logic,@Repositoryenables persistence exception translation,@Controller/@RestControllerfor web handlers. Semantic + tooling differences. -
When do you use @Bean vs @Component?
@Component(and stereotypes) for classes you control that are scanned.@Beanmethods in@Configurationclasses for third-party objects or when custom construction logic is needed. -
What are bean scopes in Spring?
singleton(default, one per container),prototype(new instance each request), and web scopes:request,session,application,websocket. -
What do @Primary and @Qualifier do?
@Primarymarks the preferred bean when multiple candidates exist.@Qualifierexplicitly selects a named bean, overriding@Primary. -
What is the difference between CommandLineRunner and ApplicationRunner?
Both execute after the context is ready.CommandLineRunnerreceives rawString... args;ApplicationRunnerreceives structuredApplicationArguments. Use@Orderfor sequencing. -
What is lazy initialization?
Beans are created only when first requested (@Lazyorspring.main.lazy-initialization=true). Useful for faster startup but can hide errors until runtime. -
What is the difference between @Autowired and @Resource?
@Autowiredis by type (Spring).@Resourceis by name (JSR-250). Prefer constructor injection with@Autowiredor implicit single constructor. -
How does Spring handle circular dependencies?
By default, it fails for constructor injection. Field/setter injection can sometimes resolve via proxies, but circular dependencies indicate design issues and should be avoided. -
What is @ConditionalOnMissingBean?
A condition that creates a bean only if no bean of the same type (or name) already exists, allowing user configuration to override auto-configuration.
REST & Web Layer
-
What is the difference between @Controller and @RestController?
@RestController=@Controller+@ResponseBody. Methods return data (JSON/XML) directly instead of view names. -
Explain @RequestParam, @PathVariable, and @RequestBody.
@PathVariableextracts from URI path (/users/{id}).@RequestParamfrom query/form parameters.@RequestBodydeserializes the request body into an object. -
How do you handle exceptions globally?
Use@RestControllerAdvice(or@ControllerAdvice) with@ExceptionHandlermethods. ReturnProblemDetail(RFC 9457) for standardized errors. Enable withspring.mvc.problemdetails.enabled=true. -
How does request validation work?
Addspring-boot-starter-validation. Annotate DTOs with constraints (@NotNull,@Size, etc.) and use@Validon controller parameters. Failures throwMethodArgumentNotValidException. -
What is the difference between @Valid and @Validated?
@Validis the standard Bean Validation trigger.@Validated(Spring) supports validation groups and method-level validation. -
How do you enable CORS?
Class/method@CrossOrigin, globalWebMvcConfigurer.addCorsMappings, orCorsConfigurationSourcein the security filter chain. Prefer specific origins over*. -
What is content negotiation?
Spring selects the response format (JSON, XML) based on theAcceptheader or URL extension, usingHttpMessageConverters. -
How do you return a custom HTTP status?
UseResponseEntity.status(HttpStatus.CREATED).body(...)or@ResponseStatuson methods/exceptions. -
What is the difference between @GetMapping and @RequestMapping?
@GetMappingis a composed annotation for HTTP GET only.@RequestMappingsupports all methods and is more general. -
How do you consume/produce specific media types?
Useconsumesandproducesattributes on mapping annotations, orContent-Type/Acceptheaders.
Data Access & JPA
-
What does spring-boot-starter-data-jpa provide?
Spring Data JPA, Hibernate, HikariCP connection pool, and auto-configuration ofDataSource,EntityManagerFactory, and transaction manager. -
What is the difference between CrudRepository and JpaRepository?
CrudRepositoryprovides basic CRUD.JpaRepositoryextends it with JPA-specific features likeflush(), batch operations, and pagination support. -
How do derived query methods work?
Method names likefindByEmailAndActiveTrueare parsed by Spring Data to generate queries automatically. -
What is the N+1 query problem and how do you fix it?
Loading a collection triggers one query per association due to lazy loading. Fix withJOIN FETCH,@EntityGraph, batch fetching, or DTO projections. Disable open-in-view if possible. -
What does @Transactional do?
Declares that a method runs inside a transaction. By default, rolls back on unchecked exceptions. Supports propagation, isolation, and timeout attributes. -
What are common @Transactional pitfalls?
Self-invocation bypasses the proxy (no transaction), only public methods are proxied, and default rollback is only for RuntimeExceptions. Prefer short, focused transactions. -
What is transaction propagation?
Defines how a transactional method joins an existing transaction. Common:REQUIRED(default, join or create),REQUIRES_NEW(suspend and create new),SUPPORTS,NOT_SUPPORTED,MANDATORY,NEVER. -
How do you manage schema migrations?
Use Flyway or Liquibase. Place versioned scripts indb/migration. Spring Boot auto-runs them on startup. Avoidddl-auto=updatein production. -
What is spring.jpa.hibernate.ddl-auto?
Controls Hibernate schema generation:none(default for non-embedded),validate,update,create,create-drop. Prefer migrations overupdate. -
What is the difference between JPA and Hibernate?
JPA is the specification (API). Hibernate is the most common implementation.
Security
-
What happens when you add spring-boot-starter-security?
All endpoints require authentication by default. A default user is created with a random password logged at startup. Form login and HTTP Basic are enabled. -
How do you configure security in modern Spring Boot (no WebSecurityConfigurerAdapter)?
Define aSecurityFilterChainbean using the lambda DSL:http.authorizeHttpRequests(...).oauth2ResourceServer(...).csrf(...). -
How do you secure a REST API with JWT?
Usespring-boot-starter-oauth2-resource-server, configureissuer-uriorjwk-set-uri, and enable JWT validation in the security filter chain. Stateless, no sessions. -
When should you disable CSRF?
For stateless APIs using bearer tokens (JWT) in headers, as CSRF protects cookie-based sessions. Keep it enabled for browser form-based apps. -
How does method-level security work?
Enable with@EnableMethodSecurity. Use@PreAuthorize("hasRole('ADMIN')")or SpEL expressions. Applied via AOP proxies (self-invocation caveat applies). -
What is the difference between authentication and authorization?
Authentication verifies identity (who you are). Authorization checks permissions (what you can do). -
How do you implement custom authentication?
ImplementAuthenticationProvideror use OAuth2/JWT resource server configuration, or custom filters in the security chain. -
What is Spring Security's filter chain?
A chain of filters that handle authentication, authorization, CSRF, CORS, etc. Order matters; customize viaSecurityFilterChain.
Testing
-
What does @SpringBootTest do?
Loads the full application context. Can start an embedded server. Useful for integration tests but slower than slice tests. -
What is the difference between @WebMvcTest, @DataJpaTest, and @SpringBootTest?
@WebMvcTestslices the web layer (controllers + MockMvc).@DataJpaTestslices the JPA layer (repositories + in-memory DB).@SpringBootTestloads everything. -
How do you test REST controllers?
Use@WebMvcTest+MockMvcto perform requests and assert status, content, and headers without starting a full server. -
What is @MockBean (and its replacement in Boot 4)?
Replaces a bean with a Mockito mock in the context. In Spring Boot 4, use@MockitoBean(or@MockitoSpyBean). -
How do you test with profiles?
Use@ActiveProfiles("test")or@SpringBootTest(properties = "spring.profiles.active=test").
Actuator, Monitoring & Production
-
What is Spring Boot Actuator?
Provides production-ready endpoints for health, metrics, info, environment, loggers, etc. (/actuator/health,/actuator/metrics). -
How do you expose Actuator endpoints?
By default onlyhealthandinfoare exposed. Usemanagement.endpoints.web.exposure.include=*(carefully) or specific ones. Secure them. -
What is the health endpoint?
Aggregates health indicators (DB, disk space, custom). ReturnsUP/DOWN. Supports liveness and readiness probes for Kubernetes. -
How do you expose metrics?
Actuator + Micrometer. Common registries: Prometheus (/actuator/prometheus), Datadog, etc. Use@Timedor custom meters. -
What is graceful shutdown?
Enabled by default in recent versions. Allows in-flight requests to complete before shutdown. Configure withserver.shutdown=gracefuland timeout. -
How do you enable HTTP/2?
Setserver.http2.enabled=true(requires HTTPS in most cases).
Advanced Topics
-
What is @Async and how do you enable it?
Runs a method in a separate thread. Enable with@EnableAsync. Configure a customTaskExecutorfor control. ReturnCompletableFutureorvoid. -
How do you implement caching?
Addspring-boot-starter-cache,@EnableCaching, and use@Cacheable,@CachePut,@CacheEvict. Supports Caffeine, Redis, Ehcache, etc. -
How do you schedule tasks?
@EnableScheduling+@Scheduled(fixedRate=..., fixedDelay=..., cron=...)on methods. Use a customTaskSchedulerfor control. -
What is the difference between fixedRate and fixedDelay?
fixedRate: interval between method starts.fixedDelay: interval between method completion and next start. -
How do you use WebClient vs RestTemplate vs RestClient?
RestTemplateis legacy blocking.RestClient(Boot 3.2+) is the modern blocking fluent API.WebClientis reactive/non-blocking (WebFlux). -
What is Spring WebFlux?
Reactive web framework on Project Reactor. Non-blocking, suitable for high-concurrency, streaming, or backpressure scenarios. Uses Netty by default. -
How do you configure multiple data sources?
Define multipleDataSourcebeans with@Primaryand@Qualifier, plus separateEntityManagerFactoryandTransactionManagerconfigurations. -
What is @ConditionalOnProperty?
Creates a bean only if a property matches a value (or is present). Useful for feature flags. -
How does DevTools work?
Provides automatic restart on classpath changes, LiveReload, and remote debugging support. Exclude from production. -
What is the difference between JAR and WAR packaging?
JAR with embedded server is preferred (standalone). WAR is for deployment to an external servlet container. -
How do you package a Spring Boot app as a Docker image?
Use the Spring Boot Maven/Gradle plugin'sbuild-imagegoal (Cloud Native Buildpacks) or a Dockerfile with multi-stage builds.
Microservices & Cloud
-
What is Spring Cloud?
A set of tools for building distributed systems on Spring Boot: service discovery, config server, circuit breakers, API gateway, etc. -
What is service discovery?
Dynamic registration and lookup of service instances (e.g., Eureka, Consul, or Kubernetes DNS) so clients don't hardcode addresses. -
What is a circuit breaker?
A resilience pattern (Resilience4j) that fails fast and provides fallbacks when a downstream service is unhealthy, preventing cascade failures. -
What is Spring Cloud Config?
Centralized external configuration server that serves properties from Git or other backends, with support for encryption and profiles. -
What is an API Gateway in Spring Cloud?
Spring Cloud Gateway routes requests, applies filters (auth, rate limiting, path rewriting), and acts as the single entry point. -
How do you implement distributed tracing?
Micrometer Tracing + OpenTelemetry (or Zipkin/Brave). Propagates trace IDs across services via headers.
Recent Changes & Best Practices (Boot 3/4)
-
What are the key changes in Spring Boot 3?
Jakarta EE namespace (jakarta.*), Java 17 minimum, native image support, ProblemDetail errors, virtual threads support (Java 21), Micrometer Observation. -
What are major changes in Spring Boot 4?
Spring Framework 7, Jackson 3 (tools.jackson), modular starters (e.g.,spring-boot-starter-webmvc), Undertow removed, JUnit 4 removed,@MockBeanreplaced by@MockitoBean, built-in retry, API versioning support. -
Why was Undertow removed in Boot 4?
Lack of support for Servlet 6.1 (Jakarta EE 11). Use Tomcat 11 or Jetty 12. -
How do you handle Jackson 3 migration?
Package change fromcom.fasterxml.jacksontotools.jackson. Update imports; optionally setspring.jackson.use-jackson2-defaults=truefor compatibility. -
What is the recommended migration path to Boot 4?
Upgrade to Boot 3.5 first, eliminate all deprecation warnings, then migrate to 4.x. Use the properties migrator dependency temporarily. -
What is native image support?
GraalVM native compilation for faster startup and lower memory. Requires careful configuration of reflection, resources, and dynamic proxies. -
How do you enable virtual threads?
spring.threads.virtual.enabled=true(Java 21+). Suitable for I/O-bound workloads; be cautious with synchronized blocks and pinning. -
What is API versioning support in Boot 4?
Native support via@GetMapping(version = "2.0")or headers/paths, with auto-configuration for MVC and WebFlux. -
Why prefer RestClient over RestTemplate?
RestTemplate is in maintenance mode. RestClient offers a modern, fluent, builder-style API with better defaults and is the recommended blocking client.
Miscellaneous & Practical
-
How do you log in Spring Boot?
SLF4J + Logback (default). Configure levels in properties (logging.level.com.example=DEBUG). Use structured logging for production. -
What is the difference between @ControllerAdvice and @RestControllerAdvice?
@RestControllerAdviceis@ControllerAdvice+@ResponseBody, so handlers return data directly (ideal for REST). -
How do you customize the error response?
ImplementErrorController, use@ControllerAdvice, or rely onProblemDetail. OverrideBasicErrorControllerif needed. -
What is the purpose of @EnableAutoConfiguration?
Triggers auto-configuration. Usually not used directly because it is included in@SpringBootApplication. -
What are best practices for Spring Boot applications?
Prefer constructor injection, keep transactions short, use profiles, externalize config, secure Actuator, use Flyway/Liquibase, write slice tests, monitor with Actuator + metrics, and follow the principle of convention over configuration while overriding only when necessary.