3. Spring Boot Interview Q&A
Dashboard
50 Master Q&A Set
Home › Spring Boot Interview Q&A

⚡ Spring Boot Technical Interview Questions & Answers

Complete 50-Question Master Guide covering Spring Boot Fundamentals, Auto-Configuration, Actuator, DevTools, REST APIs, Exception Handling, Testing, Caching, and Production Deployment.

📌 Index of Topics Covered (50 Questions)

SectionCategoryQuestion RangeKey Concepts Included
1. Boot FundamentalsAuto-Config & StartersQ1 – Q10What is Spring Boot, Spring MVC vs Boot, Starters, Auto-Configuration, @SpringBootApplication, Stereotypes, RestController, Constructor DI
2. Lifecycle & ConfigActuator & PropertiesQ11 – Q20Bean Lifecycle, Spring Boot Actuator, DevTools, properties vs yml, Profiles, @ConfigurationProperties vs @Value, Embedded Tomcat & Jetty
3. Runners & WebRunners, REST & ValidationQ21 – Q30CLI, CommandLineRunner vs ApplicationRunner, Global Exception Handling (@RestControllerAdvice), Data Validation (@Valid vs @Validated), Testing starters
4. Testing & ConfigTesting & Security ConfigQ31 – Q40@MockBean, @DataJpaTest, Multiple DataSources, Auto-Restart, Banner, Externalized Config, Logging, Changing Port, HTTPS, CORS
5. Advanced FeaturesCaching, Async & HealthQ41 – Q50Cache (@Cacheable), Scheduling (@Scheduled), Async (@Async), File Upload, Secrets Management, Health Indicators, Startup & Performance Tuning, Deployment & Best Practices

1. Spring Boot Fundamentals (Q1 – Q10)

Q1: What is Spring Boot?
Answer: Spring Boot is an extension of the Spring Framework that simplifies enterprise application development by providing:
  • Auto Configuration: Automatically configures Spring beans based on classpath dependencies.
  • Embedded Web Servers: Built-in Tomcat, Jetty, or Undertow servers (no external WAR deployment required).
  • Starter Dependencies: Single aggregated Maven/Gradle dependencies that pull in all compatible libraries.
  • Production-Ready Features: Health checks, metrics, and externalized config out-of-the-box.
  • Minimal Configuration: Eliminates boilerplate XML configuration.
Q2: Why use Spring Boot instead of Spring MVC?
Answer:
FeatureSpring MVCSpring Boot
ConfigurationRequires extensive XML or Java ConfigZero XML, Auto-Configuration
Web ServerRequires external Tomcat/WildFly WAR deploymentEmbedded Tomcat/Jetty executable JAR
Dependency ManagementMust manage individual library versions manuallyStarter dependencies with managed BOM versions
Development SpeedSlower setup timeRapid setup & instant execution
Q3: What are Spring Boot Starters? Give examples.
Answer: Predefined dependency bundles that simplify build configuration.
Common Starters:
  • spring-boot-starter-web: Restful APIs, Spring MVC, Jackson JSON, and Embedded Tomcat.
  • spring-boot-starter-data-jpa: Spring Data JPA, Hibernate, and HikariCP connection pool.
  • spring-boot-starter-security: Spring Security authentication & authorization.
  • spring-boot-starter-test: JUnit 5, Mockito, AssertJ, and Spring Test.
  • spring-boot-starter-cache: Spring Caching support (Caffeine, Redis, Ehcache).
Q4: Explain Auto Configuration.
Answer: Spring Boot automatically configures beans based on:
  • Classpath dependencies (present JARs)
  • Existing beans (custom beans override defaults)
  • Application properties
