Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Spring & Spring Boot — Top 50 Interview Questions & Answers (With Simple Code)

 

✅ 1️⃣ Core Spring Framework — Interview Questions


1️⃣ What is Spring Framework?

Spring is a lightweight Java framework used to build loosely coupled, testable, and maintainable applications using IoC, DI, and AOP.


2️⃣ What is Inversion of Control (IoC)?

IoC means Spring Framework controls object creation, not the developer.

Without IoC:

Service s = new Service();

With IoC:
Spring creates and injects it automatically.


3️⃣ What is Dependency Injection (DI)?

DI provides required dependencies from outside instead of creating internally.

Example:

@Service public class OrderService { private final PaymentService paymentService; public OrderService(PaymentService paymentService) { this.paymentService = paymentService; } }

4️⃣ What is a Spring Bean?

A bean is an object managed by Spring Container.


5️⃣ Bean Scopes?

  • singleton (default)

  • prototype

  • request

  • session

Example:

@Component @Scope("prototype") class TestBean {}

6️⃣ What is @Component, @Service, @Repository, @Controller?

They are stereotype annotations:

  • @Component – generic bean

  • @Service – business logic

  • @Repository – database + exception translation

  • @Controller – MVC controller


7️⃣ What is @Autowired?

Used to inject dependencies automatically.


8️⃣ Difference between @Bean and @Component?

  • @Component → class level auto scanning

  • @Bean → method level manual bean creation


9️⃣ What is AOP in Spring?

Aspect Oriented Programming — handles cross-cutting concerns like logging, security.


🔟 What is @Transactional?

Handles transactions automatically.

@Transactional public void transfer() {}

1️⃣1️⃣ What is Spring MVC?

Framework for building web apps using MVC architecture.


1️⃣2️⃣ What is DispatcherServlet?

Front Controller in Spring MVC.


1️⃣3️⃣ What is ViewResolver?

Maps view names to actual pages.


1️⃣4️⃣ What are Profiles?

Used to define environments (dev/test/prod)


1️⃣5️⃣ What is Bean Lifecycle?

Bean creation → Dependency Injection → Initialization → Destruction


1️⃣6️⃣ What is @Lazy?

Delays bean creation until first use.

@Lazy @Component class Demo{}

1️⃣7️⃣ What is @Primary?

Used when multiple beans exist for same type.


1️⃣8️⃣ What is @Qualifier?

Used to choose specific bean.

@Autowired @Qualifier("emailService") Service service;

1️⃣9️⃣ What is ApplicationContext?

It is Spring’s IoC container.


2️⃣0️⃣ What is BeanFactory?

Basic container (ApplicationContext is advanced BeanFactory)



🚀 2️⃣ Spring Boot — Interview Questions


2️⃣1️⃣ What is Spring Boot?

Spring Boot simplifies Spring by providing:
✔ Auto Configuration
✔ Embedded Server
✔ Starter dependencies


2️⃣2️⃣ Difference — Spring vs Spring Boot?

SpringSpring Boot
Manual configAuto Config
Needs serverHas embedded Tomcat
Many dependenciesStarters simplify

2️⃣3️⃣ What is @SpringBootApplication?

Combination of:

  • @Configuration

  • @EnableAutoConfiguration

  • @ComponentScan


2️⃣4️⃣ How to create REST API?

@RestController @RequestMapping("/api") public class HelloController { @GetMapping("/hello") public String hello() { return "Hello Spring Boot"; } }

2️⃣5️⃣ What are Starters?

Ready dependency packs like:

  • spring-boot-starter-web

  • spring-boot-starter-data-jpa

  • spring-boot-starter-test


2️⃣6️⃣ application.properties vs application.yml?

Both used for configuration.


2️⃣7️⃣ What is Spring Boot Actuator?

Provides health & monitoring endpoints.

management.endpoints.web.exposure.include=*

2️⃣8️⃣ What is Auto Configuration?

Spring Boot configures beans automatically based on dependencies.


2️⃣9️⃣ How to Change Server Port?

