[go: up one dir, main page]

0% found this document useful (0 votes)
57 views29 pages

Top 50 Java Spring Interview Q&A

The document lists the top 50 most challenging Spring interview questions along with concise answers. It covers various topics including transaction management, circular dependencies, Spring Boot auto-configuration, security, and microservices. Each question is followed by a brief explanation and examples where applicable.

Uploaded by

kapil verma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views29 pages

Top 50 Java Spring Interview Q&A

The document lists the top 50 most challenging Spring interview questions along with concise answers. It covers various topics including transaction management, circular dependencies, Spring Boot auto-configuration, security, and microservices. Each question is followed by a brief explanation and examples where applicable.

Uploaded by

kapil verma
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Top 50 Most

Challenging Spring

a
an
Interview
Questions m
tra
at
PART - 1
nk
ve
@

https://www.linkedin.com/in/venkattramana

1
1. What is the difference between @Transactional(propagation =
Propagation.REQUIRES_NEW) and Propagation.NESTED in Spring?

Answer:

●​ REQUIRES_NEW: Suspends the current transaction and creates a new, independent


transaction.
●​ NESTED: Runs in a nested transaction within the current one; rollback only affects the
nested block.

a
Example:

an
m
tra
at
nk
ve
@

2. How does Spring handle circular dependencies, and how can you
resolve them?

Answer:​
Spring resolves circular dependencies via singleton bean injection through setter injection,
not constructor injection.

2
Example:

a
an
m
tra
To resolve constructor-based circular dependencies: Use @Lazy, redesign, or inject via setters.
at
3. What happens if a Spring bean is @Transactional, but the method is
called from inside the same class?
nk

Answer:​
Self-invocation bypasses the proxy, so the transaction is ignored.

Fix: Move the method to a separate bean or call via ApplicationContext.getBean(...).


ve
@

3
Example:

a
an
m
4. Explain how @EventListener works in Spring. How can you handle
async events?
tra
Answer:​
@EventListener listens for published Spring events.​
Use @Async + @EnableAsync to make them asynchronous.
at

Example:
nk
ve
@

4
5. How does Spring Boot auto-configuration work internally?

Answer:​
Spring Boot uses spring.factories under the hood:

●​ It scans for @Configuration classes listed in META-INF/spring.factories.

Example:

a
an
m
tra
at
6. What are the differences between @Component, @Bean, and
@Configuration?
nk

Answer:
ve
@

5
Example:

a
an
m
7. How does @RequestScope, @SessionScope, and @ApplicationScope
differ?
tra
Answer:

●​ @RequestScope: Bean lives per HTTP request.


●​ @SessionScope: Lives per session.
at
●​ @ApplicationScope: Lives for the entire app.
nk

Example:
ve
@

8. Explain method-level security using @PreAuthorize, @PostAuthorize.


How are they evaluated?

Answer:

●​ @PreAuthorize: Checks before method executes.

6
●​ @PostAuthorize: Checks after method executes (can use return object).

Example:

a
an
9. What is Spring’s BeanPostProcessor, and where is it useful?

m
Answer:​
It allows custom logic before/after bean initialization.

Example:
tra
at
nk

Used in AOP, lifecycle hooks, and proxy enhancement.


ve

10. How can you implement dynamic multi-tenancy in Spring Boot +


@

Hibernate?

Answer:​
Use MultiTenantConnectionProvider and CurrentTenantIdentifierResolver.

7
Example:

a
an
m
tra
at
11. What is the use of @ControllerAdvice and how is it different from
@ExceptionHandler in controllers?
nk

Answer:

●​ @ControllerAdvice is a global exception handler across multiple controllers.


ve

●​ @ExceptionHandler is specific to one controller.

Example:
@

8
12. How does Spring Boot support graceful shutdown, and how do you
implement it?

Answer:​
Spring Boot supports graceful shutdown by delaying shutdown until current requests complete.

To enable:

a
an
Custom hook:

m
tra
at
nk

13. How to create a custom Spring Boot Starter?

Answer:
ve

1.​ Create a new Maven module.


2.​ Add spring.factories.
3.​ Provide default auto-config classes.
@

Example:

9
14. How does Spring Security's FilterChainProxy work under the hood?

Answer:​

a
FilterChainProxy holds multiple SecurityFilterChain objects mapped to different URL
patterns.

an
Each chain contains filters like:

●​ UsernamePasswordAuthenticationFilter

