Properties, profiles and environment values become available.
4
ApplicationContext.
Spring creates the IoC container.
5
Component scanning.
Spring discovers annotated components.
6
Auto-configuration.
Boot conditionally configures infrastructure.
7
Bean creation.
Spring creates and configures managed objects.
8
Dependency injection.
Dependencies are supplied to beans.
9
Embedded server.
Web applications start their configured embedded server.
10
Ready.
Application completes startup and can accept traffic.
Interview answer: “Spring Boot starts through SpringApplication.run(), creates the ApplicationContext, loads configuration, performs component scanning and auto-configuration, creates and wires beans, starts the embedded server and completes the startup lifecycle.”
3. How Does Spring Boot Auto-Configuration Work?
@SpringBootApplication
|
+-- @Configuration
+-- @ComponentScan
+-- @EnableAutoConfiguration
|
v
Auto-Configuration Candidates
|
v
Conditional Checks
/ Conditions true Conditions false
| |
v v
Configure beans Skip config
|
v
Existing application beans can make
auto-configuration back off
Concept
Explanation
@EnableAutoConfiguration
Enables Spring Boot automatic configuration.
Classpath
Dependencies influence which auto-configurations are candidates.
Conditions
Boot evaluates class, bean, property and other conditions.
Existing beans
Auto-configuration commonly backs off when an appropriate application bean exists.
Interview answer: “Spring Boot auto-configuration examines the classpath, properties and application context, then conditionally configures infrastructure while backing off when the application provides its own matching configuration.”
4. Spring Boot Runners
Runner
Purpose
Typical Use
CommandLineRunner
Runs startup code after context initialization and receives String... arguments.
Similar startup callback with structured ApplicationArguments.
Startup logic requiring parsed arguments.
@Component
public class StartupRunner implements CommandLineRunner {
@Override
public void run(String... args) {
System.out.println("Application started");
}
}
Ordering: Multiple runners can be ordered using @Order or Ordered.
Interview answer: “I use runners for startup tasks that should execute after Spring initialization, such as validation, reference-data loading or cache warming.”
5. How to Create Singleton Beans
Spring beans created using @Component, @Service, @Repository or @Bean are singleton-scoped by default.
@Service
public class PaymentService {
}
@Bean
@Scope("singleton")
public PaymentService paymentService() {
return new PaymentService();
}
Scope
Behavior
singleton
One bean instance per ApplicationContext.
prototype
New instance when the container is asked for the bean.
request
One instance per HTTP request in a web-aware context.
session
One instance per HTTP session in a web-aware context.
application
One instance per ServletContext.
Interview trap: A Spring singleton is not necessarily one object for the entire JVM; it is one instance per Spring ApplicationContext.
Interview answer: “I normally create singleton beans using @Service, @Component or @Bean because singleton is the default Spring scope.”
6. Mutable State in Spring Boot
@Service
public class CounterService {
private int count = 0;
public void increment() {
count++;
}
}
External session store when horizontal scaling requires it.
Business state
Durable persistence such as a database.
@Service
public class CounterService {
private final AtomicInteger counter = new AtomicInteger();
public int increment() {
return counter.incrementAndGet();
}
}
Important:AtomicInteger handles concurrency within one JVM; it does not by itself solve distributed consistency across multiple instances.
Interview answer: “Because singleton beans are shared by concurrent requests, I avoid mutable instance fields for request or business state and use thread-safe or external state management when shared mutable state is actually required.”
7. Exception Handling in Spring Boot
Approach
Use
try/catch
Local recovery or exception translation.
@ExceptionHandler
Handles specific exceptions in a controller/advice.
@ControllerAdvice
Centralizes MVC exception handling.
@RestControllerAdvice
Centralizes REST exception handling.
Custom exceptions
Represent business/domain failures clearly.
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(OrderNotFoundException.class)
public ResponseEntity<ErrorResponse> handleOrderNotFound(
OrderNotFoundException ex) {
ErrorResponse error =
new ErrorResponse("ORDER_NOT_FOUND", ex.getMessage());
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body(error);
}
}
Practice
Reason
Do not expose stack traces
Security and clean API contracts.
Consistent error schema
Easier client handling.
Correct HTTP status
Communicates failure semantics.
Structured logging
Supports troubleshooting.
Correlation/trace ID
Helps trace distributed requests.
Interview answer: “For REST APIs, I prefer centralized exception handling using @RestControllerAdvice with specific handlers, consistent error contracts, appropriate HTTP status codes, structured logging and correlation IDs.”
8. Spring Boot Actuator
Actuator provides production-oriented monitoring and management capabilities.
Endpoint
Purpose
/actuator/health
Application health information.
/actuator/info
Application information exposed through configuration.
/actuator/metrics
Application and JVM metrics.
/actuator/loggers
View/change logging levels when appropriately secured.
/actuator/env
Environment/property information; sensitive data requires protection.
/actuator/configprops
Bound configuration properties; sensitive data requires protection.
/actuator/beans
Spring beans in the context.
/actuator/mappings
Request mappings.
/actuator/threaddump
Thread dump information.
/actuator/heapdump
Heap dump; tightly secure in production.
/actuator/caches
Cache information.
/actuator/conditions
Condition evaluation useful for auto-configuration diagnosis.
/actuator/startup
Startup information when startup tracking is enabled.
/actuator/prometheus
Prometheus-compatible metrics when integration is configured.
Production security: Expose only required endpoints and protect operational endpoints with appropriate authentication, authorization and network controls.
Interview answer: “Actuator exposes operational endpoints for health, metrics and diagnostics; in production I expose only required endpoints and secure them.”
9. Role of Spring Cloud Config
Spring Cloud Config provides centralized external configuration management for distributed applications.
┌─────────────────────┐
│ Configuration Repo │
│ Git / Source │
└──────────┬──────────┘
↓
┌─────────────────────┐
│ Config Server │
└──────┬──────┬───────┘
↓ ↓
Order Service Payment Service
↓
Inventory Service
Benefit
Explanation
Centralization
Manage distributed configuration centrally.
Environment separation
Separate DEV/UAT/PROD settings.
Versioning
Git-backed configuration can be version controlled.
Consistency
Common settings can be managed consistently.
Externalization
Environment settings do not need to be packaged into artifacts.
Refresh
Some configuration can be refreshed depending on the setup and property.
Security: Avoid plain-text production secrets in Git; use Vault, cloud secret managers or platform secret mechanisms.
Interview answer: “Spring Cloud Config centralizes external configuration for distributed services, while production secrets should be handled by a dedicated secret-management solution.”
10. How Do You Manage Configuration in Production?
Profiles, external config service or deployment configuration.
Deployment values
Environment variables/platform configuration.
Passwords/API keys
Dedicated secret manager.
Kubernetes values
ConfigMap / Secret as appropriate.
Cloud secrets
Cloud-managed secret manager.
Feature flags
Feature-flag platform or suitable config service.
Sensitive values
Never hard-code in source code.
Interview answer: “I separate configuration from code, externalize environment-specific settings, manage secrets through a dedicated secret store and inject values at deployment or runtime.”
11. Ways to Load Properties in Spring Boot
Approach
Example
Best Use
application.properties
server.port=8080
Standard configuration.
application.yml
Hierarchical YAML.
Structured configuration.
@Value
@Value("${app.name}")
Small number of values.
Environment
environment.getProperty("app.name")
Programmatic lookup.
@ConfigurationProperties
Typed property class.
Grouped configuration.
@PropertySource
@PropertySource("classpath:custom.properties")
Additional property source.
Profile files
application-dev.yml
Environment-specific config.
Environment variables
APP_NAME=OrderService
Runtime configuration.
Command-line arguments
--server.port=9090
Startup overrides.
Spring Cloud Config
Central config server.
Distributed configuration.
spring.config.import
External config import.
Modern external configuration.
Senior note: Spring Boot aggregates multiple property sources into the Spring Environment; precedence determines which value wins when the same property exists in multiple sources.
@Component
public class AppConfig {
@Value("${app.name}")
private String applicationName;
@Value("${app.timeout}")
private int timeout;
@Value("${app.enabled}")
private boolean enabled;
}
Interview answer: “I use @Value for a small number of simple property values and prefer @ConfigurationProperties for structured application configuration.”
13. Environment – Programmatic Property Lookup
@Component
public class ConfigReader {
private final Environment environment;
public ConfigReader(Environment environment) {
this.environment = environment;
}
public String getAppName() {
return environment.getProperty("app.name");
}
}
Interview statement: “Environment is useful when I need programmatic property lookup rather than direct field injection.”
@ConfigurationProperties(prefix = "app")
public class AppProperties {
private String name;
private int timeout;
private Retry retry;
// getters and setters
}
@Configuration
@EnableConfigurationProperties(AppProperties.class)
public class AppConfig {
}
Alternatively:
@ConfigurationPropertiesScan
@SpringBootApplication
public class Application {
}
@Value
@ConfigurationProperties
Individual values.
Groups related values.
Convenient for small configuration.
Strongly typed binding.
Less structured.
Hierarchical configuration.
Can become scattered.
Centralized configuration model.
Interview answer: “For production applications with multiple related settings, I prefer @ConfigurationProperties because it provides strongly typed, grouped and maintainable configuration binding.”
@Configuration
@PropertySource("classpath:custom.properties")
public class PaymentConfig {
}
@Value("${payment.timeout}")
private int timeout;
Interview point:@PropertySource is useful for additional property sources; for normal Spring Boot configuration, standard Boot configuration mechanisms are generally preferred.
16. @Qualifier – Best Example
public interface PaymentService {
void pay(double amount);
}
@Service("creditCardPayment")
public class CreditCardPaymentService implements PaymentService {
public void pay(double amount) {
System.out.println("Credit Card Payment");
}
}
@Service("upiPayment")
public class UpiPaymentService implements PaymentService {
public void pay(double amount) {
System.out.println("UPI Payment");
}
}
@Service
public class OrderService {
private final PaymentService paymentService;
public OrderService(
@Qualifier("upiPayment")
PaymentService paymentService) {
this.paymentService = paymentService;
}
}
Interview answer: “@Qualifier explicitly selects the required bean when multiple candidates of the same type exist.”
17. @Qualifier vs @Primary
Feature
@Qualifier
@Primary
Purpose
Selects a specific bean.
Defines the default candidate.
Explicit choice
Yes.
No.
Best for
Different choices at different injection points.
One implementation should normally be selected.
Example
Use UPI at a particular injection point.
Make Card the default.
@Primary
@Service
public class CreditCardPaymentService implements PaymentService {
}
Interview answer: “I use @Primary when one implementation should be the default and @Qualifier when an injection point needs a specific implementation.”
18. @Qualifier + Strategy Pattern – Real-World Example
public interface PaymentProcessor {
PaymentResponse process(PaymentRequest request);
}
@Component("cardProcessor")
public class CardPaymentProcessor implements PaymentProcessor { }
@Component("upiProcessor")
public class UpiPaymentProcessor implements PaymentProcessor { }
@Component("paypalProcessor")
public class PaypalPaymentProcessor implements PaymentProcessor { }
@Service
public class PaymentService {
private final PaymentProcessor processor;
public PaymentService(
@Qualifier("upiProcessor")
PaymentProcessor processor) {
this.processor = processor;
}
}
Principle / Pattern
Application
SRP
Each processor handles one payment mechanism.
OCP
New payment methods can be added without changing existing processors.
DIP
Service depends on the PaymentProcessor abstraction.
Strategy
Payment algorithms are interchangeable.
DI
Spring injects the implementation.
@Qualifier
Selects the exact implementation.
Senior interview point: “This combines Strategy Pattern, Dependency Injection, OCP and @Qualifier to keep payment implementations loosely coupled and extensible.”
19. What Is a Bounded Context?
Bounded Context is a Domain-Driven Design concept representing an explicit boundary within which a domain model and terminology have a consistent meaning.
Interview answer: “A bounded context is a DDD boundary within which a domain model and terminology have a consistent meaning; in microservices, I often align service boundaries with bounded contexts to reduce coupling and preserve domain ownership.”
Important: Do not say every bounded context must be exactly one microservice; a bounded context is a domain-model boundary while a microservice is an architectural/deployment unit.
20. Spring Boot Interview – Most Important Questions
Question
Strong One-Line Answer
What is Spring Boot?
It simplifies Spring development through auto-configuration, starters, embedded servers and production-oriented features.
What does @SpringBootApplication do?
It combines configuration, component scanning and auto-configuration.
How does Spring Boot start?
SpringApplication.run() bootstraps the context, loads configuration, scans components, applies auto-configuration, creates beans and starts the server.
What is IoC?
Spring controls object creation and lifecycle instead of application code doing it directly.
What is DI?
Dependencies are supplied to components instead of components constructing them.
Constructor vs field injection?
Constructor injection is generally preferred because dependencies are explicit, supports immutability and improves testability.
What is auto-configuration?
Boot conditionally configures infrastructure based on classpath, properties and existing beans.
What is a Spring singleton?
One bean instance per ApplicationContext by default.
What is @Qualifier?
It selects a specific bean when multiple candidates of the same type exist.
@Qualifier vs @Primary?
@Qualifier is explicit; @Primary defines the default candidate.
What are runners?
Startup callbacks used for initialization work after context initialization.
What is @ConfigurationProperties?
It binds grouped external configuration into a strongly typed object.
How do you handle exceptions?
Use centralized REST exception handling with @RestControllerAdvice and specific handlers.
What is Actuator?
Production-oriented endpoints for health, metrics and operational diagnostics.
What is Spring Cloud Config?
A centralized external configuration solution for distributed applications.
What is a bounded context?
A DDD boundary where a domain model and terminology have a consistent meaning.
How do you manage production configuration?
Externalize non-sensitive configuration and use dedicated secret management for secrets.
How do you handle mutable state?
Avoid mutable state in shared singleton beans unless it is deliberately synchronized or externally managed.
21. Strong Senior-Level Closing Answer
“I start with a clear bounded context and keep the service focused on one business capability. At the code level, I apply SOLID principles, use constructor-based dependency injection and appropriate patterns such as Strategy, Factory and Adapter. Spring Boot starts through SpringApplication.run(), creates the ApplicationContext, performs component scanning and conditional auto-configuration, and wires the required beans. I keep configuration externalized using Spring Boot mechanisms and, where appropriate, Spring Cloud Config, while storing secrets in a dedicated secret-management solution. I avoid mutable state in singleton beans because the same instance can serve concurrent requests. For REST APIs, I use centralized exception handling with @RestControllerAdvice, validation, consistent error responses and appropriate HTTP status codes. For production operations, I use Actuator for health and metrics and integrate logging, metrics and distributed tracing. When multiple implementations of an interface exist, I use @Qualifier for explicit selection or @Primary when one implementation should be the default.”
Architecture Story to Remember
DDD → Bounded Context → Microservice Boundary → SOLID → Design Patterns → Spring IoC / DI → Auto-Configuration → Externalized Configuration → Exception Handling → Resilience → Actuator / Observability → Production Deployment
Senior interview mindset: Don't answer only with definitions. Explain what it is, why you use it, where you use it and give a realistic production example.