KEMBAR78
Spring Boot Interview Questions | PDF | Class (Computer Programming) | Databases
0% found this document useful (0 votes)
4 views6 pages

Spring Boot Interview Questions

Uploaded by

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

Spring Boot Interview Questions

Uploaded by

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

1.

What is Bean
- It Java Object + configuration metadata (Annotations)
Two ways to create a bean
@Component
@Configuration + @Bean

2. What is Application Context?


- It is the implementation of Spring IoC Container, which will store all the beans
inside an application

3. suppose we have one microservice which takes output of another microservice, but
now another microservice is down and user is hitting our microservice so what will
happen and how to handle?
- If service 2 is down we will get RestClientException. To handle this scenario, we
can add try try-catch block and return some error message to the user in case of
RestClientException.
Or we can add circuitBreaker to handle this scenario.
There are 3 states in a circuitBreaker
closed - service1 will hit service2 and get response
open - service1 is down and not returning response, circuit will be closed
halfOpen - after a while some trial request will be hit and check if service2 has
recovered.
eg
@circuitBreaker(name="method1", callbackMethod="mycallbackMethod")
method1{...}
mycallbackMethod(Throwable T){...}

4. How can we configure circuitBreaker?


- The most common way is to use the Resilience4j library.
- Steps:
Include resilience4j-spring-boot3 dependency in pom.xml
Enable Circuit breaker annotation using @CircuitBreaker and add a fallback
method
Configure the circuit breaker in application.properties
slidingWindowSize=10 // the circuit breaker stores the outcome of the
last 10 calls, used to calculate the failure rate
failureRateThreshold=50 // if more than 50% of the calls in the sliding
window fail, the circuit breaker will open
waitDurationInOpenState=10s // after the circuit breaker opens, it will
wait 10 sec before trying again
permittedNumberOfCallsInHalfOpenState=3 // when transitioning to half-
open-state, only 3 trial calls are allowed to test if the system has recovered
minimumNumberOfCalls=5 //the circuit breaker won't evaluate the failure
rate until at least 5 calls have been recorded
automaticTransitionFromOpenToHalfOpenEnabled=true //Enables automatic
transition from open to half-open state after waitDurationInOpenState expires.

5. @BeforeEach & @BeforeAll


- BeforeEach runs before each test method in the test class. Use it to set up test
data or state freshly before every test.
- BeforeAll runs once before all test methods in the class. Used for the expensive
setup that only needs to happen once, eg, start the database

6. How do you test the void method?


- We can use Mockito.verify()

7. What is Mock vs InjectMock


- Mock: creates a mock instance of a class or interface, and this mock does not
execute real methods unless explicitly stubbed. It is used to simulate dependencies
by mocking their behaviour. In mock, we control what method returns without calling
the actual logic.
- InjectMocks: It creates an instance of the class under test. Injects all the
mocks annotated with @MOck into this instance. We test this object with real logic,
but its dependencies are mocked.
- Eg @InjectMocks
UserService userService; // Real instance of UserService

@Mock
UserRepository userRepository; // Injected into userService

8. When can we annotate a class with @Component? what if we replace @Service with
@Component, will it work?'
- You can annotate a class with @Component in Spring when you want to declare it as
a Spring-managed bean so that Spring IOC container can automatically detect,
instantiate and manage it through component scanning. It is used when our class is
a general-purpose Spring bean without a more specific stereotype. eg utility class
- Yes if we replace @Service with @Component it will work fine because @Service is
itself a specialization of @Component

9. When can we use the @Bean annotation and where?


- @Bean is used to declare a method that produces a Spring-managed bean. It tells
Spring, "Execute this method, and register the returned objects as a bean in the
application context". It's typically used in @Configuration classes
@Bean is preferred over @Component when you don't control the source code (third-
party classes) or when you want to programmatically configure the bean

10. What does EnableAutoConfiguration do? what and how does it configure?
- @EnableAutoConfiguration configures the application automatically based on the
dependencies present in the classpath.

11. How do authorization implemented in you project?


- We are using SSO(single sign on) with OAuth2 for authentication and sso returns
oAuth2User details which includes user identity and roles, which spring boot app
authorize

12. Global exception handling


