Spring Framework
Spring is a powerful open-source framework for building Java applications. It simplifies Java enterprise development by handling lots of heavy lifting (like managing objects, database connections, transactions, etc.).
Key Goals:
Bean
In Spring, a Bean is just a normal Java object (POJO) that is managed by Spring.Bean = an object registered in the Spring container.
Ways to define a Bean:
ApplicationContext
The ApplicationContext is the Spring Container that:
1.3.1 There are different types of ApplicationContext
Core Concepts of Spring
1.4.1 Dependency Injection (DI):
1.4.2 Aspect-Oriented Programming (AOP):
Aspect: A module that encapsulates cross-cutting logic.
Advice: The action taken at a join point (@Before, @After, etc.).
Join Point: A point during execution (e.g., method call).
Pointcut: A predicate that matches join points.
1.4.3 Spring Container:
1.4.4 Important Modules in Spring
Spring is not just one thing; it's a collection of modules.
How Spring Works (Internally)?
Containers like BeanFactory and ApplicationContext manage all this.
Advantages of Spring
Ways to Configure Spring
SpringBoot
Spring Boot is a framework designed to simplify the development of Java applications, particularly those built with the Spring Framework.
It provides:
Core Spring Boot Annotations
| Annotation | Description |
|---|---|
| @SpringBootApplication | Combines @Configuration, @EnableAutoConfiguration, and @ComponentScan |
| @EnableAutoConfiguration | Enables Spring Boot’s auto-configuration mechanism |
| @ComponentScan | Scans the package for Spring components (@Component, @Service, etc.) |
| @Configuration | Marks a class as a source of bean definitions |
| @Bean | Declares a bean manually inside a @Configuration class |
How does Spring Boot auto-configuration work?
Component Stereotypes
| Annotation | Description |
|---|---|
| @Component | Generic Spring-managed component |
| @Service | Marks a class as a service layer component |
| @Repository | Marks a class as a DAO/repository component |
| @Controller | Marks a class as a web controller |
| @RestController | Combines @Controller + @ResponseBody |
Dependency Injection
| Annotation | Description |
|---|---|
| @Autowired | Injects a dependency by type |
| @Qualifier | Used with @Autowired to resolve ambiguity |
| @Value | Injects values from application properties |
@Qualifier Common Scenarios for @Qualifier
| Scenario | Why Use @Qualifier? |
|---|---|
| Multiple @Service or @Component of same interface | To inject a specific one |
| Multiple @Bean definitions | To differentiate them |
| Multiple implementations of repository or strategy pattern | For flexibility and testing |
| When integrating third-party APIs | Inject appropriate handler |
@Qualifier is used to resolve ambiguity when multiple beans of the same type are present.
Web & REST Annotations
| Annotation | Description |
|---|---|
| @RequestMapping | Maps HTTP requests to handler methods/classes |
| @GetMapping | Shortcut for @RequestMapping(method = GET) |
| @PostMapping | Shortcut for @RequestMapping(method = POST) |
| @PutMapping | Shortcut for @RequestMapping(method = PUT) |
| @DeleteMapping | Shortcut for @RequestMapping(method = DELETE) |
| @PathVariable | Binds URL path variables to method parameters |
| @RequestParam | Binds request parameters (query strings) |
| @RequestBody | Binds request body to a method parameter |
| @ResponseBody | Returns object data as response body (JSON, etc.) |
| @CrossOrigin | Enables CORS for controller/method |
Persistence (Spring Data JPA)
| Annotation | Description |
|---|---|
| @Entity | Marks a class as a JPA entity |
| @Table | Maps the entity to a database table |
| @Id | Marks the primary key |
| @GeneratedValue | Specifies auto-generation strategy for ID |
| @Column | Maps a field to a table column |
| @Repository | Marks the interface as a Spring Data repository |
| @Query | Custom JPQL/native SQL query |
Validation (JSR-303)
| Annotation | Description |
|---|---|
| @Valid | Triggers validation on method arguments |
| @NotNull | Field must not be null |
| @NotBlank | Field must not be null or empty (String) |
| @Min, @Max | Specifies numeric constraints |
| @Size | Specifies size limits for collections or strings |
Spring AOP
| Annotation | Description |
|---|---|
| @Aspect | Declares a class as an AOP aspect |
| @Before | Runs before the matched method execution |
| @After | Runs after the method execution |
| @AfterReturning | Runs after a method returns successfully |
| @AfterThrowing | Runs if method throws an exception |
| @Around | Surrounds method execution (pre & post) |
Test Annotations (Spring Boot Test)
| Annotation | Description |
|---|---|
| @SpringBootTest | Loads full Spring Boot context for integration tests |
| @WebMvcTest | Loads only web layer (controllers) |
| @DataJpaTest | Loads JPA components only (repository layer) |
| @MockBean | Adds mock of a bean to Spring context |
| @TestConfiguration | Custom configuration class for tests |
Spring Boot Runners
| Runner | Interface | Purpose | Method to Implement | Parameter Type | Use Case |
|---|---|---|---|---|---|
| CommandLineRunner | org.springframework.boot. CommandLineRunner | Run code after Spring Boot application starts | run(String... args) | Raw command-line arguments | Simple use cases, quick startup scripts |
| ApplicationRunner | org.springframework.boot. ApplicationRunner | Run code after app starts (with structured access to args) | run( ApplicationArguments args) | Parsed args with option access | More control over startup args and options |
Spring Boot provides two main interfaces to run logic after the application context is initialized.
You can have multiple runners, and you can order them with @Order(1) or implement Ordered.
SpringBoot Application invocation:
SpringBoot application invokes from the main() method and main() method is responsible to invoke the run() method
Run() method performs the activities like
| Step | Component/Code | Description |
|---|---|---|
| 1 | public static void main(String[] args) | Entry point of the Spring Boot application (Java main method) |
| 2 | SpringApplication.run() | Boots up the Spring application context and starts the embedded server |
| 3 | @SpringBootApplication | Convenience annotation for @Configuration + @EnableAutoConfiguration + @ComponentScan |
| 4 | Auto-configuration (@EnableAutoConfiguration) | Spring Boot automatically configures beans based on classpath and properties |
| 5 | Component Scan (@ComponentScan) | Detects and registers @Component, @Service, @Repository, @Controller |
| 6 | Application Context is initialized | All beans are instantiated, dependencies injected |
| 7 | CommandLineRunner / ApplicationRunner | Executes logic right after application context is loaded |
| 8 | Embedded Server Starts (e.g., Tomcat) | Starts embedded servlet container and listens on the configured port |
Different approaches of designing class having dependency
Dependency lookup: It is an approach where we can get the resource after demand
Depedency Injection: IOC/DI describes the situation where one object uses a second object to provide a particular capacity.
Instead of you asking for dependencies, Spring pushes them into your classes. This is the "Inversion of Control" (IoC) concept
Constructor Injection when object must be created with all it’s dependencies.
Setter Injection: Use Setter Injection when the number of dependencies is large or when some of them are optional.
In field injection, Spring injects dependencies directly into class variables (fields), typically marked with @Autowired
How to create a singleton beans in SpringBoot
Creating singleton beans in Spring Boot is quite straightforward because Spring beans are singleton by default. This means that when you define a bean in a Spring Boot application, Spring will create only one instance of that bean and reuse it wherever it's injected.
how to create Mutable state in Springboot
In Spring Boot, mutable state refers to data that can be changed during the application's runtime—like in-memory counters, caches, or user sessions
Spring Boot automatically manages the session via cookies (usually JSESSIONID).
As long as the session is active, the state is maintained for that user.
When the session expires or the browser is closed, the state is lost.
Handle Exception in SpringBoot
In Spring Boot, you handle exceptions centrally using the @ControllerAdvice annotation along with @ExceptionHandler. This allows you to define global exception handling logic, keeping your controllers clean and consistent.
Different actuator in SpringBoot
Spring Boot Actuator provides production-ready features to help monitor and manage your application. It exposes various endpoints to get internal insights like health, metrics, environment properties, etc.
| Actuator Endpoint | URL Path | Description |
|---|---|---|
| health | /actuator/health | Shows application health status (UP/DOWN) |
| info | /actuator/info | Displays arbitrary application info (from application.properties) |
| metrics | /actuator/metrics | Shows metrics like JVM memory, CPU usage, etc. |
| env | /actuator/env | Displays all environment properties |
| beans | /actuator/beans | Lists all Spring beans in the application context |
| mappings | /actuator/mappings | Shows all @RequestMapping paths |
| loggers | /actuator/loggers | View and modify logger levels at runtime |
| threaddump | /actuator/threaddump | Shows a thread dump from the JVM |
| httptrace | /actuator/httptrace | Displays recent HTTP request/response trace (requires enabling explicitly) |
| auditevents | /actuator/auditevents | Displays audit events (e.g., login success/failures) |
| shutdown | /actuator/shutdown | Gracefully shuts down the application (must be enabled explicitly) |
| caches | /actuator/caches | Shows available caches and statistics |
| scheduledtasks | /actuator/scheduledtasks | Shows scheduled tasks in the application |
| startup | /actuator/startup | Displays startup steps and timing (Spring Boot 3.x+) |
Configuration Tips
| Property | Purpose |
|---|---|
| management.endpoints.web.exposure.include=* | Enables all actuator endpoints |
| management.endpoint.shutdown.enabled=true | Enables the shutdown endpoint |
| management.endpoint.health.show-details=always | Shows detailed health info |
Metrics in Spring Boot (Micrometer)
| Metric Category | Examples (Metric Names) | Description |
|---|---|---|
| JVM Metrics | jvm.memory.used, jvm.threads.live | Monitors heap, non-heap memory, GC, threads |
| System Metrics | system.cpu.usage, system.load.average.1m | Tracks CPU and system load |
| Process Metrics | process.uptime, process.cpu.usage | Uptime, CPU time used by the JVM |
| HTTP Metrics | http.server.requests | Tracks HTTP request count, status, response times |
| Datasource Metrics | hikaricp.connections, jdbc.connections.active | Monitors database connection pools |
| Cache Metrics | cache.gets, cache.puts, cache.evictions | Tracks cache usage and hit/miss stats |
| Logback Metrics | logback.events | Tracks log events (info, error, warn) |
| Custom Metrics | Custom via @Timed, MeterRegistry.counter() | Developers can define custom metrics |
Enabling Prometheus Exporter
| Step | Configuration |
|---|---|
| Add dependency | spring-boot-starter-actuator + micrometer-registry-prometheus |
| Enable endpoint in application.properties | management.endpoints.web.exposure.include=prometheus |
| Access metrics at | http://localhost:8080/actuator/prometheus |
Key Config Properties
| Property | Description |
|---|---|
| management.metrics.enable.* | Enable/disable specific metric categories |
| management.endpoint.metrics.enabled=true | Enable the /actuator/metrics endpoint |
| management.metrics.distribution.percentiles | Configure custom percentiles for timers |
Spring Boot Core Starters
| Starter | Usage | Category |
|---|---|---|
| spring-boot-starter | Core starter, includes auto-configuration, logging, and YAML support. | Core |
| spring-boot-starter-web | Builds web, RESTful applications using Spring MVC. Uses Tomcat as default embedded container. | Web |
| spring-boot-starter-data-jpa | Simplifies JPA-based database access. Used with Hibernate as the default JPA provider. | Data Access |
| spring-boot-starter-security | Adds Spring Security for authentication and authorization. | Security |
| spring-boot-starter-test | Adds testing libraries like JUnit, Hamcrest, Mockito, and Spring Test. | Testing |
| spring-boot-starter-thymeleaf | Integrates Thymeleaf template engine for server-side rendering of HTML. | Template Engines |
| spring-boot-starter-actuator | Adds production-ready features like health checks, metrics, and monitoring. | Monitoring |
| spring-boot-starter-validation | Supports Java Bean Validation (JSR-380) with Hibernate Validator. | Validation |
| spring-boot-starter-data-mongodb | Simplifies MongoDB access with Spring Data MongoDB. | Data Access |
| spring-boot-starter-batch | Supports Spring Batch for batch processing and ETL applications. | Batch Processing |
| spring-boot-starter-amqp | Enables AMQP messaging with RabbitMQ. | Messaging |
| spring-boot-starter-cache | Adds abstraction support for caching. | Caching |
| spring-boot-starter-mail | Provides JavaMail support for sending emails. | |
| spring-boot-starter-quartz | Integrates Quartz Scheduler for scheduling tasks. | Scheduling |
| spring-boot-starter-aop | Adds Aspect-Oriented Programming support using Spring AOP and AspectJ. | AOP |
| spring-boot-starter-data-redis | Enables Spring Data Redis for Redis key-value store support. | Data Access |
| spring-boot-starter-oauth2-client | Supports OAuth2-based Single Sign-On and client applications. | Security |
| spring-boot-starter-graphql | Supports building GraphQL APIs. | API Development |
| spring-boot-starter-websocket | Adds WebSocket support for real-time bi-directional communication. | WebSocket |
| spring-boot-starter-integration | Supports Spring Integration for building messaging-based applications. | Integration |
| spring-boot-starter-freemarker | Adds support for FreeMarker template engine. | Template Engines |
| spring-boot-starter-mustache | Adds support for Mustache template engine. | Template Engines |
| spring-cloud-starter-circuitbreaker-resilience4j | Provides Circuit Breaker support using Resilience4j library. | Cloud Resilience |
| spring-cloud-starter-gateway | Enables building API gateways with routing, load balancing, and filtering using Spring Cloud Gateway. | Cloud API Gateway |
| spring-kafka | Supports Apache Kafka integration for event-driven messaging applications. | Messaging |
| spring-boot-starter-activemq | Provides support for Java Message Service (JMS) API using ActiveMQ as the message broker. | Messaging |
| spring-boot-starter-webflux | Builds reactive web applications using Spring WebFlux with support for non-blocking APIs, Reactor, and Netty server. | Reactive Web |
Spring Boot realistic, end-to-end flow of a Microservices system
end-to-end flow of a Microservices system
High-Level Architecture
Each microservice handles its own domain, has its own database, and communicates through HTTP (REST) or sometimes Messaging (Kafka/RabbitMQ).
Components Setup
Step-by-Step Flow
(A) User Request
(B) API Gateway Routing
(C) Authentication Service
JWT = base64(header) + base64(payload) + signature
(D) Subsequent Requests with JWT
Example header:
Authorization: Bearer <your_jwt_token_here>
(E) Gateway forwards request
POST /user/create → User-Service
GET /order/history → Order-Service
(F) Microservice verifies JWT again (optional)
(G) Business Logic + PostgreSQL
User user = userRepository.findById(userId);
(H) Circuit Breaker in Action
Resilience4j example:
@CircuitBreaker(name = "orderService", fallbackMethod = "orderFallback")
public Order getOrder(String orderId) { ... }
If getOrder() fails, orderFallback() will be triggered.
Diagram (Simple View)
Real Life Example
Let's say:
Spring Boot-level transactions
(using @Transactional): Spring manages the transaction boundaries for you, calling COMMIT or ROLLBACK based on success or exception.
Global Exception Handler
Handling global exceptions in Spring Boot is super important for clean, maintainable, and user-friendly error management. The best way to handle global exceptions is through @ControllerAdvice. It provides a centralized way of handling exceptions across your whole application.
How to Handle Global Exceptions in Spring Boot
Create a Global Exception Handler with @ControllerAdvice
Explain how you designed a scalable microservices architecture in Spring Boot.
| Component | Technology / Pattern | Purpose |
|---|---|---|
| Service Layer | Spring Boot Microservices | Independent, loosely coupled services for business domains |
| API Gateway | Spring Cloud Gateway / Zuul | Single entry point, routing, security, and rate-limiting |
| Service Discovery | Eureka / Consul | Dynamic service registration and discovery |
| Load Balancer | Ribbon (legacy), Spring Cloud LoadBalancer, external (e.g. NGINX) | Distributes requests across instances |
| Configuration | Spring Cloud Config Server / Vault | Centralized and dynamic configuration management |
| Database Layer | Polyglot Persistence (MySQL, MongoDB, PostgreSQL) | Each service has its own DB (Database per service pattern) |
| Communication | REST (Feign), Messaging (RabbitMQ/Kafka) | Sync (Feign) and Async (Messaging) communication |
| Security | OAuth2 / JWT / Spring Security | Centralized authentication and authorization |
| Observability | Spring Boot Actuator, Micrometer + Prometheus + Grafana | Metrics, health checks, and custom monitoring |
| Logging | ELK (Elasticsearch, Logstash, Kibana) / EFK (Fluentd) | Centralized logging and search |
| Tracing | Sleuth + Zipkin / Jaeger | Distributed tracing |
| Containerization | Docker | Packaged and portable deployment |
| Orchestration | Kubernetes (AKS, EKS, GKE) | Automated deployment, scaling, and management |
| CI/CD | GitHub Actions / Jenkins / Azure DevOps | Automated build, test, and deployment pipelines |
Microservice Design Principles
| Design Element | Approach |
| Bounded Context | Each service aligns with a single business domain (e.g., User, Order, Payment) |
| Loose Coupling | Services interact via REST APIs or messaging queues |
| High Cohesion | Encapsulate business logic within a single service |
| Resilience | Circuit Breakers (Resilience4j), retries, timeouts |
| Scalability | Stateless services + Kubernetes HPA |
Sample Tech Stack
| Layer | Technology |
|---|---|
| API Gateway | Spring Cloud Gateway |
| Service Discovery | Netflix Eureka |
| Inter-Service Comm. | Feign, Kafka |
| Configuration | Spring Cloud Config |
| Authentication | Keycloak / OAuth2 / JWT |
| Monitoring | Prometheus + Grafana |
| Tracing | Sleuth + Zipkin |
| Logging | Logback + Elasticsearch/Kibana |
| Deployment | Docker + Kubernetes (AKS) |
Architecture Diagram
+---------------------+
| Client UI |
+---------------------+
|
▼
+---------------------+
| API Gateway |
+---------------------+
|
+------------+------------+
| | |
▼ ▼ ▼
+---------+ +----------+ +----------+
| Order | | User | | Payment | ← Spring Boot Services
+---------+ +----------+ +----------+
| | |
+---------+ +----------+ +----------+
|MySQL DB | |MongoDB | |Postgres |
+---------+ +----------+ +----------+
(All services registered in Eureka)
Scalability Features Implemented
| Feature | Details |
| Horizontal Scaling | Services are stateless and deployed as replicas in Kubernetes |
| Central Config | Spring Cloud Config Server enables dynamic reloading via Actuator |
| Health Monitoring | /actuator/health used by Kubernetes for liveness/readiness checks |
| Resilience | Retry and circuit breaker patterns via Resilience4j |
| Asynchronous Messaging | Kafka used for non-blocking inter-service communication (e.g., order events) |
| JWT Security | Auth tokens are validated at the API Gateway level |
| Autoscaling | HPA scales pods based on CPU/memory/requests per second |
Key Best Practices
How do you handle service discovery and communication between services (e.g., Eureka, Feign, REST Template)?
When handling service discovery and communication between microservices, especially in a Spring Boot microservice architecture, you typically use a combination of tools like Eureka, Feign, and RestTemplate.
Eureka is a service registry from Netflix used to register and discover services in a microservices architecture.
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
A. Feign Client (Declarative REST Client)
Use when: You want cleaner, readable code and tighter Spring Cloud integration.
@FeignClient(name = "order-service")
public interface OrderClient {
@GetMapping("/orders/{id}")
Order getOrderById(@PathVariable("id") Long id);
}
@EnableFeignClients
@SpringBootApplication
public class Application { }
RestTemplate
Use when: You want full control over the HTTP request or need to integrate with external APIs.
@Autowired
private RestTemplate restTemplate;
public Order getOrderById(Long id) {
return restTemplate.getForObject("http://order-service/orders/" + id, Order.class);
}
@Bean
@LoadBalanced // Enables service name resolution via Eureka
public RestTemplate restTemplate() {
return new RestTemplate();
}
What is the role of Spring Cloud Config? How do you manage configurations in production?
Spring Cloud Config provides centralized configuration management for distributed microservices. It allows you to externalize configuration properties from your application code and manage them in a central Git repository (or Vault, JDBC, etc.).
Why use Spring Cloud Config?
| Problem | Solution with Spring Cloud Config |
| Duplication of configs across services | Centralized config in a single place (e.g., Git) |
| Manual config updates | Dynamic refresh using @RefreshScope and actuator/refresh |
| Multiple environments (dev, qa, prod) | Profile-specific YAMLs like application-prod.yml |
| Secrets and sensitive values | Support for integration with Vault, KMS, etc. |
Summary
| Aspect | Spring Cloud Config Benefits |
| Centralized management | Yes (via Git, Vault, etc.) |
| Environment segregation | Yes (via profiles) |
| Dynamic reload | Yes (@RefreshScope, Spring Cloud Bus) |
| Secret management | Yes (Vault integration) |
| Production safe? | Yes, when using secure backends + Bus + refresh |
How do you secure microservices (OAuth2, JWT, Spring Security)?
Securing microservices is critical in distributed architectures. You typically secure them using Spring Security, OAuth2, and JWT. Here's a structured breakdown of how to secure microservices in a modern Spring Boot setup:
Authentication and Authorization in Microservices
| Security Concern | Solution |
| Identity verification | OAuth2 / OpenID Connect |
| Token-based auth | JWT (JSON Web Tokens) |
| Central auth management | Authorization Server (e.g., Keycloak, Auth0) |
| Service-to-service auth | Propagate JWT or use Mutual TLS |
Core Security Components
A. Spring Security
B. OAuth2 / OpenID Connect
C. JWT (JSON Web Token)
How it Works (Flow)
Authorization: Bearer <token>
Each microservice:
What’s your approach to versioning REST APIs?
Versioning REST APIs is critical for maintaining backward compatibility while allowing continuous evolution of your services. Here's a structured approach to REST API versioning:
| Purpose | Benefit |
|---|---|
| Avoid breaking changes | Clients using old versions keep working |
| Allow iterative improvements | New features added in new versions |
| Support multiple client versions | Mobile apps, third-party consumers |
Why API Versioning Matters
| Purpose | Benefit |
|---|---|
| Avoid breaking changes | Clients using old versions keep working |
| Allow iterative improvements | New features added in new versions |
| Support multiple client versions | Mobile apps, third-party consumers |
Best Practices for API Versioning
| Best Practice | Why It Matters |
| Use semantic versioning (v1, v2) | Clear evolution of API |
| Keep versions backward compatible | Avoid breaking existing clients |
| Deprecate old versions gradually | Communicate EOL to clients |
| Document version changes clearly | Use Swagger/OpenAPI per version |
| Use consistent versioning strategy | Across all microservices |
What’s your approach to ensuring high availability and fault tolerance?
Ensuring high availability (HA) and fault tolerance is critical for resilient, production-grade systems
Design for Failure
Redundancy & Replication
Failover Mechanisms
Stateless Services
Graceful Degradation & Circuit Breakers
Load Balancing & Auto-Scaling
Distributed Data Consistency
Data Backup & Recovery
Monitoring, Alerting & Incident Response
Chaos Engineering
Summary Table:
| Strategy | Purpose | Example Tools / Techniques |
|---|---|---|
| Redundancy & Replication | Eliminate SPOF | Kubernetes, Multi-AZ DB replicas |
| Failover | Auto switch on failure | Kubernetes probes, DNS failover |
| Stateless Design | Easy scaling & recovery | External session stores |
| Circuit Breakers | Avoid cascading failures | Resilience4j, Hystrix |
| Load Balancing & Auto-Scaling | Handle load and failures | AWS ALB, Kubernetes HPA |
| Monitoring & Alerting | Early detection & response | Prometheus, Grafana, PagerDuty |
| Chaos Engineering | Test fault tolerance | Chaos Monkey, Gremlin |
Microservices Architecture Design
| Component | Role |
|---|---|
| API Gateway | Single entry point for all client requests, routing, authentication, rate limiting, and request aggregation. |
| Service Mesh | Manages inter-service communication with features like service discovery, load balancing, retries, circuit breaking, and security. |
| Microservices | Independently deployable services implementing business capabilities, communicating over the network. |
| Observability | Monitoring, logging, tracing, and alerting across all services to gain insight and detect issues. |
How to Run Spring Boot Actuator on a Different Port
You can specify a different port for Actuator endpoints by setting the management.server.port property in your application.properties or application.yml.
server.port=8080 # Application runs on port 8080
management.server.port=8081 # Actuator runs on port 8081
management.endpoints.web.exposure.include=* # Expose all actuator endpoints
To override or customize the /health endpoint
Instead of fully overriding /health, you typically contribute custom health indicators:
@Component
public class MyCustomHealthIndicator implements HealthIndicator {
@Override
public Health health() {
}
Fully Override the /health Endpoint (Not Recommended)
Exclude the default Actuator /health
management.endpoints.web.exposure.exclude=health
@RestController
public class CustomHealthController {
@GetMapping("/health")
public ResponseEntity<Map<String, Object>> customHealth() {
Map<String, Object> status = new HashMap<>();
status.put("status", "CUSTOM_HEALTH_OK");
status.put("timestamp", Instant.now());
return ResponseEntity.ok(status);
}
}
How do you design a microservices system using Spring Boot?
What is a Bounded Context?
Bounded Context is a key concept in Domain-Driven Design (DDD). It helps you clearly define the boundaries within which a specific domain model applies — especially important in large-scale, enterprise, or microservices-based systems.
What is a Reactive Programming?
Reactive programming is an asynchronous programming paradigm that focuses on non-blocking, event-driven data processing with backpressure handling.
It’s useful when:
Spring Boot Reactive
Spring Boot uses the Spring WebFlux module to support reactive programming using:
Built on Project Reactor, a reactive library for Java.
When to Use It
@GetMapping
public Flux<Employee> getAll() {
return service.getAll();
}
@GetMapping("/{id}")
public Mono<Employee> get(@PathVariable String id) {
return service.getById(id);
}
@PostMapping
public Mono<Employee> create(@RequestBody Employee emp) {
return service.save(emp);
}
where your Spring Boot app needs to process a large file efficiently
To handle large files in Azure, we store them in Azure Blob. We split the file logically and use Service Bus to distribute chunks to Spring Boot instances. The app is containerized and deployed to AKS, and we scale it horizontally using HPA based on CPU or queue depth. This enables dynamic scaling and efficient processing.