Spring Intermediate Concepts(Interview)
Hello guys! if you are looking for some concepts for backend developer which is asked in the interview and also increase your understanding in spring.
So let's start……..
First talk about how @ComponentScan works in spring
Before this let's understand Component Annotation
A component is annotations which refer to the class that spring searched for and which was managed by the IOC container.There may be multiple places for component annotations in a project, So problems arise with how to search for component annotations.
So, Now @ComponentScan comes into play.
ComponentScan(basePackage={“path1”, “path1”})
@ComponentScan(basePackages = {"com.example.controller", "com.example.service", "com.example.repository"})
so the component scan is used to search for the Component class in all packages that come under the hierarchy of “path1” and also of “path2”.
@ SpringBootApplication , when we use this annotations it automatically initates ComponentScan for the package in which SpringBootApplication is written.
Scope Of Bean
The scope Of Bean is the most important concept for an interview
There are multiple scopes for beans but mainly are of 4 type
Singleton:- One instance per spring context, means all requests for that bean name will return the same object, which is cached. Any modifications to the object will be reflected in all references to the bean.
Singleton is default scope of spring
@Bean@Scope("singleton")public ComplexAlgoImp complexAlgoImp() {Prototype:- New bean whenever requested, which means a bean with theprototypescope will return a different instance every time it is requested for that.@Bean@Scope("prototype")public ComplexAlgoImp complexAlgoImp() {Request:- One Bean per HTTP requests. Web-aware spring application context, which means only a single instance will be created and available during the complete lifecycle of an HTTP request.@Bean@Scope("request")public ComplexAlgoImp complexAlgoImp() {Session:- One Bean per HTTP session. Web-aware Spring application context, which means only a single instance will be created and available during the complete lifecycle of an HTTP Session.@Bean@Scope("session")public ComplexAlgoImp complexAlgoImp() {
A “web-aware” Spring application is one that is designed to run in a web-based environment and has access to the web-related features and capabilities provided by Spring
Dependency Injection
We already discussed Dependency Injection in detail, you can check out here
Types Of Dependency Injection
Setter Injection@Componentpublic class TOdoBuisnessService{TodoDataService dataService;@Autowiredpublic void setDataService(TodoDataService dataService){this.dataService=dataService;}}Constructor Injection@Componentpublic class TodoBuisnessService{TodoDataService dataService;@Autowiredpublic TodoBuisnessService(TodoDataService dataService){this.dataService=dataService;}}
At the enterprise level or at high-level design, we mostly used constructor injection over setter injection. So now discuss some reason for it.
Why is Constructor Injection preferred over Setter Injection?
Encapsulation:Constructor injection allows you to ensure that all the required dependencies for a bean areset at the time of construction, and cannot be changed afterward. This helps to ensure that the bean is in a valid state and encapsulates its dependencies. In contrast, with setter injection,dependencies can be changed after the bean is constructed, which can lead to an inconsistent or invalid state.Immutability:Constructor injection allows you to make the dependencies of a bean immutable, which can make the bean easier to reason about and test. In contrast, with setter injection, dependencies can be changed at any time, making it harder to reason about the behavior of the bean and write effective tests.Safety:Constructor injection ensures that all required dependencies are set at the time of construction, which helps toprevent runtime errorsrelated to missing or null dependencies. In contrast, with setter injection, dependencies can be set to null or missing,which can lead to runtime errors or unexpected behavior.
Now goes to Next Concept or you can say the most interesting one
How does spring do auto wiring? or How autowire annotation works?
autowired annotations find the relevant component by using two methods/approach and these two methods are used in sequence i.e. if the first fails then moves to the second method.
Methods are:-
By TypeBy Name
By Type:-
First, take a look at the following code
@Componentpublic class ComplexAlgorithmImpl{
@Autowiredprivate SortAlgorithm sortAlgorithm;
}
public interface SortAlgorithm{
public int[] sort(int numbers[])
}
@ComponentpublicclassQuickSortAlgorithm implement SortAlgorithm{
By putting autowired, First spring find the implementations of SortAlgorithm (Since it's an interface, we will look for its implementations and in the case of class it looks for class). QuickSortAlgorithm is implementing SortAlgorithm. so spring wired up QuickSortAlgorithm to sortAlgorithm.
By Name:-
In the previously given example, if there is two class that is implementing SortAlgorithm and the name of the variable is changed to quickSortAlgorithm, Then how does spring find with which it wired up?
@Componentpublic class ComplexAlgorithmImpl{@Autowiredprivate SortAlgorithm quickSortAlgorithm;}@ComponentpublicclassBubbleSortAlgorithm implement SortAlgorithm{
In this case, Spring look for the name of the variable (its shift from type to name of the variable) i.e. quickSortAlgorithm. Spring understands camelcase so now it looks for the component class which is implementing SortAlgorithm(interface) and also class name(QuickSortAlgorithm) matches with the variable name(quickSortAlgorithm) and then wire QuickSortAlgoithm to the quickSortAlgorithm variable.
Now let's take look at some annotation that help autowired,
Primary and Qualifier Annotations
Primary:-
@Component@PrimarypublicclassBubbleSortAlgorithm implement SortAlgorithm{
Primary annotation makes the component class priority first when spring look for auto wiring.
Qualifier:-
@Qualifier("mainAlgorithm")private SortAlgorithm sortAlgorithm@Component@Qualifier("mainAlgrithm")public class BubbleSortAlgorithm implements SortAlgorithm{
In This case, Spring looks for Quaalifier with the name “mainAlgorithm” and once it found a component with the same qualifier name, then it autowired.
Thanks for reading this article so far. If you find these Spring Concept useful in your preparation then please share them with your friends and colleagues. I highly appreciate your support.