Example: If spring-boot-starter-web is on the classpath, Spring Boot automatically configures DispatcherServlet, Jackson ObjectMapper, and embedded Tomcat.
Q5: How does Auto Configuration work internally?
Answer: 1. Uses @EnableAutoConfiguration.
2. Internally loads configuration class names listed in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports.
3. Each auto-configuration class evaluates conditional annotations before registering beans: - @ConditionalOnClass: Registers bean if specific class is present on classpath. - @ConditionalOnBean: Registers bean if another specific bean exists. - @ConditionalOnMissingBean: Registers default bean ONLY IF user hasn't defined a custom one.
Q6: What is `@SpringBootApplication`?
Answer: A composite convenience annotation combining three annotations:
  • @Configuration: Tags the class as a source of bean definitions.
  • @EnableAutoConfiguration: Enables Spring Boot's auto-configuration mechanism.
  • @ComponentScan: Enables component scanning on the package of the declaring class and its sub-packages.
Q7: Difference between `@Component`, `@Service`, and `@Repository`?
Answer:
  • @Component: General-purpose Spring bean archetype.
  • @Service: Specializes @Component to hold business logic.
  • @Repository: Specializes @Component for database access layer; automatically translates SQL vendor exceptions into Spring's DataAccessException hierarchy.
Q8: Difference between `@RestController` and `@Controller`?
Answer:
  • @Controller: Used for traditional Spring MVC web applications returning HTML views (e.g. Thymeleaf/JSP). Requires @ResponseBody on methods to return raw data.
  • @RestController: Combination of @Controller and @ResponseBody. Automatically serializes Java objects directly into JSON/XML HTTP response payloads.
Q9: What is Dependency Injection and how do you implement it?
Answer: Injecting required object dependencies at runtime instead of instantiating them manually using new.
Modes: Constructor Injection, Field Injection, and Setter Injection.
Constructor Injection is strongly recommended.
Q10: Why is Constructor Injection recommended?
Answer:
  • Allows creating immutable beans using final fields.
  • Enables easy unit testing without launching Spring context (pass mocks directly into constructor).
  • Prevents NullPointerException at runtime (guarantees mandatory dependencies exist at object creation).
  • Triggers immediate circular dependency detection at application startup.

2. Lifecycle & Configuration (Q11 – Q20)

Q11: Explain the Spring Bean Lifecycle.
Answer:
Instantiate BeanDependency InjectionAware Callbacks@PostConstructBean Ready@PreDestroyDestroyed
Q12: What is Spring Boot Actuator? List key endpoints.
Answer: Provides production-grade monitoring and management features for running applications.
Key Endpoints:
  • /actuator/health: Shows application health status (UP/DOWN).
  • /actuator/info: Displays arbitrary application build & git info.
  • /actuator/metrics: Exposes Micrometer metrics (CPU, Memory, JVM, HTTP requests).
  • /actuator/env: Exposes active environment properties.
  • /actuator/loggers: Views and dynamically modifies logger levels at runtime.
  • /actuator/threaddump: Generates a JVM thread dump for diagnosing deadlocks.
Q13: What is Spring Boot DevTools?
Answer: Development-time module offering:
  • Automatic Restart: Restarts application whenever files on classpath change.
  • LiveReload: Triggers browser refresh automatically when static assets change.
  • Disables template caching by default for faster iteration.
Q14: What is `application.properties`?
Answer: Central key-value configuration file used to customize Spring Boot defaults.
server.port=8081
spring.datasource.url=jdbc:mysql://localhost:3306/db
logging.level.root=INFO
Q15: Difference between `application.properties` and `application.yml`?
Answer: Both configure application settings. YAML (.yml) supports hierarchical data structuring, avoiding repetitive prefixes and making complex configuration significantly more readable than flat properties files.
Q16: How do Profiles work in Spring Boot?
Answer: Profiles isolate environment-specific configurations (e.g. application-dev.yml, application-prod.yml). Activate a profile via:
  • application.yml: spring.profiles.active=prod
  • JVM Parameter: -Dspring.profiles.active=prod
  • Environment Variable: SPRING_PROFILES_ACTIVE=prod
