Spring Boot Interview Guide

Senior Java • Spring Boot • Microservices

Annotations, application lifecycle, auto-configuration, runners, singleton beans, mutable state, exception handling, Actuator, configuration, Bounded Context and @Qualifier.

1. Spring Boot Annotations

AnnotationPurpose – Single StatementExample / UseInterview Area
@SpringBootApplicationCombines @Configuration, @EnableAutoConfiguration and @ComponentScan.Application entry point.Startup
@ConfigurationDefines a source of Spring bean definitions.Java configuration class.Configuration
@BeanRegisters an object as a Spring-managed bean.Third-party objects such as ObjectMapper.Configuration
@ComponentMarks a generic class for component scanning.Utility or infrastructure component.DI
@ServiceSpecialized component for business/service logic.OrderService.Service layer
@RepositoryMarks a persistence component and participates in exception translation.DAO/repository.Persistence
@ControllerDefines an MVC controller, commonly for views.Web MVC controller.MVC
@RestControllerCombines controller semantics with response-body behavior for REST APIs.REST endpoint class.REST
@AutowiredInjects a Spring-managed dependency; constructor injection is generally preferred.Constructor dependency injection.DI
@QualifierSelects a specific bean when multiple candidates have the same type.@Qualifier("upiPayment").Multiple beans
@PrimaryMakes one matching bean the default candidate.Default payment implementation.DI resolution
@ValueInjects an individual configuration value.@Value("${app.timeout}").Configuration
@ConfigurationPropertiesBinds grouped external configuration into a strongly typed object.@ConfigurationProperties(prefix="app").Production config
@ProfileActivates configuration/beans for selected environments.@Profile("prod").Profiles
@ConditionalOnPropertyApplies configuration when a property condition is satisfied.Feature toggle.Conditional config
@ConditionalOnMissingBeanCreates auto-configuration only when a matching bean is absent.Common in Boot auto-config.Auto-config
@ConditionalOnClassApplies configuration when specified classes are available.Common in Boot auto-config.Auto-config
@EnableSchedulingEnables scheduled task processing.Use with @Scheduled.Jobs
@ScheduledRuns a method according to a schedule.Cron/fixed delay tasks.Jobs
@EnableAsyncEnables asynchronous method execution.Use with @Async.Async
@AsyncExecutes a method asynchronously through Spring's executor.Async notification.Async
@TransactionalDefines a Spring transaction boundary.Service database operation.Transactions
@CacheableCaches a method result.Cache product lookup.Caching
@GetMappingMaps HTTP GET requests.@GetMapping("/{id}").REST
@PostMappingMaps HTTP POST requests.Create resource.REST
@PutMappingMaps HTTP PUT requests.Update resource.REST
@DeleteMappingMaps HTTP DELETE requests.Delete resource.REST
@PathVariableBinds a URI path variable to a method parameter./orders/{id}.REST
@RequestParamBinds a query parameter to a method parameter.?status=PAID.REST
@RequestBodyConverts request-body data into a Java object.JSON → DTO.REST
@ExceptionHandlerHandles a specified exception in a controller/advice.Business exception handler.Errors
@RestControllerAdviceCentralizes REST exception handling across controllers.Global error handler.Errors
@ValidTriggers Bean Validation for an object.@Valid @RequestBody.Validation
@PostConstructRuns initialization logic after dependency injection.Initialization method.Lifecycle

2. How Does a Spring Boot Application Work?

main() → SpringApplication.run() → Environment → ApplicationContext → Component Scan → Auto-Configuration → Bean Creation → Dependency Injection → Embedded Server → Application Ready
StepWhat HappensInterview Explanation
1JVM executes main().Application starts from the Java main method.
2SpringApplication.run().Bootstraps the Spring Boot application.
3Environment preparation.Properties, profiles and environment values become available.
4ApplicationContext.Spring creates the IoC container.
5Component scanning.Spring discovers annotated components.
6Auto-configuration.Boot conditionally configures infrastructure.
7Bean creation.Spring creates and configures managed objects.
8Dependency injection.Dependencies are supplied to beans.
9Embedded server.Web applications start their configured embedded server.
10Ready.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
ConceptExplanation
@EnableAutoConfigurationEnables Spring Boot automatic configuration.
ClasspathDependencies influence which auto-configurations are candidates.
ConditionsBoot evaluates class, bean, property and other conditions.
Existing beansAuto-configuration commonly backs off when an appropriate application bean exists.
PropertiesConfiguration properties customize auto-configured behavior.
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

RunnerPurposeTypical Use
CommandLineRunnerRuns startup code after context initialization and receives String... arguments.Startup validation, reference data, cache warming.
ApplicationRunnerSimilar 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();
}
ScopeBehavior
singletonOne bean instance per ApplicationContext.
prototypeNew instance when the container is asked for the bean.
requestOne instance per HTTP request in a web-aware context.
sessionOne instance per HTTP session in a web-aware context.
applicationOne 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++;
    }
}
Request 1 ─┐
Request 2 ─┼──→ Same singleton bean instance
Request 3 ─┘
RequirementRecommended Approach
Request stateLocal variables or request-scoped state.
Shared counter in one JVMThread-safe structures such as AtomicInteger.
Distributed stateRedis/database as appropriate.
User/session stateExternal session store when horizontal scaling requires it.
Business stateDurable 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

