Spring Boot and Microservices Interview Questions for Java
25 Spring Boot and Microservices questions with answers for java roles — 5 easy, 10 medium, 10 hard.
About Spring Boot and Microservices
Spring Boot is the standard framework for Java backends in India. Learn dependency injection, auto-configuration, REST controllers, validation, profiles and configuration, transactions, Spring Security with JWT, testing with JUnit and Mockito, Actuator, and microservice patterns such as circuit breakers, Kafka events, sagas, Docker and Kubernetes deployment.
Sheet progressStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
✓ 3 questions free • Unlock the rest in seconds
01
What is Spring Boot and how is it different from the Spring Framework?
Spring Framework provides dependency injection, MVC, transactions and data access but needs manual configuration. Spring Boot builds on it with auto-configuration, starter dependencies, an embedded server such as Tomcat and production features through Actuator, so you can run a service with java -jar. Spring Boot 3 requires Java 17 or later and uses Jakarta EE packages instead of javax.
02
What is dependency injection and why is constructor injection preferred?
Dependency injection means the container creates objects and supplies their dependencies, instead of classes creating them, which reduces coupling and helps testing. Constructor injection is preferred because dependencies can be final, objects are never half-built, required dependencies are obvious and unit tests can pass mocks without Spring. Field injection with @Autowired hides dependencies and is harder to test.
03
What is the difference between @Component, @Service, @Repository and @Controller?
All four mark a class as a Spring bean for component scanning. @Service and @Component are functionally the same, with @Service showing business logic intent. @Repository also enables translation of persistence exceptions into Spring DataAccessException. @Controller handles web requests and returns views, and @RestController adds @ResponseBody so return values are written as JSON.
04
Write a simple REST controller in Spring Boot for creating and fetching products.
Situation: in my current role I build Spring Boot services for a payments product. Task: show impact beyond writing code. Action: I improved API latency by 60 percent through query tuning and caching, raised test coverage from 40 to 80 percent and handled on-call calmly. Result: I bring solid Java, Spring and SQL skills, ownership of production and a habit of measuring results, which fits this role.
At startup Spring Boot reads auto-configuration classes listed in META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports. Each class uses conditions like @ConditionalOnClass, @ConditionalOnMissingBean and @ConditionalOnProperty, so it creates beans only when the library is on the classpath and you have not defined your own. Run with --debug to see the condition report showing what was applied and why.
singleton is the default: one instance per application context. prototype creates a new instance each time it is requested. Web scopes include request, session and application. Singletons must be stateless or thread safe because all requests share them. Injecting a prototype into a singleton gives only one instance, so use ObjectProvider or a scoped proxy to get fresh ones.
Actuator adds production endpoints such as /actuator/health for liveness and readiness probes, /actuator/metrics and /actuator/prometheus for Micrometer metrics, plus info, loggers and thread dumps. Expose only what you need with management.endpoints.web.exposure.include and secure sensitive endpoints with Spring Security. Kubernetes uses the health groups to decide restarts and traffic routing.
09
A @Transactional method is not rolling back after an exception. What could be wrong?
Check that the exception is unchecked, since checked exceptions do not roll back unless rollbackFor is set. Check that the method is called through the Spring proxy, not from another method in the same class. Make sure the method is public and the exception is not caught and swallowed inside. Also confirm the database engine supports transactions and the right transaction manager is used.
10
You must expose configuration that differs between dev, QA and production. How do you manage it?
Use Spring profiles with application-dev.yml and application-prod.yml, and bind settings to typed @ConfigurationProperties classes with validation. Keep secrets out of the repo by injecting them through environment variables, Kubernetes Secrets or a vault. Activate the profile with SPRING_PROFILES_ACTIVE in each environment. Use the same build artefact everywhere and change only configuration.
11
Clients report duplicate orders when they retry after a timeout. How do you prevent it?
Make the create order API idempotent. The client sends an Idempotency-Key header; the server stores the key with the result in a table with a unique constraint or in Redis. A retry with the same key returns the saved response instead of creating a new order. Database unique constraints on business keys add another safety net.
12
Write a unit test for a service class using JUnit 5 and Mockito.
Mock the repository and verify behaviour.
@ExtendWith(MockitoExtension.class)
class ProductServiceTest {
@Mock ProductRepository repo;
@InjectMocks ProductService service;
@Test
void throwsWhenMissing() {
when(repo.findById(1L)).thenReturn(Optional.empty());
assertThrows(NotFoundException.class, () -> service.get(1L));
verify(repo).findById(1L);
}
}
No Spring context starts, so the test runs in milliseconds.
13
Bind typed configuration properties with validation in Spring Boot.
Use a record with @ConfigurationProperties.
@ConfigurationProperties(prefix = "payment")
@Validated
public record PaymentProps(
@NotBlank String baseUrl,
@Min(100) int timeoutMs) {}
// application.yml
// payment:
// base-url: https://pay.internal
// timeout-ms: 2000
Enable it with @ConfigurationPropertiesScan on the main class. The app fails at startup if values are invalid.
14
Write a minimal Dockerfile for a Spring Boot application.
A multi-stage build keeps the image small.
FROM eclipse-temurin:21-jdk AS build
WORKDIR /app
COPY . .
RUN ./mvnw -q package -DskipTests
FROM eclipse-temurin:21-jre
WORKDIR /app
COPY --from=build /app/target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "app.jar"]
Spring Boot can also build images without a Dockerfile using mvn spring-boot:build-image.
Situation: three freshers joined my Spring Boot team at once. Task: make them productive quickly. Action: I created a starter task list, paired with each on their first story, gave detailed but kind code reviews and held a weekly session on topics like transactions and testing. Result: all three shipped features independently within a month and one now mentors new joiners.
16
How does @Transactional work and what are its common pitfalls?
@Transactional is applied through a proxy that opens a transaction before the method and commits or rolls back after. Pitfalls: calling a transactional method from the same class bypasses the proxy, so no transaction starts; by default rollback happens only for unchecked exceptions; it works on public methods; and long transactions with remote calls hold connections. Use propagation and readOnly where suitable.
17
What are the key patterns used in microservices built with Spring Boot?
Common patterns are API gateway (Spring Cloud Gateway) for routing and auth, service discovery or Kubernetes services, externalised config, circuit breaker and retry with Resilience4j, database per service, event-driven communication with Kafka, saga for distributed transactions, and observability with Micrometer, tracing and centralised logs. Each service owns its data and deploys independently.
18
How does JWT based authentication work in a Spring Boot API?
After login, the auth server issues a signed JWT with claims like user id, roles and expiry. The client sends it in the Authorization: Bearer header. The API, configured as an OAuth2 resource server in Spring Security, verifies the signature with the public key, checks expiry and builds the security context, so no session is needed. Keep tokens short-lived and use refresh tokens for renewal.
19
A downstream payment service is slow and your API threads pile up. How do you protect your service?
Set strict connect and read timeouts on the HTTP client. Add a Resilience4j circuit breaker so calls fail fast once the error rate crosses a threshold, a bulkhead to limit concurrent calls and retry with backoff only for safe idempotent requests. Return a clear fallback such as payment pending. Monitor breaker state through Actuator metrics and alerts.
20
How would you split a monolith into microservices?
Do not split everything at once. Identify bounded contexts with the business, such as orders, payments and catalogue, and pick a module with clear boundaries and high change rate first. Use the strangler fig pattern: route its traffic through a gateway to the new service, give it its own database and sync data through events. Add observability and CI/CD before scaling out further.
21
An order must update inventory and payment in different services. How do you keep data consistent?
Distributed two-phase commit is fragile, so use the saga pattern. Each service performs a local transaction and publishes an event; failures trigger compensating actions, such as releasing stock when payment fails. Use the transactional outbox pattern so the database change and event publish never diverge, and make consumers idempotent because Kafka may deliver a message more than once.
22
Your Spring Boot service takes 40 seconds to start in Kubernetes and pods get killed. How do you fix it?
First set a startupProbe so Kubernetes waits for startup before liveness checks begin. Then reduce start time: remove unused starters, enable lazy initialisation where safe, avoid heavy work in @PostConstruct, give enough CPU at start and consider AppCDS. For very fast startup, a GraalVM native image built with Spring AOT can start in under a second, with some trade-offs.
23
Configure a Resilience4j circuit breaker on a client call in Spring Boot.
Spring Kafka hides most boilerplate.
@Service
class OrderEvents {
private final KafkaTemplate<String, OrderPlaced> kafka;
OrderEvents(KafkaTemplate<String, OrderPlaced> k) { kafka = k; }
void publish(OrderPlaced e) { kafka.send("orders", e.orderId(), e); }
}
@Component
class OrderListener {
@KafkaListener(topics = "orders", groupId = "inventory")
void on(OrderPlaced e) { inventory.reserve(e); }
}
Using orderId as key keeps events for one order in the same partition and order.
25
Tell me about a microservice you designed end to end.
Situation: our monolith's notification code slowed every release. Task: extract it into its own service. Action: I designed a Spring Boot service consuming Kafka events, with its own database for templates and delivery logs, retries with backoff, idempotent consumers and Actuator metrics in Grafana. Result: it handles 20 lakh messages a day, deploys independently and notification incidents dropped sharply.
Frequently asked questions
How important is Spring Boot and Microservices in Java interviews?
Spring Boot is the standard framework for Java backends in India. Learn dependency injection, auto-configuration, REST controllers, validation, profiles and configuration, transactions, Spring Security with JWT, testing with JUnit and Mockito, Actuator, and microservice patterns such as circuit breakers, Kafka events, sagas, Docker and Kubernetes deployment.
How should I use the Spring Boot and Microservices sheet?
Go top to bottom — easy to hard. Answer before opening each answer, tick what you solved and save misses to Last-Minute Revision.