m
●​ BasicAuthenticationFilter
●​ ExceptionTranslationFilter
tra
Example:
at
nk
ve

15. What is the role of @EnableConfigurationProperties and how does


it work?
@

Answer:​
It binds external configuration (YAML/properties) to POJOs.

Example:

10
a
an
16. Explain Spring Retry mechanism and its configuration.

m
Answer:​
Spring Retry allows methods to be automatically retried on failure.

Add dependency:
tra
at
nk

Usage:
ve
@

11
17. How to implement request rate limiting in Spring Boot?

Answer:​
Use libraries like Bucket4j or Redis.

Example with Bucket4j (in-memory):

a
an
m
tra
at
18. How to configure distributed tracing in Spring Boot microservices
(Zipkin)?
nk

Answer:​
Add spring-cloud-starter-zipkin + properties.
ve

Example:
@

12
Add Dependency:

19. What is the use of @Profile and how to load beans conditionally based

a
on environment?

an
Answer:​
@Profile defines beans conditionally based on active Spring profiles.

Example:

m
tra
at
nk

Set profile using:


ve

-Dspring.profiles.active=dev
@

20. Explain the role of WebMvcConfigurer and how to customize Spring


MVC configuration.

Answer:​
WebMvcConfigurer provides hook methods for:

●​ CORS configuration
●​ Interceptors
●​ Formatters

13
●​ Resource handling

Example:

a
an
m
21. How do you secure inter-service communication in Spring Boot
microservices? tra
Answer:​
You can secure communication using:

●​ OAuth2 with JWT tokens


●​ Mutual TLS
at
●​ API Gateway Authentication

Example (OAuth2 with Feign):


nk
ve
@

Feign Client with Token Relay:

14
22. How does Spring Cloud Config work and how does it refresh properties
at runtime?

Answer:​
Spring Cloud Config Server fetches properties from Git or Vault and injects them into clients.
Use @RefreshScope + actuator to refresh values.

Example:

a
an
m
tra
Trigger refresh:

curl -X POST http://localhost:8080/actuator/refresh


at
nk

23. What is Circuit Breaker in Spring Cloud and how do you implement it
with Resilience4j?
ve

Answer:​
A circuit breaker prevents system overload by stopping repeated failed requests.

Example:
@

15
Config in application.yml:

a
24. How to implement distributed locking in Spring (e.g., for scheduled

an
tasks)?

Answer:​
Use Redis-backed locking using libraries like ShedLock.

m
Example: tra
at

Dependency:
nk
ve

25. What is the difference between @RequestBody and @ModelAttribute?


@

Answer:

Annotation Parses From Use Case

@RequestBody JSON/XML body REST API

@ModelAttrib Form data / Query Web forms (MVC)


ute Params

16
Example:

a
26. Explain how @Aspect, JoinPoint, and Pointcut work together in
Spring AOP.

an
Answer:

●​ @Aspect: Declares a class as an aspect.

m
●​ @Pointcut: Defines a matching expression.
●​ @Before, @After: Advice methods that run on matched points.

Example:
tra
at
nk
ve
@

27. How does Spring Boot DevTools work under the hood for live reload
and restarts?

Answer:​
Spring DevTools uses a separate classloader to watch non-static classes and triggers a
context restart (not full JVM restart) on file change.

Features:

17
●​ Auto-reload via RestartClassLoader
●​ LiveReload integration with browsers

28. How do you implement content negotiation in Spring Boot (XML/JSON


responses)?

Answer:​
Configure HttpMessageConverters or let Spring auto-detect based on headers.

a
Example:

an
m
Spring chooses response type based on:

●​ Accept header
tra
●​ URL extension (if enabled)
at
29. How does Spring Boot Actuator monitor application health?
nk

Answer:​
Actuator exposes /actuator/health, /metrics, /env endpoints.

Example:
ve
@

18
Custom health indicator:

a
30. What is the difference between @ConditionalOnProperty and

an
@ConditionalOnMissingBean?

Answer:

m
Annotation tra Use Case

@ConditionalOnProper Load bean based on property


ty value

@ConditionalOnMissin Load only if bean not defined


gBean
at

Example:
nk
ve
@

31. What is the difference between Mono and Flux in Spring WebFlux?

Answer:

Return Type Meaning Use Case

19
Mono<T> 0 or 1 element REST responses

Flux<T> 0 to N Streaming
elements data/events

Example:

a
an
m
tra
32. How does backpressure work in Spring Reactive streams?