Q17: What is `@ConfigurationProperties`?
Answer: Binds nested external properties directly into type-safe Java objects.
@ConfigurationProperties(prefix = "app.mail") maps app.mail.host and app.mail.port to corresponding Java fields automatically.
Q18: Difference between `@Value` and `@ConfigurationProperties`?
Answer:
  • @Value: Used for individual property injection (e.g. @Value("${server.port}")), supports SpEL expressions, no relaxed binding.
  • @ConfigurationProperties: Used for bulk hierarchical property binding, supports type-safe validation (JSR-380), relaxed property name binding, better maintainability.
Q19: Explain Embedded Tomcat.
Answer: Spring Boot packages Apache Tomcat web server inside the executable JAR file itself. Running java -jar app.jar boots the server and deploys the application automatically without requiring external server installation.
Q20: Can Spring Boot use Jetty instead of Tomcat? How?
Answer: Yes. Exclude Tomcat from spring-boot-starter-web and include spring-boot-starter-jetty in your pom.xml.

3. Runners, Web & Validation (Q21 – Q30)

Q21: What is Spring Boot CLI?
Answer: A developer command-line interface tool used to rapidly prototype Spring applications using Groovy scripts without verbose boilerplate.
Q22: What is CommandLineRunner?
Answer: An interface used to execute initialization code after the Spring ApplicationContext has loaded. Accepts raw command-line arguments as String... args.
Q23: What is ApplicationRunner?
Answer: Similar to CommandLineRunner, but receives parsed ApplicationArguments providing access to option vs non-option arguments.
Q24: Difference between CommandLineRunner and ApplicationRunner?
Answer: CommandLineRunner.run(String... args) receives raw strings, whereas ApplicationRunner.run(ApplicationArguments args) provides structured parsing for option flags (--option=value).
Q25: How do you handle exceptions globally in Spring Boot?
Answer: Create a global exception handler class annotated with @RestControllerAdvice containing methods annotated with @ExceptionHandler(CustomException.class) returning clean error payloads.
Q26: What is `@ControllerAdvice`?
Answer: A specialized @Component that allows applying exception handling, model attributes, and data binding rules globally across all controllers.
Q27: How do you validate request data?
Answer: Annotate controller payload parameters with @Valid and domain class fields with JSR-380 validation annotations (@NotNull, @NotBlank, @Email, @Size(min=2)).
Q28: Difference between `@Valid` and `@Validated`?
Answer:
  • @Valid: Standard Java/Jakarta Bean Validation annotation (no validation groups).
  • @Validated: Spring-specific extension supporting **Validation Groups** (validating different constraints for Create vs Update scenarios) and method-level parameters.
Q29: What is included in `spring-boot-starter-test`?
Answer: JUnit 5 (Jupiter), Mockito (mocking framework), Spring Test & Spring Boot Test, AssertJ (fluent assertions), Hamcrest (matchers), JSONPath, and Skyscreamer JSONassert.
Q30: Difference between `@SpringBootTest` and `@WebMvcTest`?
Answer:
  • @SpringBootTest: Loads full ApplicationContext for comprehensive integration testing (slower).
  • @WebMvcTest: Loads ONLY the web layer (controllers, converters, Jackson) while mocking service/repository beans via @MockBean (fast slice test).

4. Testing & Security Configuration (Q31 – Q40)