- A Global Exception Handler in spring boot is centralized mechanism to handle
exceptions thrown across the whole application, rather than writing try catch block
in each controller or service.
In Spring Boot, I use @ControllerAdvice and @ExceptionHandler to implement global
exception handling. It allows me to manage both specific and general errors in a
centralized way, improving maintainability and user-friendly error reporting.

13. how to avoid deadlock?


- lock ordering, lock timeout, avoid nested lock, use concurrent collections

14. if we have to change the defult tomcat server in spring boot to another server,
what all changes we will have to make?
- Exclude tomcat dependency in pom.xml and add your desired server dependency in
pom.xml and thats it. Spring boot will detect the new server through class path and
use it.

15. What are microservices components? and how are they used in Spring Boot
application?
- Service Discovery, API Gateway, Config Server, Load Balancer, Circuit Breaker,
Security-Auth, Messaging, Persistence
16. Design pattern used in springboot application?
- Dependency Injection: Decouples object creation from business logic. used by
@Autowired, @component, @Service etc
- Singleton Pattern: Ensure a class has only one instance and provide global point
of access
- Factory Pattern: Spring container acts as a factory for creating beans. you dont
instantiate the bean, eg: BeanFactory
- Proxy Pattern: Adds additional behaviour without changing the original code. eg :
@Transactional, @Cachable
- Template Method Pattern: Defines the skeleton of an operation, deferring steps to
subclasses or other components. eg : RestTemplate, JDBCTemplate
- MVC Pattern: separate the application into MOdel(data), view(UI) and controller
(business logic) promoting separation of concerns
- Builder pattern: Build complex objects step by step. eg: ResponseEntity,
HttpHeaders

17. How is an HTTP request routed in the controller?


- Using dispatcher servlet, which acts as a front controller, routes the incoming
HTTP request to the correct applicable endpoint in the controller

18. springboot is stateful or stateless?


- Bydefault, springboot is stateless

19. Pagination and sorting


- Spring Data JPA provides built-in support for pagination and sorting, we have to
extends JpaRepository

Sort sortOrder = Sort.by(asc, id);


Pageable pageable = PageRequest.of(page, size, sortOrder);
return userRepository.findAll(pageable); //this will return Page<User> response

20. JWT and OAuth2

21.

22. @Qualifier
- @Qualifier is used to resolve the ambiguity when spring finds multiple beans of
the same type and doesn't know which one to inject. It works alongside @Autowired
For eg:
@Component
public class Dog implements Animal {}
@Component
public class Cat implements Animal {}

Now, if you do
@Autowired
private Animal animal; //spring will throw error because it finds two bean of type
Animal

we can fix it by
@Autowired
@Qualifier("dog") //"dog" is the bean name(by default, class name is camel case)
private Animal animal;

23. failfast, failslow, something?


- Fail-Fast and Fail-Slow (or Fail-safe) are concepts in software design,
especially in collection handling, error handling and system desing.
- A fail-fast system immediately throws an error/exception as soon as the problem
is detected
- A fail-safe system tries to continue operating despite errors to maintain
availability and avoid system crashes, used in logging, monitoring, circuit
breakers etc

24. Content properties?


- Metadata or attributes that describe the content being sent, received, or stored
in the database.
Eg: content-Type - eg application/json, etc

25. Microservices Architecture?


- Microservices architecture is a software design approach where an application is
built as a collection of small, loosely coupled services, each responsible for a
specific business capability.
Characteristic
- Single Responsibility: Each service should focus on one specific function
- Independent Deployment: Services can be developed, deployed and scaled
independently
- Own Data: Each microservice typically manages its own database
- Technology Flexibility: Different services can use different languages,
databases, or frameworks.
- Communication: Services communicate via REST APIs or messaging systems.

26. Aspect Oriented programming (AOP)?


- Aspect-Oriented Programming allows you to separate cross-cutting concerns or
extra tasks like (logging, security, transactions) from your main business logic
- Aspect: A module that encapsulates cross-cutting logic
- Join Point: A point during execution where an aspect can be applied
- Advice: The action taken by an aspect(eg: @before, after, @around)
- PointCut: Expression to match join points
- Weaving: the process of applying aspects to the target object

27. How to implement AOP