server.port=8081

3️⃣0️⃣ What is @RestController vs @Controller?

ControllerRestController
returns viewreturns JSON
uses @ResponseBody manuallybuilt-in


🗄 3️⃣ Spring Boot + Database / JPA


3️⃣1️⃣ How to configure DB?

spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=root spring.datasource.password=root

3️⃣2️⃣ What is JPA Repository?

public interface UserRepo extends JpaRepository<User, Long> {}

3️⃣3️⃣ Entity Example

@Entity class User { @Id @GeneratedValue Long id; String name; }

3️⃣4️⃣ What is Hibernate?

ORM Framework used by JPA.


3️⃣5️⃣ What is @Entity?

Marks class as database table.


3️⃣6️⃣ What is @Id & @GeneratedValue?

Primary key + auto increment.


3️⃣7️⃣ Difference between save() and saveAll()?

save() — single record
saveAll() — multiple records



🔐 4️⃣ Spring Security


3️⃣8️⃣ What is Spring Security?

Framework for authentication + authorization.


3️⃣9️⃣ How to secure endpoint?

http.authorizeRequests() .anyRequest().authenticated() .and() .httpBasic();

4️⃣0️⃣ What is OAuth2?

Authorization framework.



🧪 5️⃣ Spring Boot Testing


4️⃣1️⃣ How to Unit Test?

@SpringBootTest class TestApp {}

4️⃣2️⃣ MockMVC Example

@Autowired MockMvc mockMvc;

4️⃣3️⃣ Test REST API

mockMvc.perform(get("/api/hello")) .andExpect(status().isOk());


⚙ 6️⃣ Advanced Spring Questions


4️⃣4️⃣ What is Microservices?

Small independent services communicating via REST.


4️⃣5️⃣ What is REST?

Representational State Transfer — Web API standard.


4️⃣6️⃣ What is Feign Client?

Used for calling other microservices.


4️⃣7️⃣ What is Eureka?

Service registry.


4️⃣8️⃣ What is Circuit Breaker?

Prevents failures in distributed systems.


4️⃣9️⃣ What is @Value?

Reads values from properties.

@Value("${app.name}") String name;

5️⃣0️⃣ Difference between Monolithic & Microservice?

MonolithicMicroservices
Single appMultiple small services
Hard to scaleEasy to scale
Single failure kills appIndependent failure handling

Distributed Tracing in Spring Boot using OpenTelemetry + Jaeger (2025 Guide)

 

Distributed Tracing in Spring Boot using OpenTelemetry + Jaeger (2025 Guide)

This guide helps you understand:

✅ What is distributed tracing
✅ How to enable OpenTelemetry in Spring Boot
✅ How Jaeger receives spans
✅ What is the difference between OTEL vs Prometheus
✅ Complete ready-to-run example with Docker Compose
✅ Architecture diagrams
✅ README for your project


1. What is Distributed Tracing?

Modern microservices often involve multiple services communicating with each other:

Client → API Gateway → Auth Service → Order Service → Inventory Service

Debugging such systems with only logs is extremely difficult.

Distributed Tracing solves this by:

✔ Tracking a request end-to-end
✔ Showing how long each service took
✔ Identifying bottlenecks
✔ Detecting where a failure occurs

OpenTelemetry (OTEL) is the standard for collecting such traces.


2. What is OpenTelemetry (OTEL)?

OpenTelemetry is an open-source CNCF standard for:

  • Traces

  • Metrics

  • Logs

In your Spring Boot app, OTEL:

  1. Creates spans

  2. Stores them briefly in memory

  3. Exports them through OTLP protocol

  4. Sends to a backend like Jaeger, Tempo, Zipkin, etc.

✔ OTEL uses a push model

This means:

Your application sends data OUT to Jaeger, like this:

Spring Boot (OTEL SDK) ↓ (push) Jaeger Collector

3. What is Jaeger?

Jaeger is an open-source distributed tracing system.

In local mode (all-in-one):

  • Collector

  • Query

  • UI

  • Storage