ApproachUse
try/catchLocal recovery or exception translation.
@ExceptionHandlerHandles specific exceptions in a controller/advice.
@ControllerAdviceCentralizes MVC exception handling.
@RestControllerAdviceCentralizes REST exception handling.
Custom exceptionsRepresent 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);
    }
}
PracticeReason
Do not expose stack tracesSecurity and clean API contracts.
Consistent error schemaEasier client handling.
Correct HTTP statusCommunicates failure semantics.
Structured loggingSupports troubleshooting.
Correlation/trace IDHelps 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.

EndpointPurpose
/actuator/healthApplication health information.
/actuator/infoApplication information exposed through configuration.
/actuator/metricsApplication and JVM metrics.
/actuator/loggersView/change logging levels when appropriately secured.
/actuator/envEnvironment/property information; sensitive data requires protection.
/actuator/configpropsBound configuration properties; sensitive data requires protection.
/actuator/beansSpring beans in the context.
/actuator/mappingsRequest mappings.
/actuator/threaddumpThread dump information.
/actuator/heapdumpHeap dump; tightly secure in production.
/actuator/cachesCache information.
/actuator/conditionsCondition evaluation useful for auto-configuration diagnosis.
/actuator/startupStartup information when startup tracking is enabled.
/actuator/prometheusPrometheus-compatible metrics when integration is configured.
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
management.endpoints.web.exposure.include=health,info,metrics,prometheus
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
BenefitExplanation
CentralizationManage distributed configuration centrally.
Environment separationSeparate DEV/UAT/PROD settings.
VersioningGit-backed configuration can be version controlled.
ConsistencyCommon settings can be managed consistently.
ExternalizationEnvironment settings do not need to be packaged into artifacts.
RefreshSome 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?

Application → External Configuration → Secret Management → Runtime Injection
Configuration TypeRecommended Approach
Application defaultsapplication.yml or application.properties.
Environment-specific settingsProfiles, external config service or deployment configuration.
Deployment valuesEnvironment variables/platform configuration.
Passwords/API keysDedicated secret manager.
Kubernetes valuesConfigMap / Secret as appropriate.
Cloud secretsCloud-managed secret manager.
Feature flagsFeature-flag platform or suitable config service.
Sensitive valuesNever 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

ApproachExampleBest Use
application.propertiesserver.port=8080Standard configuration.
application.ymlHierarchical YAML.Structured configuration.
@Value@Value("${app.name}")Small number of values.
Environmentenvironment.getProperty("app.name")Programmatic lookup.
@ConfigurationPropertiesTyped property class.Grouped configuration.
@PropertySource@PropertySource("classpath:custom.properties")Additional property source.
Profile filesapplication-dev.ymlEnvironment-specific config.
Environment variablesAPP_NAME=OrderServiceRuntime configuration.
Command-line arguments--server.port=9090Startup overrides.
Spring Cloud ConfigCentral config server.Distributed configuration.
spring.config.importExternal 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.

12. @Value — Example

app.name=OrderService
app.timeout=3000
app.enabled=true
@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.”

14. @ConfigurationProperties – Production Example

app:
  name: OrderService
  timeout: 3000
  retry:
    attempts: 3
    backoff: 500
@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.”

15. @PropertySource

# custom.properties
payment.timeout=5000
payment.provider=stripe
@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
PurposeSelects a specific bean.Defines the default candidate.
Explicit choiceYes.No.
Best forDifferent choices at different injection points.One implementation should normally be selected.
ExampleUse 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

                    PaymentProcessor
                           |
          ┌────────────────┼────────────────┐
          ↓                ↓                ↓
       Card              UPI             PayPal
     processor          processor        processor
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 / PatternApplication
SRPEach processor handles one payment mechanism.
OCPNew payment methods can be added without changing existing processors.
DIPService depends on the PaymentProcessor abstraction.
StrategyPayment algorithms are interchangeable.
DISpring injects the implementation.
@QualifierSelects 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.

E-Commerce Domain
|
+-- Customer Context
|     +-- Customer
|     +-- Address
|
+-- Order Context
|     +-- Order
|     +-- OrderLine
|
+-- Payment Context
|     +-- Payment
|     +-- Transaction
|
+-- Inventory Context
      +-- Stock
      +-- Warehouse
ContextMeaning of “Customer”
Customer ContextIdentity, profile and contact information.
Order ContextBuyer associated with an order.
Payment ContextPayer/payment-account information.
Marketing ContextCustomer segment and campaign membership.
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

QuestionStrong 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.