Guide To Clear Spring Boot Microservice Interviews (Free Sample Copy)
Guide To Clear Spring Boot Microservice Interviews (Free Sample Copy)
Introduction 3
Why You Should Prepare for Spring-Boot & Microservice Interview 5
How to Prepare for Spring-Boot & Microservice Interview 6
Chapter 1: Spring-Framework 8
What is Spring Framework? 8
What is Inversion of control? 8
What is Spring IOC Container? 9
In How many ways we can define the configuration in spring? 9
What is Dependency injection? 9
Difference between Inversion of Control and Dependency Injection? 10
What are the types of dependency injection and what benefit we are getting
using that? 11
Which one is better Constructor-based or setter-based DI? 12
What is Method Injection? 12
How inversion of control works inside the container? 12
What are different spring modules? 13
What are Spring MVC, Spring AOP and Spring Core modules? 14
How Component Scanning(@ComponentScan) Works? 15
What is ApplicationContext and how to use inside spring? 16
What is BeanFactory and how to use inside spring? 16
What is Bean? 16
What are Bean scopes? 17
What is the Spring bean lifecycle? 17
What is the bean lifecycle in terms of application context? 18
Difference Between BeanFactory and ApplicationContext? 19
What is default bean scope in spring? 19
How bean is loaded inside spring, can you tell the difference between Lazy
loading and Eager loading? 20
Lazy Loading vs Eager Loading in spring (Important interview Question) 20
How to Specify Lazy Loading and Eager Loading 21
How @Autowire annotation works? 21
"As a Java Developer, I've experienced the real challenges of preparing for
Spring Boot Microservice interviews—it's a vast topic that demands
comprehensive readiness.
• Spring Cloud
• Spring Boot with AWS
• Knowledge of AWS cloud
• Continuous Integration and Continuous Deployment (CICD)
• Jenkins
• Kubernetes, Docker, Message broker
• Middleware
• Reactive Spring
Recognizing the significance of these areas, I've included them in the book to
ensure comprehensive preparation for interviews."
The Spring Boot framework has gained immense popularity for building robust
and scalable microservices. Its simplicity, convention-over-configuration
approach, and powerful features have made it a go-to choose for developing
modern applications. However, cracking interviews that assess your proficiency
in Spring Boot microservices requires a solid understanding of not only the
framework itself but also related concepts, design patterns, RESTful APIs,
databases, and more.
This book is structured to cover a wide range of topics, starting with the
fundamentals of the Spring Framework. We'll dive into dependency injection,
To help you grasp the practical aspects, we'll also cover the development of
RESTful APIs, focusing on HTTP methods, request/response handling, security,
and best practices. In addition, we'll explore Spring Cloud, Spring Boot with AWS
Scenario based interview question on spring boot microservice and commonly
encountered in microservice interviews.
Whether you are aiming for a junior or senior-level position, "Guide to Clear
Spring Boot Microservice Interviews" will serve as your go-to resource, providing
you with the insights, knowledge, and confidence needed to excel in your
interviews and land your dream job.
Best Regards,
Ajay Rathod
Foremost, relying solely on core Java skills won't suffice in your career or daily
job. Why? Because Java technology invariably serves as the backbone in most
backend server applications, employing frameworks like Spring, Spring Boot,
Hibernate, Struts, among others.
During my early career days, I had to delve into frameworks like Spring Boot
and Hibernate for my current job tasks and interviews. It's safe to say, Java
interviews almost always include questions on Spring Boot and microservices.
It's invaluable to gain hands-on experience with Spring or Spring Boot projects,
as practical work surpasses theoretical learning. Hence, I encourage my readers
to both learn and work on projects within these technologies.
Regardless of your experience level, this book provides insights into interview
expectations, serving as a knowledge repository. If you opt for a learning
approach, perusing the chapters sequentially will offer a comprehensive
understanding of crucial topics.
For those pursuing Java developer roles where Spring Boot microservices are a
desired skill, this book serves as a valuable resource, aiding in quicker
preparation.
Along with Spring-Boot, Microservice is one more topic which is inseparable from
it, mostly in Microservice environment spring boot is used as implementation
and having good knowledge on this microservice is crucial.
If you're already familiar with the Spring framework, understanding concepts like
the Spring IOC container, dependency injection, Autoconfiguration, Actuators,
starter dependency, and others is advantageous. If not, start learning and
practice by writing programs related to these concepts.
Prerequisites:
Spring Cloud
Participate in as many interviews as possible to grasp the latest trends and note
down topics for focused preparation. This strategy worked wonders for me.
Lastly, concentrate on the topics you're most confident in. Your responses will
shape the interview's outcome. Best of luck!
The Spring Framework's IoC container simplifies this process by taking over the
responsibility of creating and managing objects. You simply tell Spring what
objects you need, and it will create them for you and provide them to your code.
This is called dependency injection.
Dependency injection makes your code more modular and easier to maintain. It
also reduces the risk of errors, because you no longer have to worry about
creating objects correctly.
The container gets its instructions on what objects to instantiate, configure, and
assemble by reading configuration metadata. The configuration metadata is
represented in XML, Java annotations, or Java code. It lets you express the
objects that compose your application and the rich interdependencies between
those objects.
1. XML based config : It can be useful to have bean definitions span multiple
XML files. Often, each individual XML configuration file represents a logical layer
or module in your architecture.
Code is cleaner with the DI principle, and decoupling is more effective when
objects are provided with their dependencies. The object does not look up its
dependencies and does not know the location or class of the dependencies. As a
result, your classes become easier to test, particularly when the dependencies
are on interfaces or abstract base classes, which allow for stub or mock
implementations to be used in unit tests.
Goal Decouple objects and increase flexibility Improve maintainability and testability
External entity (e.g., framework)
controls object creation and Inject dependencies into objects through
Mechanism dependencies constructors, setters, or method arguments
IoC containers are responsible for creating and managing objects, and they do
this by relying on a set of configuration rules that define how objects are created
and wired together.
Object creation: When your application requests an object from the container,
the container uses the configuration rules to create a new instance of the
requested object.
Dependency injection: The container injects any required dependencies into the
newly created object. These dependencies are typically defined in the
configuration rules.
Core Container: The Core Container module forms the foundation of the Spring
Framework, providing essential services like dependency injection, bean lifecycle
management, and resource management. It's responsible for creating,
configuring, and managing objects throughout the application.
Test: The Test module offers tools and frameworks for testing Spring
applications, including support for dependency injection in unit tests, integration
tests, and web application tests.
Here is the diagram to visualize the spring framework runtime as per module
What are Spring MVC, Spring AOP and Spring Core modules?
Reason to ask this question is, these three modules are very important while
developing the spring-based application.
Spring MVC, Spring AOP, and Spring Core are three essential modules of the
Spring Framework that play crucial roles in building robust and scalable Java
applications.
Controller classes: Handle user requests by processing data, interacting with the
model, and selecting appropriate views.
Aspect execution: Handles the invocation of aspect advice, which defines the
actions to be taken at the join points.
Spring Core
e.g.
Configuration Class:
@Configuration
@ComponentScan("com.example. springapp")
myService.doSomething();
context.close();
Here is example,
myService.doSomething();
What is Bean?
Bean:
(Default) Scopes a single bean definition to a single object instance for each
Spring IoC container.
Prototype:
Request:
Scopes a single bean definition to the lifecycle of a single HTTP request. That is,
each HTTP request has its own instance of a bean created off the back of a
single bean definition. Only valid in the context of a web-aware Spring
ApplicationContext.
Session:
Scopes a single bean definition to the lifecycle of an HTTP Session. Only valid in
the context of a web-aware Spring ApplicationContext.
Application:
Websocket:
Scopes a single bean definition to the lifecycle of a WebSocket. Only valid in the
context of a web-aware Spring ApplicationContext.
• The application context plays a central role in managing the bean lifecycle,
providing various mechanisms to control the creation, configuration,
usage, and destruction of beans.
• Bean Configuration Metadata: The application context stores configuration
metadata for beans, defining how they should be created, configured, and
managed.
The Spring Framework uses a process called bean instantiation to create beans
and make them available to the application. This process involves the following
steps:
Scanning for beans: The Spring Framework scans the application context for
classes that are annotated with Spring annotations such as @Component,
@Service, @Repository, and @Controller.
Configuring beans: The Spring Framework configures each bean by setting its
properties and injecting its dependencies.
Initializing beans: The Spring Framework initializes each bean by calling its
initialization callbacks.
Eager Loading:
Lazy Loading:
• Use eager loading for beans critical for startup or frequently used.
• Use lazy loading for beans potentially not needed or used infrequently.
• Consider the trade-off between startup time and potential access delays.
• Spring also allows mixing both strategies within the same application for
optimal performance.
@Lazy
@Service
@Service
Use lazy loading for beans that are not needed by the application as soon as it
starts up.
Use eager loading for beans that are needed by the application as soon as it
starts up.
Use eager loading for beans that have a high startup cost.
Use lazy loading for beans that are not frequently used.
• byType: This is the default type of autowiring. The Spring Framework will
look for a bean with the same type as the dependency.
• byName: The Spring Framework will look for a bean with the same name
as the dependency.
• byConstructor: The Spring Framework will look for a constructor that
takes a single argument of the type of the dependency.
• byQualifier: The Spring Framework will look for a bean with a qualifier
that matches the specified value.
@Configuration
@Bean
In this example, the myService() method is annotated with @Bean. This tells the
Spring container to create an instance of the MyServiceImpl class and manage
its lifecycle. The bean can then be injected into other beans using the
@Autowired annotation.
@Configuration
@Bean
e.g.
e.g.
@Value("${app.name}")
e.g.
@Value("#{'${app.name}'.toUpperCase()}")
Stateless beans are typically used for services that perform actions or
calculations, but do not maintain any state between invocations. This can include
services that perform mathematical calculations, access external resources, or
perform other tasks that do not require the bean to maintain state.
Stateless beans can be implemented as singleton beans, and multiple clients can
share the same instance of the bean. Since stateless beans do not maintain any
Stateless beans also have the advantage of being simpler and easier to reason
about, since they do not have to worry about maintaining state between
invocations. Additionally, since stateless beans do not maintain any state, they
can be easily serialized and replicated for high availability and scalability.
Spring provides several ways to inject beans into other beans, including:
Constructor injection: A bean can be injected into another bean by passing it
as a constructor argument. Spring will automatically create an instance of the
dependent bean and pass it to the constructor.
public class BeanA {
private final BeanB beanB;
public BeanA(BeanB beanB) {
this.beanB = beanB;
}
}
Setter injection: A bean can be injected into another bean by passing it as a
setter method argument. Spring will automatically call the setter method and
pass the dependent bean.
public class BeanA {
private BeanB beanB;
@Autowired
public void setBeanB(BeanB beanB) {
this.beanB = beanB;
}
}
Field injection: A bean can be injected into another bean by annotating a field
with the @Autowired annotation. Spring will automatically set the field with the
dependent bean.
By default, Spring will try to autowire beans by type, but if there are multiple
beans of the same type, it will try to autowire by name using the bean's name
defined in the configuration file.
A cyclic dependency between beans occurs when two or more beans have a
mutual dependency on each other, which can cause issues with the creation and
initialization of these beans.
There are several ways to handle cyclic dependencies between beans in Spring:
Lazy Initialization: By using the @Lazy annotation on one of the beans
involved in the cycle, it can be initialized only when it is actually needed.
@Lazy
@Autowired
private BeanA beanA;
Constructor injection: Instead of using setter or field injection, you can use
constructor injection, which will make sure that the dependencies are provided
before the bean is fully initialized.
@Autowired
public BeanA(BeanFactory beanFactory) {
this.beanB = beanFactory.getBean(BeanB.class);
}
}
What would you call a method before starting/loading a Spring boot
application?
In Spring Boot, there are several methods that can be called before starting or
loading a Spring Boot application. Some of the most commonly used methods
are:
main() method: The main() method is typically the entry point of a Spring Boot
application. It is used to start the Spring Boot application by calling the
SpringApplication.run() method.
1. Configuration:
2. Request Flow:
• When a client sends a request, it goes through each filter in the specified
order.
• Each filter can:
3. Response Flow:
• Once the request reaches the application logic and receives a response,
the response flows back through the filters in reverse order.
• Filters can again:
• Inspect the response headers and body.
• Modify the response content or headers.
Benefits:
• Intercept and modify requests and responses: Provide more control over
application behavior.
• Centralize common tasks: Avoid duplicating code for security, logging,
etc.
• Chain multiple filters: Achieve complex processing logic by combining
multiple filters.
What is DispatcherServlet?
DispatcherServlet acts as the central "front controller" for Spring MVC
applications. It is a Servlet that receives all incoming HTTP requests and
delegates them to appropriate controller classes. The DispatcherServlet is
responsible for identifying the appropriate handler method for each request and
invoking it, ensuring that the request is processed correctly.
The following example of the Java configuration registers and initializes the
DispatcherServlet, which is auto-detected by the Servlet container.
@Override
context.register(AppConfig.class);
ServletRegistration.Dynamic registration =
servletContext.addServlet("app", servlet);
registration.setLoadOnStartup(1);
registration.addMapping("/app/*");
e.g.
@Controller
@GetMapping("/hello")
return "index";
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
Pattern Matching: The HandlerMapping compares the request URI and HTTP
method against the registered request patterns. It uses pattern matching rules
to identify the most specific matching pattern.
Response Handling: After the handler method completes its execution, the
DispatcherServlet receives the generated response object. It prepares the
response by setting appropriate headers and content, and sends the response
back to the client.
@RestController
@RequestMapping("/persons")
class PersonController {
@GetMapping("/{id}")
// ...
@PostMapping
// ...
You can use the @RequestParam annotation to bind Servlet request parameters
(that is, query parameters or form data) to a method argument in a controller.
@Controller
@RequestMapping("/pets")
@GetMapping
model.addAttribute("pet", pet);
return "petForm";
By default, method parameters that use this annotation are required, but you
can specify that a method parameter is optional by setting the @RequestParam
annotation’s required flag to false or by declaring the argument with an
java.util.Optional wrapper.
@Pathparam
Function:
It allows you to map variables from the request URI path to method parameters
in your Spring controller.
This gives you a cleaner and more flexible way to handle dynamic data in your
API.
Inside the annotation, you specify the name of the variable in the URI path that
should be bound to the parameter.
Controller processes the request: The controller handles the request and
performs the necessary processing logic. It may interact with the model
component to retrieve data or update the data.
Model updates the data: The model component manages the data and provides
an interface for the controller to retrieve or update the data.
View renders the response: The view template is rendered to generate the
response. It may include data from the model component.
However, it's important to note that if the singleton bean is stateful, and the
state is shared among requests, this could lead to race conditions and other
concurrency issues. For example, if two requests are trying to modify the same
piece of data at the same time, it could lead to data inconsistencies.
To avoid these issues, it's important to make sure that any stateful singleton
beans are designed to be thread-safe. One way to do this is to use
synchronization or other concurrency control mechanisms such as the
synchronized keyword, Lock or ReentrantLock classes, or the @Transactional
annotation if the bean is performing database operations.
On the other hand, if the singleton bean is stateless, it can handle multiple
parallel requests without any issues. It can be used to provide shared
functionality that doesn't depend on the state of the bean.
In conclusion, a singleton bean can handle multiple parallel requests, but it's
important to be aware of the state of the bean and to ensure that it's designed
to be thread-safe if it has shared state.
These are just a few examples of the design patterns used in Spring, there are
many more. Spring framework makes use of these patterns to provide a
consistent and simple way to build applications, making it easier to manage
complex systems.
The factory method is a design pattern that provides a way to create objects of
different classes based on a factory interface. In Spring, the IoC container acts
as the factory, and the factory interface is represented by the BeanFactory or
ApplicationContext interfaces.
The IoC container is responsible for creating and managing the lifecycle of
beans. When you define a bean in the configuration, the IoC container will use
Here's an example of how you can define a bean in Spring using the factory
design pattern:
@Configuration
public class MyConfig {
@Bean
public MyService myService() {
return new MyService();
}
}
In this example, the myService() method is annotated with @Bean. This tells
Spring to create an instance of the MyService class when the IoC container is
created. The IoC container will use the factory pattern to create the instance and
manage its lifecycle.
In Spring, AOP proxies are created by the IoC container, and they are used to
intercept method calls made to the target bean. This allows you to add
additional behaviour, such as logging or security checks, before or after the
method call is made to the target bean.
AOP proxies are created using one of three proxy types: JDK dynamic proxies,
CGLIB proxies, or AspectJ proxies.
JDK dynamic proxies: This is the default proxy type in Spring, and it is used to
proxy interfaces.
Here's an example of how you can use Spring AOP to add logging to a bean:
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.*.*(..))")
public void logBefore(JoinPoint joinPoint) {
log.info("Started method: " + joinPoint.getSignature().getName());
}
}
If a singleton bean is injected into a prototype bean, then each time the
prototype bean is created, it will receive the same instance of the singleton
bean. This is because the singleton bean is only created once during the startup
of the application context, and that same instance is then injected into the
prototype bean each time it is created.
On the other hand, if a prototype bean is injected into a singleton bean, then
each time the singleton bean is called, a new instance of the prototype bean will
be created. This is because prototype beans are not managed by the container,
and a new instance is created each time a dependency is injected.
@Scope("singleton")
@Component
@Scope("prototype")
@Autowired
In this example, when a prototype bean is created and injected with the
singleton bean, it will receive the same instance of the singleton bean each time
it is created. However, if the singleton bean is created and injected with the
prototype bean, it will receive a new instance of the prototype bean each time it
is called.
It's important to note that mixing singleton and prototype scopes in a single
application context can lead to unexpected behaviour and should be avoided
unless necessary. It's best to use one scope consistently throughout the
application context.
Overall, both Spring and Spring Boot are powerful frameworks that can be used
to build enterprise-level applications. The choice between them depends on the
specific needs of your application and the level of flexibility and customization
that you require.