are all in one container.

Jaeger stores data:

  • In memory (in local mode)

  • Elastic / Cassandra / ClickHouse / etc. (in production)


4. Architecture Diagram (Spring Boot → OTEL → Jaeger)

Client | v Spring Boot App | | creates spans v OTel SDK | | batches spans (memory buffer) v OTLP Exporter | | pushes spans v Jaeger Collector (4317/4318) | v Jaeger Storage (Memory) | v Jaeger UI (16686)

5. How Does OTEL Export Data? (Important)

👉 OTEL does not store long-term data
👉 OTEL only batches spans in memory for milliseconds
👉 OTEL pushes spans to Jaeger via OTLP

There is no polling.

✔ Jaeger never calls your app
✔ Your app always pushes the data


6. What is Prometheus?

Prometheus is used for:

  • Metrics (CPU, memory, request_count, latency, etc.)

  • Alerting

  • Time-series storage

Prometheus follows a pull model:

Prometheus scrapes /actuator/prometheus endpoint

✔ Prometheus calls your Spring Boot endpoint

✔ Your app does NOT push data

✔ Prometheus stores metrics on disk


7. OTEL vs Prometheus (VERY IMPORTANT)

FeatureOpenTelemetryPrometheus
PurposeTracing (request flow)Metrics (performance)
Data TypeSpans, traces, logsTime-series metrics
Collection ModelPush (App → Jaeger)Pull (Prometheus → App)
How It WorksOTEL sends trace data instantlyPrometheus periodically scrapes
What It ShowsEnd-to-end request timingCPU, memory, errors, latency
StorageJaeger (memory/DB)Prometheus TSDB
UIJaeger UIGrafana
Ideal UseMicroservice debuggingMonitoring & alerting

✔ Both used together in production

You use:

OTEL + Jaeger for tracing
Prometheus + Grafana for metrics


8. Spring Boot Example (Tracing /hello endpoint)

Your controller:

@GetMapping("/hello") public String hello() { Span span = tracer.spanBuilder("custom-span").startSpan(); span.addEvent("processing-hello"); try { Thread.sleep(50); } catch(Exception ignored) {} span.end(); return "Hello with tracing!"; }

Every request generates a trace visible in Jaeger.


9. Docker Compose — Spring Boot + Jaeger

version: "3.8" services: spring-app: build: . image: springboot-tracing-demo:latest container_name: springboot-tracing environment: - OTEL_SERVICE_NAME=springboot-tracing-demo - OTEL_EXPORTER_OTLP_ENDPOINT=http://jaeger:4318 - OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf - OTEL_TRACES_EXPORTER=otlp ports: - "8080:8080" depends_on: - jaeger jaeger: image: jaegertracing/all-in-one:1.57 container_name: jaeger ports: - "16686:16686" - "4317:4317" - "4318:4318"

10. Source code

https://github.com/kkvinodkumaran/springboot-tracing-demo-complete

Circuit Breaker in Spring Boot — Complete Guide With Real Example (2025 Edition)

 

Circuit Breaker in Spring Boot — Complete Guide With Real Example (2025 Edition)

Modern microservices constantly depend on other services — internal API calls, third-party services, databases, payment gateways, or internal microservice-to-microservice communication.

But what happens when one of those services becomes slow or unstable?

  • Your threads get stuck

  • Your service slows down

  • Requests start timing out

  • Your system collapses (cascading failure)

To prevent this, we use the Circuit Breaker Pattern.


1. What Is a Circuit Breaker?

A Circuit Breaker prevents your application from continuously calling a failing service.

It works like an electrical breaker:

  • Closed → ON → working normally

  • Open → OFF → stop calling the service

  • Half-Open → testing the service


2. Why Do We Use a Circuit Breaker?

ProblemWhat Circuit Breaker Does
Slow external APIStops further calls; returns fallback
Service downPrevents thread blocking
Too many failuresOpens circuit quickly
Cascading failuresProtects upstream services
Improves reliabilityFail fast instead of waiting