- Add spring AOP dependency in pom.xml
- Crete Business Service
- Create an Aspect class like below:
@Aspect
@Component
public class LoggingAspect {

@Before("execution(* com.example.demo.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
System.out.println("Logging BEFORE method: " +
joinPoint.getSignature().getName());
}

@After("execution(* com.example.demo.service.*.*(..))")
public void logAfter(JoinPoint joinPoint) {
System.out.println("Logging AFTER method: " +
joinPoint.getSignature().getName());
}

@Around("execution(* com.example.demo.service.*.*(..))")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
System.out.println("BEFORE method: " + joinPoint.getSignature().getName());
Object result = joinPoint.proceed();
System.out.println("AFTER method: " + joinPoint.getSignature().getName());
return result;
}
}
- Call the method in rest controller

28. HOw do you handle multiple beans at the same time in springboot?
- we can handle multiple beans by below ways:
APPORACH WHEN TO USE
@Qualifier You want to choose a specific bean by name
@Primary You want one bean to be injected by default
Inject List/Map You want to work with all beans of the same type
Custom @Qualifier You want fine-grained control over injection

29. What is custom annotation, and how can we create it?


-

30. How does interservice communication happen between microservices?


- In microservices, interservice communication happens either synchronously (via
REST, gRPC) or asynchronously (via messaging systems like RabbitMQ or Kafka).
Synchronous is suitable for real-time interactions, while asynchronous is better
for decoupling and handling high-throughput or background tasks. We often use
service discovery, API gateways, and circuit breakers to make communication
scalable and resilient.

31. How can we customise a specific autoconfiguration in springboot?

32. What are the different scopes available in springboot for beans?
- Below are the scopes
singleton One for the container (default)
prototype New every time requested
request One per HTTP request
session One per HTTP session
application One per servlet context
websocket One per WebSocket session

33. Can we create a custom scope in springboot If yes, how?

34. Difference between service registry and service discovery?


- Service Registry is a central component in a microservices architecture that
stores the network locations (host, port, etc.) of all the services in the system.
It acts like a dynamic address book.
Service Discovery is the process of looking up and locating a service instance by
querying the service registry at runtime.
There are two types of discovery:
Client-side discovery: The client queries the registry and chooses a service
instance (e.g., Netflix Ribbon).
Server-side discovery: A load balancer or gateway does the lookup on behalf of the
client (e.g., Spring Cloud Gateway).

35. saga design pattern?


- Saga Pattern is a microservices design pattern used to manage data consistency
in a distributed system without using distributed transactions. In microservices,
one business process may span multiple services. If one service fails, we can't
rollback easily using database transactions (since each service may have its own
DB). So we use sagas to maintain consistency using local transactions and
compensating actions.
1. Choreography-based Saga
Each service listens to events and reacts. No central controller.
2. Orchestration-based Saga
A central orchestrator tells each service what to do next.

36. what is idempotency in microservices?

37. API Gateway?


- An API Gateway is a server that acts as a single entry point for all clients to
interact with your backend microservices. Instead of calling microservices
directly, clients call the API Gateway, which then routes, transforms,
authenticates, and aggregates the requests/responses.

38. Difference between api gateway and load balancer


- In a distributed or microservices architecture, both API Gateway and Load
Balancer play important roles, but they serve different purposes:
A Load Balancer works primarily at the network or transport layer (Layer 4), and
sometimes at the application layer (Layer 7). Its main function is to distribute
incoming traffic evenly across multiple service instances to ensure high
availability and reliability. It doesn’t understand much about the application
logic; it simply routes traffic based on IP or port.
An API Gateway, on the other hand, works at the application layer and serves as a
single entry point for all client requests. It can do smart request routing based
on paths or headers, handle authentication and authorization (like JWT/OAuth2),
perform rate limiting, request/response transformation, logging, and even aggregate
responses from multiple services.
For example, in a microservices setup, the client might call /user/123, and the API
Gateway routes it to the correct user service. At the same time, it verifies the
JWT token, applies rate limits, and logs the request — things a load balancer
doesn’t handle.
In most real-world applications, both are used together: the load balancer handles
traffic distribution across multiple API gateway instances, and the API gateway
manages the API-specific logic.

39. How can we have multiple db connections in our spring boot application?

40. Http Status codes


- 200 - OK
201 - Created
400 - Bad Request
401 - Unauthorized
403 - Forbidden
404 - Not Found
422 - Unprocessable Entity
500 - Internal Server Error
502 - Bad Gateway
504 - Gateway Timeout

You might also like