Answer:​
Backpressure allows consumers to signal producers about how much data they can handle,
at
preventing memory overload.

Spring uses Project Reactor, which supports backpressure through Publisher and
nk

Subscriber.

Example:
ve
@

33. How do you test @RestController in Spring Boot using


@WebMvcTest?

Answer:​
Use @WebMvcTest for controller-layer testing and mock dependencies.

20
Example:

a
an
m
tra
34. What is the purpose of @SpyBean and @MockBean in Spring Boot
testing?
at
Answer:

●​ @MockBean: Replace bean with a Mockito mock.


nk

●​ @SpyBean: Spy on the actual bean to partially mock behavior.

Example:
ve
@

35. How does Spring Kafka handle message retries and dead-letter topics?

Answer:​
Use DefaultErrorHandler and configure retries or forward to dead-letter-topic.

21
Example:

a
an
36. How does Spring Security manage session fixation attacks?

m
Answer:​
By default, Spring Security changes the session ID on login to prevent session fixation.
tra
To configure:
at

Options:
nk

●​ none(): Don’t change session


●​ newSession(): Create new session without copying attributes
ve

37. What is WebClient and how does it replace RestTemplate?


@

Answer:​
WebClient is a non-blocking, reactive HTTP client that supports async requests.

22
Example:

a
38. How do you perform method-level validation using Spring Boot and

an
Hibernate Validator?

Answer:​
Use @Validated at class level and @Min, @NotNull, etc., on method parameters.

m
Example: tra
at
nk

39. What is Spring Cloud Gateway and how does it differ from Zuul?
ve

Answer:

Feature Spring Cloud Gateway Zuul 1


@

Reactive support Yes (Project Reactor) No

Performance High (Netty) Lower (Servlet-based)

Path Rewriting, Filters Declarative + Code Mostly code

23
Example:

a
an
40. How can you create a custom Spring Boot actuator endpoint?

Answer:​
Use @Endpoint and expose it via actuator configuration.

m
Example: tra
at
nk

Enable in application.yml:
ve
@

41. How do you implement request tracing and correlation ID in Spring


Boot microservices?

Answer:​
Assign a unique ID per request (correlation ID) and pass it across service calls.

24
Example using Filter:

a
an
m
tra
42. What is functional bean registration in Spring Boot and why use it?

Answer:​
Functional bean registration provides a Java-config-only way to register beans without
at
annotations, improving clarity and startup time.

Example:
nk
ve
@

43. How to expose Prometheus metrics with Spring Boot and visualize in
Grafana?

Answer:

1.​ Add dependency:

25
2.​ Enable endpoint:

a
an
3.​ Access metrics at: http://localhost:8080/actuator/prometheus

m
44. How can you build a modular Spring Boot application using Java
modules (JPMS)?
tra
Answer:​
Split app into multiple modules with module-info.java.
at
Example:
nk
ve

Register module-path in build tools like Maven/Gradle, and avoid reflection-related features
incompatible with JPMS.
@

45. How do you secure REST APIs using API key headers in Spring Boot?

Answer:​
Use a OncePerRequestFilter to intercept and validate a custom API key header.

Example:

26
a
an
46. What is the purpose of @Conditional and how do you create a custom
condition?

Answer:​

m
@Conditional allows beans to be loaded based on custom logic.

Custom Condition:
tra
at

Usage:
nk
ve
@

47. How do you implement canary deployment with Spring Boot +


Kubernetes?

Answer:​
Create two deployments:

●​ Stable version (v1) and


●​ Canary version (v2)

27
Use K8s Ingress or Istio to split traffic (e.g., 90%-10%).

Istio VirtualService

Example:

a
an
m
48. How do you manage secrets in Spring Boot securely?
tra
Answer:​
Best practices:
at
●​ Avoid plaintext .properties
●​ Use Spring Cloud Vault, AWS Secrets Manager, or Azure Key Vault.
nk

Vault Example:
ve
@

Inject values:

28
49. How to handle JSON Patch or Merge Patch in Spring Boot?

Answer:​
Use Jackson and JsonMergePatch or libraries like json-patch.

Example:

a
an
50. How do you implement multi-tenancy in Spring Security?

m
Answer:​
Approaches:
tra
1.​ Tenant from JWT
2.​ Tenant from subdomain/header
3.​ Tenant stored in SecurityContext
at
Example:
nk
ve
@

29

You might also like