3. Circuit Breaker Lifecycle (Simple Diagram)

┌──────────────┐ │ CLOSED │ ← everything normal └───────┬──────┘ │ failures exceed threshold ▼ ┌──────────────┐ │ OPEN │ ← stop calling service └───────┬──────┘ │ wait duration expires ▼ ┌──────────────┐ │ HALF-OPEN │ ← send limited test calls └───────┬──────┘ │ success ▼ ┌──────────────┐ │ CLOSED │ ← service recovered └──────────────┘

4. What Happens When Multiple Failures Occur?

Consider this configuration:

failure-rate-threshold: 50 sliding-window-size: 10 minimum-number-of-calls: 5 wait-duration-in-open-state: 5s

✔ Step-by-Step Example

You call an endpoint 5 times:

Call 1 → FAIL Call 2 → FAIL Call 3 → FAIL Call 4 → FAIL Call 5 → FAIL

Now:

Total calls = 5 Failures = 5 Failure rate = 100% (greater than threshold 50%)

✔ Circuit Breaker immediately switches to OPEN.


5. What Happens in OPEN State?

NO calls are sent to the real endpoint.
⭐ Every call is immediately failed by the circuit breaker.
⭐ The fallback method is executed instantly.

This is called FAIL-FAST.

So yes:

“If 5 failures happen, the circuit will stop hitting that endpoint for a few seconds/minutes until it recovers.”


6. HALF-OPEN State (Testing Recovery)

After the wait-duration passes (5 seconds):

  • Circuit moves to HALF-OPEN

  • Allows limited number of test calls
    (permitted-number-of-calls-in-half-open-state)

If test calls succeed → circuit goes back to CLOSED
If test calls fail → circuit goes back to OPEN


7. CLOSED State (Recovered)

Once enough successful calls occur, the service is considered healthy again.

Circuit becomes CLOSED, and traffic flows normally.


8. Implementing Circuit Breaker in Spring Boot (Using Resilience4j)

Resilience4j is the most modern and recommended fault-tolerance library for Spring Boot (replacing Netflix Hystrix).


✔ Step 1: Add Dependencies (pom.xml)

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency> <dependency> <groupId>io.github.resilience4j</groupId> <artifactId>resilience4j-spring-boot3</artifactId> </dependency>

✔ Step 2: Add Configuration (application.yml)

resilience4j: circuitbreaker: instances: externalServiceCB: failure-rate-threshold: 50 sliding-window-size: 10 minimum-number-of-calls: 5 wait-duration-in-open-state: 5s permitted-number-of-calls-in-half-open-state: 3

✔ Step 3: Create a Service That Calls an External API

@Service public class ExternalApiService { private final RestTemplate restTemplate = new RestTemplate(); @CircuitBreaker(name = "externalServiceCB", fallbackMethod = "fallback") public String callExternalService() { // Simulating a failing service String url = "https://example.com/api/data"; return restTemplate.getForObject(url, String.class); } public String fallback(Exception ex) { return "Fallback: External service unavailable"; } }

✔ Step 4: Add Controller

@RestController public class DemoController { @Autowired private ExternalApiService apiService; @GetMapping("/get-data") public String getData() { return apiService.callExternalService(); } }

9. Testing the Circuit Breaker

Case A — External API is down

✔ First 5 attempts → failures
✔ Circuit goes OPEN
✔ All next requests return immediately:

Fallback: External service unavailable

Case B — After 5 seconds

✔ Circuit enters HALF-OPEN
✔ Allows 3 test calls
✔ If successful → closes
✔ If fails → stays open


10. Real Use Cases of Circuit Breaker

✔ Microservices communication

E.g., Order Service → Payment Service

✔ 3rd party systems

SMS gateways, Stripe, PayPal, email APIs.

✔ Database outage

Fail fast instead of waiting for JDBC timeout.

✔ Cloud-native systems

Network hiccups are common.

✔ High-traffic applications

Avoid saturating threads and CPU.


11. Final Summary (Interview-Ready)

  • Circuit Breaker protects your app from calling failing services.