Q31: What is `@MockBean`?
Answer: Annotation that creates a Mockito mock and registers it in the Spring ApplicationContext, replacing any existing bean of the same type for isolated testing.
Q32: What is `@DataJpaTest`?
Answer: A slice test annotation that configures an in-memory database (like H2), configures Hibernate/JPA, and scans ONLY @Repository interfaces and @Entity classes.
Q33: How do you connect to multiple databases in Spring Boot?
Answer: Configure two distinct configuration classes, each defining its own: 1. DataSource
2. LocalContainerEntityManagerFactoryBean
3. PlatformTransactionManager
Mark one DataSource configuration as @Primary.
Q34: What is Spring Boot Auto Restart?
Answer: DevTools feature that monitors classpath directory changes and automatically triggers a fast application context restart.
Q35: What is Spring Boot Banner and how to customize it?
Answer: ASCII logo displayed during startup. Customize by creating a banner.txt file in src/main/resources or disable using spring.main.banner-mode=off.
Q36: What is Externalized Configuration precedence order?
Answer: Order of precedence (highest overrides lowest): 1. Command-line arguments (--server.port=9000)
2. JVM System properties (-Dserver.port=9000)
3. OS Environment variables
4. Profile-specific configuration (application-prod.yml)
5. Application properties (application.yml)
Q37: What is Spring Boot Logging architecture?
Answer: Uses SLF4J facade with **Logback** as default implementation out-of-the-box. Supports console and file appenders configured via application.yml or logback-spring.xml.
Q38: How do you change the default port?
Answer: In application.properties: server.port=9090, or via command line: java -jar app.jar --server.port=9090.
Q39: How do you enable HTTPS in Spring Boot?
Answer: Configure SSL properties in application.yml:
server.port=8443
server.ssl.key-store=classpath:keystore.p12
server.ssl.key-store-password=secret
server.ssl.key-store-type=PKCS12
Q40: What is CORS in Spring Boot and how to configure it?
Answer: Cross-Origin Resource Sharing permits browser clients on different domains/ports to access APIs.
- Controller-level: Add @CrossOrigin(origins = "https://frontend.com").
- Global-level: Implement WebMvcConfigurer.addCorsMappings().

5. Advanced Features & Best Practices (Q41 – Q50)

Q41: What is Spring Boot Cache and key annotations?
Answer: Abstraction layer supporting caching providers.
- @EnableCaching: Enables caching support.
- @Cacheable: Caches method result based on input key.
- @CachePut: Always executes method and updates cache.
- @CacheEvict: Removes entries from cache.
Q42: What is Spring Boot Scheduling?
Answer: Enables executing background tasks periodically using @EnableScheduling and @Scheduled(cron = "0 0 * * * *") or fixedRate = 5000.
Q43: What is Asynchronous Processing (`@Async`)?
Answer: Executes target methods in a background thread pool without blocking the caller thread. Enabled via @EnableAsync and @Async.
Q44: How do you upload files in Spring Boot?
Answer: Use MultipartFile parameter in @PostMapping controller methods and configure spring.servlet.multipart.max-file-size=10MB.
Q45: How do you secure sensitive configuration secrets?
Answer: Never store secrets in source code. Inject at runtime via:
  • OS Environment Variables
  • External Secret Managers (AWS Secrets Manager, Azure Key Vault, HashiCorp Vault)
  • Jasypt configuration encryption
Q46: What are Spring Boot Actuator Health Indicators?
Answer: Custom components implementing HealthIndicator that report operational health of external systems (DB, Redis, RabbitMQ) via /actuator/health.
Q47: How do you improve Spring Boot application startup time?
Answer:
  • Enable Lazy Initialization (spring.main.lazy-initialization=true).
  • Exclude unnecessary auto-configurations.
  • Optimize component scan base packages.
  • Use Spring AOT (Ahead-of-Time) & GraalVM Native Image compilation.
Q48: What are common Spring Boot performance optimizations?
Answer: Tune HikariCP connection pool, enable HTTP response compression (GZIP), use @Async for non-blocking operations, enable caching, and profile JVM memory.
Q49: How do you deploy a Spring Boot application?
Answer:
  • Fat Executable JAR: java -jar app.jar.
  • Docker Container: Multi-stage Dockerfile packaging executable JAR.
  • Kubernetes: Deployed as pods with liveness/readiness probes configured to Actuator endpoints.
  • External WAR: Extending SpringBootServletInitializer for traditional application servers.
Q50: What are Spring Boot Best Practices?
Answer: 1. Follow strict layered architecture (Controller → Service → Repository).
2. Use Constructor Injection exclusively.
3. Externalize configuration using Profiles and environment variables.
4. Centralize exception handling via @RestControllerAdvice.
5. Enforce payload validation using @Valid.
6. Write slice tests using @WebMvcTest and @DataJpaTest.
7. Monitor application health using Actuator & Micrometer.