  • After repeated failures, the circuit opens.

  • In OPEN state, service calls are blocked immediately.

  • Fallback method handles the failure gracefully.

  • After wait time, HALF-OPEN state tests service health.

  • If OK → CLOSE; if fail → OPEN again.

  • Prevents cascading failures and improves reliability.

Spring WebFlux vs Spring MVC — The Complete Beginner-Friendly Guide

 

Spring WebFlux vs Spring MVC — The Complete Beginner-Friendly Guide

(Event Loop, Reactive Programming, Thread Model, Real Use Case Explained)

Modern backend services frequently need to handle:

  • High concurrency

  • Millions of API calls

  • Slow external dependencies (DB, APIs)

  • Real-time streaming

  • Efficient CPU & memory usage

Traditional Spring MVC works perfectly for small, synchronous web apps.
But when you scale to thousands of simultaneous requests, it starts struggling.

This is why Spring WebFlux exists.

This blog will explain WebFlux in a way even freshers can easily understand.


1. What Is Spring WebFlux?

Spring WebFlux is a non-blocking, asynchronous, reactive web framework in the Spring ecosystem.

It is built on:

  • Project Reactor (Mono, Flux)

  • Reactive Streams specification

  • Netty event loop model (default)

In simple words:

WebFlux = High-performance async API system that uses very few threads.


2. What Is Spring MVC?

Spring MVC is Spring’s traditional, blocking, thread-per-request model.

Uses:

  • Tomcat

  • Jetty

  • Undertow (classic servlet containers)

In simple words:

Spring MVC = One thread handles one request and blocks until completion.


3. Why Blocking Is a Problem?

In MVC:

Thread receives request → Calls DB → waits (blocking) → Calls API → waits → Writes logs → waits → Finally sends response

During each wait, the thread is doing nothing but is still occupied.

If you have 1000 requests → you need ~1000 threads

Expensive and not scalable.


4. How WebFlux Works (Non-Blocking)

WebFlux doesn’t block threads.

When an operation may take time:

  • DB call

  • API call

  • Logging

  • Metrics

  • File IO

Rather than waiting, WebFlux does:

Start async call → Register callback → Free the thread → Continue other work → Resume when result arrives

This is the Event Loop model.


5. The Event Loop Explained (VERY IMPORTANT)

Think of the event-loop like a restaurant waiter:

🍽 Spring MVC (Blocking)

  • 1 waiter serves 1 table

  • Waiter must stand and wait while the food is cooking

  • If there are 50 tables → need 50 waiters

🍽 WebFlux (Non-Blocking Event Loop)

  • 1 waiter can serve 100 tables

  • If food is cooking, waiter moves to the next table

  • Calls come back when food is ready

  • Very few waiters needed

That is what the event loop does.


6. Text Diagram: Event Loop Model in WebFlux

┌──────────────────────────┐ │ Event Loop Thread (1) │ └───────────┬──────────────┘ │ Request A → Authenticate → DB Call (async) → Thread released │ Request B → Auth → Metadata API (async) → Thread released │ Event loop picks next ready callback → Process → Continue

One thread can handle hundreds of concurrent requests because it never waits.


7. Spring MVC vs WebFlux — Visual Comparison

🟥 Spring MVC (Thread Per Request)

Request 1 ── Thread-1 (waiting during IO) Request 2 ── Thread-2 (waiting during IO) Request 3 ── Thread-3 (waiting during IO) ... Request 1000 ─ Thread-1000 (waiting during IO)

Threads get exhausted → slow system → timeouts.


🟦 Spring WebFlux (Event Loop)

EventLoop-1 handles: - Request 1Async DB - Request 2Async API - Request 3Async DB EventLoop-2 handles: - Request 4Async API - Request 5Async DB

Only 10–20 threads required even for thousands of requests.


8. Real Use Case — Product Details API

Your API workflow:

  1. Receive request

  2. Authenticate

  3. Authorize

  4. Query product DB

  5. Query metadata service

  6. Log request

  7. Send metrics

  8. Return response

Let’s compare how MVC and WebFlux handle the flow.


9. Request Flow in Spring MVC (Blocking Model)

Step-by-step:

1. DispatcherServlet assigns Thread-25 2. Auth (fast) 3. Authorization (fast) 4. DB call → thread waits 80ms 5. Metadata API → thread waits 100ms 6. Logging → thread waits 20ms 7. Metrics → thread waits 10ms 8. Send response 9. Thread released

Total wait time: 210ms

Thread was BLOCKED for most of that time.

Imagine 5000 users → need ~5000 threads → impossible.


10. Request Flow in WebFlux (Non-Blocking)

Step-by-step:

1. EventLoop-1 receives request 2. Auth (non-block) 3. Authorization (non-block) 4. DB call → async → thread freed immediately 5. Metadata API call → async → thread freed 6. Logging → async 7. Metrics → async 8. EventLoop-1 resumes when both async results are ready 9. Send response

Thread blockage time: 0ms

The thread is never waiting.


11. Diagram — MVC vs WebFlux for Product API

🟥 SPRING MVC (Blocking)

Request ----┐ ├─ Thread-1 (blocked 210ms) Request ----┘ Total threads required ≈ number of active requests

🟦 SPRING WEBFLUX (Non-Blocking)

EventLoop Thread-1: Request → Auth → DB async → FREE EventLoop Thread-2: Request → Meta async → FREE Callback triggers: EventLoop Thread-1 resumes → Build response → Send

Total threads required ≈ 20–30 (even for 5000 requests)


12. Why WebFlux Is Faster Under Load

✔ Uses async IO

✔ Uses Netty event-loop

✔ No thread sits idle

✔ Threads only used for CPU work, not IO wait

✔ Ideal for microservices calling other microservices


13. When Timeouts Happen in WebFlux

WebFlux doesn’t magically prevent timeouts.

Timeout happens when:

  • DB takes too long

  • Downstream API is slow

  • You configure a timeout

  • Client disconnects

The difference:

MVC → thread blocked until timeout

WebFlux → thread is free, timeout happens via callback


14. When to Use WebFlux

✔ Very high concurrency
✔ Calling many external APIs
✔ Lots of IO-bound operations
✔ Real-time streaming (SSE/WebSockets)
✔ Microservices in distributed systems
✔ Reactive databases (R2DBC, Mongo Reactive)


15. When Not to Use WebFlux

❌ If you use JPA/Hibernate (blocking)
❌ If your use case is low traffic
❌ If team is not comfortable with reactive programming
❌ If CPU-heavy work (pure computation)


16. Final Summary

🔹 Spring MVC

  • Blocking

  • One thread per request

  • Threads wait → not scalable

  • Good for synchronous CRUD apps

🔹 Spring WebFlux

  • Non-blocking

  • Event loop model

  • Handles thousands of requests with few threads

  • Perfect for IO-heavy, high-concurrency systems

  • Ideal for microservices & real-time workloads


One-Line Explanation

WebFlux makes your service handle 10× to 50× more requests by not wasting threads during IO.

Spring Boot + Prometheus + Grafana — Complete Local Monitoring Guide (2025)

Spring Boot (vkspringboot) + Prometheus + Grafana — Complete Local Monitoring Guide (2025)

A full end-to-end local observability setup using Spring Boot, Prometheus, Grafana, and Docker Compose.

This guide works on:

✅ Windows
✅ macOS
✅ Linux
✅ IntelliJ / VS Code


Step 0 — Create Spring Boot Project (Name: vkspringboot)

In IntelliJ / Spring Initializr:

  1. Open IntelliJ → New Project

  2. Select Spring Initializr

  3. Fill project details:

FieldValue
Groupcom.example
Artifactvkspringboot
Namevkspringboot
Java Version17 or 21
PackagingJar
  1. Select dependencies:
    Spring Web
    Spring Boot Actuator
    Micrometer Prometheus Registry

Click Create.
This generates your project:

vkspringboot/ ├── pom.xml ├── src/main/java/com/example/vkspringboot/ └── src/main/resources/

Step 1 — Add Dependencies to pom.xml

Ensure your pom.xml contains:

<dependency> <groupId>io.micrometer</groupId> <artifactId>micrometer-registry-prometheus</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>

Step 2 — Enable Prometheus Metrics Endpoint

Create or edit:

src/main/resources/application.properties

management.endpoints.web.exposure.include=prometheus,health,info management.endpoint.prometheus.enabled=true

Metrics will appear at:

👉 http://localhost:8080/actuator/prometheus


Step 3 — Create a Simple REST Controller

src/main/java/com/example/vkspringboot/HelloController.java

package com.example.vkspringboot; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @GetMapping("/hello") public String hello() { return "Hello!"; } }

Test it:

👉 http://localhost:8080/hello


Step 4 — Create Dockerfile (Updated for vkspringboot)

Your Maven build produces:

target/vkspringboot-0.0.1-SNAPSHOT.jar

So your Dockerfile must match it:

# Use official Java runtime FROM eclipse-temurin:17-jdk # Set working directory WORKDIR /app # Copy the JAR file COPY target/vkspringboot-0.0.1-SNAPSHOT.jar app.jar # Expose Spring Boot default port EXPOSE 8080 # Start the Spring Boot application ENTRYPOINT ["java", "-jar", "/app/app.jar"]

✅ Correct JAR name
✅ Java 17 (matches project)


Step 5 — Docker Compose (App + Prometheus + Grafana)

Create docker-compose.yml in project root:

version: "3.9" services: app: build: . container_name: vkspringboot ports: - "8080:8080" prometheus: image: prom/prometheus container_name: prometheus volumes: - ./prometheus.yml:/etc/prometheus/prometheus.yml ports: - "9090:9090" grafana: image: grafana/grafana container_name: grafana ports: - "3000:3000"

Step 6 — Prometheus Config File

Create prometheus.yml in project root:

global: scrape_interval: 5s scrape_configs: - job_name: 'vkspringboot' metrics_path: '/actuator/prometheus' static_configs: - targets: ['app:8080']

✅ Prometheus scrapes Spring Boot every 5 seconds
✅ Uses service name app from Docker Compose


Step 7 — Build the Project + Run the Stack

1️⃣ Build the JAR

mvn clean package -DskipTests

2️⃣ Start everything

docker compose up --build

Step 8 — Access All Tools Locally

ComponentURL
✅ Spring Boot Apphttp://localhost:8080/hello
✅ Spring Metricshttp://localhost:8080/actuator/prometheus
✅ Prometheushttp://localhost:9090
✅ Grafanahttp://localhost:3000 (login: admin / admin)

Step 9 — Connect Grafana to Prometheus

In Grafana:

  1. Go to Configuration → Data Sources

  2. Add Prometheus

  3. URL:

http://prometheus:9090
  1. Click Save & Test

✅ Grafana is now connected.


Step 10 — Import Spring Boot Dashboards

Grafana → Dashboard → Import → Enter ID:

11378 — Spring Boot Micrometer Dashboard
4701 — JVM + Spring Boot Metrics

You will now see:

✅ API Request Count
✅ Response Time
✅ JVM Memory
✅ CPU Usage
✅ GC Metrics
✅ Thread pools
✅ Uptime


✅ ✅ Final Summary 

1. Create Spring Boot project named "vkspringboot" 2. Add Micrometer + Actuator dependencies 3. Expose /actuator/prometheus 4. Create Dockerfile using vkspringboot-0.0.1-SNAPSHOT.jar 5. Use docker-compose to run Spring Boot + Prometheus + Grafana 6. Add Prometheus as a Grafana data source 7. Import pre-built dashboards

You now have a complete local observability platform for Spring Boot.


Confusion Matrix + Precision/Recall (Super Simple, With Examples)

  Confusion Matrix + Precision/Recall (Super Simple, With Examples) 1) Binary Classification Setup Binary classification means the model p...

Featured Posts