Spring Boot Basic properties.

Spring Boot - Spring Boot helps developers create applications that just run. Specifically, it lets you create standalone applications that run on their own, without relying on an external web server, by embedding a web server such as Tomcat or Netty into your app during the initialization process.
Advantages of Spring Boot
Spring Boot works well with several servlet containers.
Bootstrapping saves memory space.
Decreased boilerplate code.
No XML configuration required.
WAR files are not required.
POM dependency management.
A large community of helpful users.
Node. js is single-threaded. Also, you don't have to worry about the problems associated with managing multiple threads — whereas, in the Spring Boot world, Java web applications are used to running everything on multiple threads.

pom.xml


A Project Object Model or POM is the fundamental unit of work in Maven. It is an XML file that contains information about the project and configuration details used by Maven to build the project.
The pom. xml file contains information of project and configuration information for the maven to build the project such as dependencies, build directory, source directory, test source directory, plugin, goals etc. Maven reads the pom. xml file, then executes the goal.
dependency -The pom. xml describes the project's dependencies and tells you how to build it. (Dependencies are third-party software required by the project. Some common examples are JUnit and JDBC.
The POM file should be in the project’s root directory.Maven reads the pom.xml file. Downloads dependencies into local repository. Execute life cycles, build phases and goals. Execute plugins.

Spring boot attaches a Tomcat or Jetty server with the compiled jar using Maven or Gradle.

Spring Boot Features


Starter Project :
If suppose we want to make a web application ,spring boot will say - we got spring boot starter web and it will give us a web project.And suppose if we want to work with JDBC than we have spring boot starter jdbc and it will give us a ready project.

Auto-configuration :
Spring boot provide spring boot auto configuration so that it will do the configuration for us and we can focus on the convention ,on our code and not on the configuration. If we want to do some manual configuration,we can do it from application.properties file.

Loosely Coupled Classes :
Coupling shows the degree of dependency between components.
Loose coupling means 1 object will not totally depends on another object.Inorder to overcome from problems of tight coupling between objects ,spring framework uses dependency injection with the help of POJO/POJI model. In tight coupling ,2 classes often change together.
Loosely coupled classesTightly Coupled classes
Degree of dependency between classes is less Degree of dependency is high
If we made some changes in 1 class than there is no requirement to implement those changes in other class If we are making changes in 1 class than it is also require to make changes in the other class.


Integration with other frameworks :
Spring framework allows us to integrate with other frameworks.It provides pre-defined templates for JDBC,hibernate,JPA etc.JPA persist data in SQL stores with java persistence API.

application.properties/application.yml


application.properties ->
application.properties’ or ‘application.yml’ files reduces your development effort by minimizing the amount of XMLs that you were writing in a standard Spring project. Under this file , we accommodate the common properties of our project in the form of key-value pairs in these files. Other than the main application.properties file .
this file is auto detected in a Spring Boot Application. It is placed inside “src/main/resources” directory.
Pre-defined keys
Spring framework provides several common default properties to specify inside application.properties such as to support database, email, JPA, Hibernate, Logging, AOP etc.
Programmer-defined Keys
‘application.properties’ file is loaded using code by adding it in starter/main class.
@PropertySource(“classpath:application.properties”)
@Value - To read one key from the properties .
if the key is not present in the properties file and we try to read using @Value() then it will throw an Exception:
IllegalArgumentException.
create and load multiple properties files in the application @PropertySource({ "classpath:abc.properties", "classpath:pqr.properties", "classpath:xyz.properties", "....", })
If we define the same key with different values in different properties files, which one will be selected?
In this case, the last loaded properties file key will ñ considered.( The value of xyz.properties file key will load )
Sometimes, we need to create custom properties files in order to fulfil the business requirements. It is placed inside “src/main/resources” directory. It stores various properties in key=value format. These properties are used to provide input to Spring container object, which behaves like one time input or static data. it reduces XML based configurations and customize them to simple properties.
----------------------
Create custom property file ->
1) Create your custom file at the same location (‘src/main/resources’)
2) Apply @PropertySource annotation at starter/runner class. as @PropertySource(“classpath:xyz.properties”)
😊😊_________________
read keys of the properties file
1) @value -- To read one key from the properties file, It’s like @Value(“${key}”)
2) @ConfigurableProperties
__________________
application.properties -Properties files are used to keep 'N' number of properties in a single file to run the application in a different environment. In Spring Boot, properties are kept in the application. properties file,
application.properties Vs application.yml
application.propertiesapplication.yml
stores data in sequential format stores data in hierarchical format
supports only key-value pairs (basically string values) supports key-value pair, as well as map, list & scalar type values.
is specifically used by Java can be used by other languages (eg Java, Python, ROR, etc)
When managing multiple configuration profiles, .properties requires you to create .properties file per every profile you can create a section for each specific profile inside a single .yml file

Dependency Injection :


With DI , we don't have to focus on object creation.We only have to focus on logic.Spring boot will give the object when required.earlier to DI, when we want to access properties of 1 class into another than we need to instantiate that class in the main class by using new keyword.So, here we were manually creating the object using new.

There are 2 ways of injecting dependency of 1 bean to aother -
Setter Injection
Constructor Injection

Setter DIConstructor DI
Setter methods are used to inject the values Constructors are used to inject the values
More reliable DILess Reliable
It can override constructor DI It can't override setter DI
It allows Partial DI Partial DI not allowed


Drawback of Setter Injection :
Setter injection doesn't ensure DI.We can't guarantee that certain dependency is injected or not.It means we may have an object with incomplete dependency while constructor injection doesn't allow to construct an object until our dependencies are ready.
Security weaken is another drawback of setter injection .By using setter injection, we can override certain dependencies which is not in constructor injection.

Autowiring :
It is the automatic DI.ie...required bean gets automatically injected/recreated in the desired class.@Autowire annotation is use for this.It does automatic finding of dependencies.This feature enables to inject the object dependency implicitly.This annotation can be use to get rid of setter method of DI.
We can apply @autowire to constructor as well.
Advantages of autowiring :
It requires less code because we don't need to write the code to inject the dependency explicitly.
Autowiring types :No,by name,by type ,constructor , autodetect.

@SpringBootApplication


It is a key annotation ,a top level annotation which contains various other annotation like -

@SpringBootConfiguration ,@EnableAutoCOnfiguration ,@ComponentScan , @filter ,@target ,@Retention ,@Documented ,@Inherited

Spring Boot @SpringBootApplication annotation is used to mark a configuration class that declares one or more @Bean methods and also triggers auto-configuration and component scanning. It's same as declaring a class with @Configuration, @EnableAutoConfiguration and @ComponentScan annotations.
@SpringBootApplication also provides aliases to customize the attributes of @EnableAutoConfiguration and @ComponentScan.

@SpringBootConfiguration : It tells container that the given class can have several bean definition.We can define various beans here that can be available at run-time to the class.
EnableAutoCOnfiguration : It tells spring boot to automatically configure the spring application based on the dependencies it seed on the classpath.
@ComponentScan : It scans the entire package and all it's sub-package which may includes 1 or more classes.If figures out all the beans and create those beans for us.

@EnableAutoCOnfiguration


@EnableAutoConfiguration: enable Spring Boot’s auto-configuration mechanism.Auto-configuration refers to creating beans automatically by scanning the classpath.
The @EnableAutoConfiguration annotation enables Spring Boot to auto-configure the application context. Therefore, it automatically creates and registers beans based on both the included jar files in the classpath and the beans defined by us.
@EnableAutoConfiguration Vs @ComponentScan
@EnableAutoConfiguration annotation tells Spring Boot to "guess" how you will want to configure Spring, based on the jar dependencies that you have added. For example, If HSQLDB is on your classpath, and you have not manually configured any database connection beans, then Spring will auto-configure an in-memory database.
@ComponentScan tells Spring to look for other components, configurations, and services in the specified package. Spring is able to auto scan, detect and register your beans or components from pre-defined project package. If no package is specified current class package is taken as the root package.

@ComponentScan


@ComponentScan: enable @Component scan on the package where the application is located.
Typically, in a Spring application, annotations like @Component, @Configuration, @Service, @Repository are specified on classes to mark them as Spring beans. The @ComponentScan annotation basically tells Spring Boot to scan the current package and its sub-packages in order to identify annotated classes and configure them as Spring beans.
@ComponentScan enables Spring to scan for things like configurations, controllers, services, and other components we define. In particular, the @ComponentScan annotation is used with @Configuration annotation to specify the package for Spring to scan for components

@Configuration


@Configuration -> method annotated with this returns the bean of the class that is managed by the IOC container . It marks that class as a bean . @Configuration: allow to register extra beans in the context or import additional configuration classes.
Designates the class as a configuration class for Java configuration. In addition to beans configured via component scanning, an application may desire to configure some additional beans via the @Bean annotation .

Difference between @SpringBootApplication vs @EnableAutoConfiguration annotations in Spring Boot?
Even though both @SpringBootApplication and @EnableAutoConfiguration can be used to enable the auto-configuration feature of Spring Boot, there is a subtle difference between them. The @SpringBootApplication does much more than what @EnableAutoConfiguration  does.
It's actually a combination of three annotations: @Configuration, which is used in Java-based configuration on Spring framework, @ComponentScan to enable component scanning of components you write like @Controller classes, and @EnableAutoConfgiuration itself, which is used to allow for auto-configuration in Spring Boot application .
It's not mandatory to put @SpringBootApplication to create a Spring Boot application, you can still use @Configuration and @EnableAutoConfiguration individually . If you are using @EnableAutoConfiguration classes, then you can selectively exclude certain classes from auto-configuration by using exclude as shown below:
@EnableAutoConfiguration(exclude=DataSourceAutoConfiguration.class)
You should annotate the Main class or Bootstrap class with the @SpringBootApplication; this will allow you to run as a JAR with embedded web server Tomcat.
===============================

Spring DevTools


We are using Spring Boot Dev Tools to avoid restarting tomcat server multiple times while testing the application. 
spring-boot-devtools module includes an embedded LiveReload server that is used to trigger a browser refresh when a resource is changed.
________________________________________
Using spring-boot-devtools it allows automatic start, this process is also automated. Whenever files change in the classpath, applications using spring-boot-devtools will cause the application to restart. The benefit of this feature is the time required to verify the changes made is considerably reduced.
________________________________________
Spring-boot does a lot of auto-configurations, including enabling caching by default to improve performance. One such example is caching of templates used by template engines, e.g. thymeleaf. But during development, it's more important to see the changes as quickly as possible. The default behavior of caching can be disabled for thymeleaf using the property spring.thymeleaf.cache=false in the application.properties file. We do not need to do this manually, introducing this spring-boot-devtools does this automatically for us. ________________________________________
It dynamically compile & run our code when we regress or add any data

Stereotype Annotations


Stereotype annotations are a set of specialized annotations that are used to indicate the role or purpose of a particular component within the application. These annotations are used to mark a class, interface, or method as belonging to a particular category or stereotype, such as a service, repository, or component.
@Component is a generic stereotype for any Spring-managed component.
@Service annotates classes at the service layer.
@Repository annotates classes at the persistence layer, which will act as a database repository
@controller :
The @Controller annotation marks a class as a controller component, which is responsible for handling incoming requests and returning appropriate responses.
@controller Vs @RestController
@Controller is used to declare common web controllers which can return HTTP response but @RestController is used to create controllers for REST APIs which can return JSON.

@Controller@RestController
To mark class as a controller class Used in restful web services
It's a old controllerIt's a new COntroller[Spring 4]
On applying this,what are the methods present in class they return a new object On applying this in the class,it will return the domain object instead of new object.

Controller : They do stuff like - dispatching,forwarding,calling service methods etc.
Service : Holds business logic ,calculations etc.
Repository : It is the DAO[Data Access Object] layer that access the database directly.

@service


The @Service annotation is used to mark a class as a service component, which typically performs business logic or other logic-related tasks within the application. This annotation is often used in conjunction with the @Component annotation to indicate that the class is both a service and a component.
Stereotype annotations are @Component , @Service , @Repository and @Controller annotations. These annotations are used for auto-detection of beans using @ComponentScan and component-scan . The Spring stereotype @Component is parent stereotype
@Component : Beans are auto-detectable by spring container.We don't need to define bean in configuration file,it will be automatically detected at runtime by spring.
@Controller : Classes annotated with this are intended to receive a request from client side using the value of @RequestMapping.
@Service : Are intended to manipulate the data that we receive from client or fetch from the database.
@Repository : Are intended to connect with database.It can also be considered as a DAO layer.If any manipulation is required,data should be sent back to @service layer.

@repository


The @Repository annotation marks a class as a repository component, which is responsible for managing the persistence of data within the application. This annotation is often used in conjunction with the @Component annotation to indicate that the class is both a repository and a component.
@Repository annotation is used to indicate that the class provides the mechanism for storage, retrieval, search, update and delete operation on objects.a repository allows you to populate data in memory that comes from the database in the form of the domain entities. Once the entities are in memory, they can be changed and then persisted back to the database through transactions

Controller layer -> uses -> Service layer
Service layer -> uses ->Repository layer
Repository layer -> uses -> Underlying Database

@Component


The @Component annotation is the most general-purpose stereotype annotation and is used to mark any class as a component that can be managed by the Spring Framework.
With @Component , @Repository , @Service and @Controller annotations in place and automatic component scanning enabled, Spring will automatically import the beans into the container and inject them to dependencies.
@Component Vs @Bean :
The @Bean annotation is a method-level annotation, whereas @Component is a class-level annotation. The @Component annotation doesn't need to be used with the @Configuration annotation, whereas the @Bean annotation has to be used within a class annotated with @Configuration .

@ResponseBody


The @ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.
The @ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object. When you use the @ResponseBody annotation on a method, Spring converts the return value and writes it to the HTTP response automatically. Each method in the Controller class must be annotated with @ResponseBody.
@ResponseBody annotation tells the Spring framework to write the method's return type to the HTTP response body.ndicates a method return value should be bound to the web response body

@value annotation


@Value annotation is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation.
the @Value annotation can be used to inject values from a property file. To do so, first, create a properties file containing the values you want to inject. Then, you can use the @Value annotation to inject these values into your Java class attributes.
@Value. The annotation @Value is used to automatically assign a value from multiple environment such as spring environment, system environment, property files, bean objects, default value etc.
Eg ....
@Value("Yawin")
private String name; //name has yasin as default value.
@Value("25")
private int age;
@DateTimeFormat(pattern = "MM-dd-yyyy")
@Value("06-21-2003")
private Date dateOfBirth;
@Value("#{null}" // default value as null
private String name;
@Value with Properties files ->
Application. Properties -
source.file.name=test.txt
@Value with reading a property from application.properties 
@Value("${source.file.name}")
private String sourceFileName;
default value 80 is assigned in the variable servicePort.
When no such configuration is written inside application.properties.
@Value("${service.port:80}")
private String servicePort;

Actuator


It uses HTTP endpoints to expose operational information about any running application. The main benefit of using this library is that we get health and monitoring metrics from production-ready applications.
To enable Spring Boot actuator endpoints to your Spring Boot application, we need to add the Spring Boot Starter actuator dependency in our build configuration file.
Actuator use to access current state of a running application in a prod environment. These states r shown by different metrics like - app uptime , processor, memory. use this to monitor & get health checks of a production-ready application.
Maven users can add the below dependency in your pom.xml file.
dependency>
groupId>org.springframework.boot/groupId>
artifactId>spring-boot-starter-actuator/artifactId>
/dependency>
Some important Spring Boot Actuator endpoints are given below. You can enter them in your web browser and monitor your application behavior.
ENDPOINTSUSAGE
/metricsTo view the application metrics such as memory used, memory free, threads, classes, system uptime etc.
/envTo view the list of Environment variables used in the application.
/beansTo view the Spring beans and its types, scopes and dependency.
/healthTo view the application health
/infoTo view the information about the Spring Boot application.
/traceTo view the list of Traces of your Rest endpoints.

Spring MVC


MVC
Model - It represents the data that is displayed over the web url.It is the model of data that we r putting on the web page.
View - It is the actual html syntax that decide how to view/display the data.Thymeleaf,Jsp technologies r use to make the data visible as view.
Controller - is the main handler that handles the web request. Controller assembles the model content & merge that with the view to render the final output.
Avoid using business logic in the Controller class ->
When we hit a url , the request passes to the controller & than controller picks the data from the model class and than send it over the web.This requires extra process or burden for the controller to see what business logic is implemented. Hence , Write all the logic part inside the service layer which can later be invoked by the controller.
_____________
Spring MVC - takes the MVC concept & combines It with the servlet.
≈=========
Servlet is a web component that is deployed on the server to create a dynamic web page. used to create a web application.5
_____________
Spring MVC is a Java framework that is used to develop web applications. It is built on a Model-View-Controller (MVC) pattern and possesses all the basic features of a spring framework, such as Dependency Injection,
Inversion of Control.
Spring MVC Advantage :
Spring MVC architecture easily lets its users configure according to their specific needs. This is especially something that you won’t find in Spring boot, which mainly relies on auto-configuration.
MVCs are mainly used to allow easy testing
With the help of Spring MVC, you no longer need to worry about writing utility code since the Spring MVC architecture allows it to handle HTTP responses and requests much more easily.

Spring boot Vs Spring MVC -
Spring boot can actually save up a lot of time and reduce the wastage of efforts while creating applications. Spring MVC, on the other hand, is particularly beneficial when it comes to developing modular applications since it promotes separation of concerns.

Rest Template


Spring RestTemplate is a synchronous REST client performing HTTP requests using a simple template-style API. Rest Template is used to create applications that consume RESTful Web Services. You can use the exchange() method to consume the web services for all HTTP methods. The code given below shows how to create Bean for Rest Template to auto wiring the Rest Template object.
Spring RestTemplate class is part of spring-web , introduced in Spring 3. We can use RestTemplate to test HTTP based restful web services, it doesn't support HTTPS protocol. RestTemplate class provides overloaded methods for different HTTP methods, such as GET, POST, PUT, DELETE etc
If we want to connect 2 different spring application together we can achieve this using RestTemplate class
Rest Template altrnative
RestTemplate : It consumes the Rest based web services. It's a client to perform Http request.It is a higher-order API since it performs HTTP requests by using an HTTP client library like the JDK HttpURLConnection, Apache HttpClient, and others. As of Spring Framework 5, Spring introduced a new HTTP client called WebClient.it is an alternative HTTP client to RestTemplate. WebClient is part of Spring WebFlux and is intended to replace the classic RestTemplate. Compared to RestTemplate , WebClient has a more functional feel and is fully reactive.


While doing rest call from the program using RestTemplate class , we hard code the url as an argument inside the rest template method definition but by using service registry we can generalized this url's host name & port without any need to hardcode it.

UUID


UUID is 36 characters long unique number. Present in java.util package. randomUUID() method randomly generate the new UUID. UUID.randomUUID() will auto generate the id.
A UUID – that's short for Universally Unique IDentifier, alphanumeric string that can be used to identify information
UUID Advantages
UUID values are unique across databases, tables, and servers. This allows you to merge rows from multiple databases or distribute databases across multiple servers. UUID values don't give out information about your data. Therefore it's safe to use in a URL.

Configuration Metadata


Configuration metadata tells the container that if you got POJO of 2 classes please create bean of them and inject those bean in the required class.So,if i want to fetch data of 1 class into another ,we are able to do it in 3 ways -
Using XML based file
Using annotation
Using Java based configuration

Advantages of XML based and Java based configuration
If using these , than all our bean definition,scope definition ,dependency injection mechanism everything remains in 1 file and hence it is good from performance perspective.Hence,Performance will be high,readablity will be high.
Advantage of Annotation Based
As soon as we create a POJO ,we give our annotation based configuration metadata.So, it reduces our time.
Disadvantage of Annotation Based
Performance & readablity is low because if i have multiple packages than container has to go in each package to see every number of package annotated with component and service or not.So, container has to go in each and every package and scan.Hence ,component scanning reduces the performance .So, for a big application , this process is time-taking. .

Spring IOC Container


IOC is a design principle and is helpful in object creation.Instead of programmer ,controlling flow of program external sources like - spring framework takes control of it.DI[Dependency Injection] is also a design principle and it implements IOC principles.
A Spring IoC container manages one or more beans. These beans are created with the configuration metadata that you supply to the container.
Spring have the IoC container which carry the Bag of Bean ; creation maintain and deletion are the responsibilities of Spring Container. We can put the bean in to Spring by Wiring and Auto Wiring.
Wiring :
mean we manually configure it into the XML file .
"Auto Wiring" mean we put the annotations in the Java file then Spring automatically scan the root-context where java configuration file, make it and put into the bag of Spring.
The IoC container is responsible to instantiate, configure and assemble the objects. The IoC container gets informations from the XML file and works accordingly. The main tasks performed by IoC container are:
to instantiate the application class
to configure the object
to assemble the dependencies between the objects
There are two types of IoC containers. They are:

BeanFactory
ApplicationContext

Bean


Bean - Java Bean is a simple java helper class, used to transfer data between classes or applications.We must declare Java Bean as a public class. It never acts as a main class
Java Beans are classes that encapsulate many objects into a single object (the bean). Spring beans are classes in which Instead of instantiating a class (using new), you get an instance of the class as a bean wired in the respective class . Beans are not  classes, but objects as instances of classes.

Spring Bean: is an object, which is created, managed and destroyed in Spring Container. We can inject an object into the Spring container through the metadata(either xml or annotation), which is called inversion of control. Bean is a POJO(Plain Old Java Object), which is managed by the spring container We wire the beans in a way, so that we do not have to take care of the instantiating or evaluate any dependency on the bean. Bean Advantage :
Any class can be called as bean in Spring if it is defined either in the spring xml file or defined by using annotation. Key advantage of making any class as spring bean is that, its entire life cycle is managed by Spring container and it helps us to achieve decoupling.

Container


It is the core of the spring framework.The container will create the objects, wire them together,configure them and manage their complete life-cycle.

The Spring container is at the core of the Spring Framework. The container will create the objects, wire them together, configure them, and manage their complete life cycle from creation till destruction. The Spring container uses DI(Dependency Injection) to manage the components that make up an application.
The container gets its instructions on what objects to instantiate, configure, and assemble by reading the configuration metadata provided. The configuration metadata can be represented either by XML, Java annotations, or Java code. The Spring IoC container makes use of Java POJO classes and configuration metadata to produce a fully configured and executable system or application.
General Container Type -
Spring BeanFactory ContainerSpring ApplicationContext Container
This is the simplest container providing the basic support for DI and is defined by the org.springframework.beans.factory.BeanFactory interface. The BeanFactory and related interfaces, such as BeanFactoryAware, InitializingBean, DisposableBean, are still present in Spring for the purpose of backward compatibility with a large number of third-party frameworks that integrate with Spring. This container adds more enterprise-specific functionality such as the ability to resolve textual messages from a properties file and the ability to publish application events to interested event listeners. This container is defined by the org.springframework.context.ApplicationContext interface.

Container type based on classes -
Core container(Bean Factory) -> Implementation class is XMLBeanFactory.
Advance container(ApplicationContext) -> Implemenation class is classpathXMLApplicationContext and many more.
Web container
Core ContainerAdvance COntainer
Slow loading processAdvance loading process
We can load only 1 configuration file Can load multiple spring application configuration file
Doesn't support AnnotationSupports Annotation
It is simplest container providing basic support for DI This container adds more enterprise specific functionality like- to resolve textual message from a file,public application events to interested event listener.

AOP


Aspect-Oriented Programming (AOP) is one of the key elements of the Spring Framework. Spring AOP module has some useful features like it provides interceptors to intercept an application. For example, when a method is executed in a system, then you can also add extra features and functionality before or after the method has been executed.

AOP Usecase :
provide declarative enterprise services, especially as a replacement for EJB declarative services.
The most important such service is declarative transaction management. allow users to implement custom aspects, complementing their use of OOP with AOP.

Common Spring Exception

NoSuchBeanDefinition :
The most common cause of this exception is simply trying to inject a bean that isn't defined.
For example, BeanB is wiring in a collaborator, BeanA:
@Component
public class BeanA {
@Autowired
private BeanB dependency;
//...
}
Now if the dependency BeanB is not defined in the Spring Context, the bootstrap process will fail with the no such bean definition exception:

NoUniqueBeanDefinition


When you do have more than one bean of a given type, you need to tell Spring which bean you wish it to use for dependency injection. If you fail to do so, Spring will throw a NoUniqueBeanDefinitionException exception, which means there’s more than one bean which would fulfill the requirement.
How to resolve such exception :
There are two simple ways you can resolve the NoUniqueBeanDefinitionException exception in Spring.
@Primary annotation, which will tell Spring when all other things are equal to select the primary bean over other instances of that type for the autowire requirement.
@Qualifier annotation. Through the use of this annotation, you can give Spring hints about the name of the bean you want to use. By default, the reference name of the bean is typically the lower case class name.Through this we can eliminate the issue of which bean needs to be injected.

BeanInstantiation Exception


This Exception thrown when instantiation of a bean failed.
The spring boot exception BeanInstantiationException: Failed to instantiate happens when the bean can’t instantiate when auto-wiring in another bean. If the bean is instantiated in another bean, the bean either throws an exception or fails to create an object. BeanInstantiationException will be fired on runtime when the bean is created and dynamically loaded in the application.

The exception BeanInstantiationException: Failed to instantiate will be threw mostly for three reasons.
If the bean implementation class is not available or has not been added to the java class path, the bean could not be loaded into the spring boot context. If the bean is instantiated using the abstract class of the bean, the abstract class does not locate the implemented class in the spring boot context.

Application Context Exception


ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean.
It simply tells us that there is no configured ServletWebServerFactory bean in the ApplicationContext. Cause for such Exception -
1.The error comes up mainly when Spring Boot fails to start the ServletWebServerApplicationContext Because the ServletWebServerApplicationContext uses a contained ServletWebServerFactory bean to bootstrap itself. Spring Boot provides the SpringApplication.run method to bootstrap Spring applications.
2.The SpringApplication class will attempt to create the right ApplicationContext for us, depending on whether we are developing a web application or not.Another cause would be missing the @SpringBootApplication annotation in the Spring Boot entry point class.

Path param Vs Request param


@RequestParam and @PathVariable can both be used to extract values from the request URI, but they are a bit different.
@RequestParam is used to get the request parameters from URL, also known as query parameters, while @PathVariable extracts values from URI.
For example, if the incoming HTTP request to retrieve a book on topic "Java" is http://localhost:8080/shop/order/1001/receipts?date=12-05-2017, then you can use the @RequestParam annotation to retrieve the query parameter date and you can use @PathVariable to extract the orderId i.e. "1001" as shown below:
@RequestMapping(value="/order/{orderId}/receipts", method = RequestMethod.GET)
public List listUsersInvoices( @PathVariable("orderId") int order,
@RequestParam(value = "date", required = false) Date dateOrNull) {
...
}
Spring controllers that can handle request parameters and path variables.
1. Using @RequestParam to get Query parameters
In a Spring MVC application, you can use the @RequestParam annotation to accept query parameters in Controller's handler methods.
For examples, suppose you have a web application that returns details of orders and trades, and you have the following URLs:
http://localhost:8080/eportal/orders?id=1001
To accept the query parameters in the above URLs, you can use the following code in the Spring MVC controller:
@RequestMapping("/orders")
public String showOrderDetails(@RequestParam("id") String orderId, Model model){
model.addAttribute("orderId", orderId);
return "orderDetails";
}
2. Using @PathVariable annotation to extract values from URI
You can use Spring MVC's @PathVaraible annotation to extract any value which is embedded in the URL itself. Spring calls it a URI template, where @PathVariable is used to obtain some placeholders from the URI itself.
URL: http://localhost:8080/book/9783827319333
Now, to extract the value of ISBN number from the URI in your Spring MVC Controller's handler method, you can use @PathVariable annotation as shown in the following code:
@RequestMapping(value="/book/{ISBN}", method= RequestMethod.GET)
public String showBookDetails(@PathVariable("ISBN") String id,
Model model){
model.addAttribute("ISBN", id);
return "bookDetails";
}
Path param vs request params :
Path params we use with get .It comes as a part of url.
Request params we send in body
_____
.@ResponseBody is a Spring annotation which binds a method return value to the web response body .The @ResponseBody annotation is used at method level or method return type level.
______
The @RequestParam is used to extract query parameters while @PathVariable is used to extract data right from the URI.

Eager Loading Vs Lazy Loading


Lazy loading delays the initialization of a resource, eager loading initializes or loads a resource as soon as the code is executed. Eager loading also involves pre-loading related entities referenced by a resource.
Eager Loading is a design pattern in which data initialization occurs on the spot.
Lazy Loading is a design pattern that we use to defer initialization of an object as long as it's possible.

Eager loading is the opposite of lazy loading. With eager loading, a web page loads all of its content immediately. Eager loading lets the browser store all contents of the web page in its cache, which can be helpful if visitors return to the page. However, this method can be slow to load larger web page files.
Does Lazy Loading improve speed and performance
Lazy loading images and video reduces initial page load time, initial page weight, and system resource usage, all of which have positive impacts on performance.
Lazy -Loading Advantage
Lazy loading improves the performance of data fetching and significantly reduces the memory footprint. When Hibernate initializes the data object, actually it creates a reference (of the data) to the data object and doesn't load the data as such.
Lazy loading Disadvantage
Users may request resources faster than expected: For instance, if a user scrolls quickly down a page, they might have to wait for the images to load. This could negatively impact user experience.

Eager initialisation Vs Lazy initialisation


Lazy initialization is technique were we restrict the object creation until its created by application code. This saves the memory from redundant objects which some time may be very big/heavy. In other way eager initialization creates the object in advance and just after starting the application or module.

Memory and resource utilization plays crucial role in current enterprise era developers always need to take care of resource creation, utilization and it's cleanness on correct time to make application more effective and optimized. Object creation is also part of it. Lazy initialization is technique were we restrict the object creation until its created by application code. This saves the memory from redundant objects which some time may be very big/heavy. In other way eager initialization creates the object in advance and just after starting the application or module. This is helpful in case the object is mandatory and in all the cases functional. This way application provides the ready to use object and saves execution time at time of actual request.
So, as per above details, both lazy and eager loading/initialization plays critical role and should be used as per the requirement and behavior of application.

JPA repository Vs Crud repository


CrudRepository is a Spring Data interface for generic CRUD operations on a repository of a specific type. It provides several methods out of the box for interacting with a database.
CrudRepository provides CRUD functions. PagingAndSortingRepository provides methods to do pagination and sort records. JpaRepository provides JPA related methods such as flushing the persistence context and delete records in a batch.
CrudRepository does not provide any method for pagination and sorting. JpaRepository extends PagingAndSortingRepository. It provides all the methods for implementing the pagination. It works as a marker interface.

JpaRepository extends PagingAndSortingRepository which in turn extends CrudRepository.
Their main functions are:
CrudRepository mainly provides CRUD functions.
PagingAndSortingRepository provides methods to do pagination and sorting records.
JpaRepository provides some JPA-related methods such as flushing the persistence context and deleting records in a batch.
Because of the inheritance mentioned above, JpaRepository will have all the functions of CrudRepository and PagingAndSortingRepository. So if you don't need the repository to have the functions provided by JpaRepository and PagingAndSortingRepository , use CrudRepository.

Spring MVC Vs Spring Boot

Spring MVC allows us to create a web app.Any app which we develop with spring boot inherently use spring MVC as creation of web based app is the basis of MVC framework. Making an app solely using spring MVC requires lot of initial configuration.
Like to add view resolver , adding web jars.Configuring dispatched servlets etc. To develop a typical web app spring mvc alone can't work. It requires some other framework with it to work.like - core Framework, jackson,logging Framework, embedded server etc which requires additional effort. With spring boot , all these things becomes pretty easy as it provides embedded Servlet container, auto-configuration feature, addition of starter dependencies of different -2 Framework. Hence, to simplify the view without using so many configuration spring boot is came.
A spring mvc app is packaged & deployed as a war file using Servlet container such as tomcat. Spring boot doesn't need a war deployment. It uses embedded server so, the app is packaged as a jar . No xml configuration with spring boot as incase of spring mvc.Configuration with spring boot is really seamless.

Spring MVC is a part of the Spring framework that helps in handling HTTP requests and responses. On the other hand, Spring Boot is the extension of the Spring framework and provides a faster way to build applications. Spring MVC allows you to easily build fully functional Java Web applications with the help of kits ready-made components, and
Spring Boot helps rapidly build production-ready applications. Spring Boot framework is also capable of embedding HTTP servers like Tomcat. In situations where more flexibility is required, it is advised to use Spring MVC as it allows you to make configurations according to your specific needs rather than spring boot. Unlike Spring MVC, spring boot is a tool that injects your functionality into the program without the laborious task of doing it individually.

Spring MVC Vs Spring Webflux

Spring WebFlux is used to create fully asynchronous and non-blocking application built on event-loop execution model Spring mvc is based on servlet stack framework& spring webflux (it is servlet agnostic ie... can & cannot use servlet) used reactive stack framework. And Nowadays, reactive programming r gaining popularity due to it's asynchronous & non blocking nature.
Spring MVC is a traditional, synchronous web framework, while Spring WebFlux is a reactive, non-blocking web framework. This means that in a Spring MVC application, each request is handled by a single thread, while in a Spring WebFlux application, multiple threads can be used to handle requests.
Each request to Spring MVC uses a single thread, which can be blocking, whereas Spring Webflux does not block a thread during execution

Spring WebFlux Disadvantage :
One of the biggest disadvantages of the Webflux is that it is reactive, a fact that brings a lot of additional complexity and needs time to be thoroughly understood and appreciated.

Spring 3 Vs Spring 4


Spring 4 introduced @RestController which is combination of @Controller + @ResponseBody. So when using @RestController, you do not need to use @ResponseBody. It's optional. Till Spring 3, we would have been using @Controller annotation and in that case it was important to use @ResponseBody annotation as well.
new changes that are introduced as part of the Spring 4 which is not part of Spring 3:

RestController annotation
JSR-335 Lambda expressions
JSR-310 Date-Time value types for Spring data binding and formatting.
JSR-343 JMS 2.0.
JSR-338 JPA 2.1.
JSR-349 Bean Validation 1.1.
JSR-236 Java EE 7 Enterprise Concurrency support.
JSR-356 Spring’s WebSocket endpoint mode.
Configuring and implementing Spring style application using Groovy 2. Also they specify that first class support for the Groovy applications.
Removed Deprecated Packages and Methods
Java 8 Support
Java EE 6 and 7 or above is now considered the baseline for Spring Framework 4
Groovy Bean Definition DSL, read more about this API.
Core Container Improvements
General Web Improvements
WebSocket, SockJS, and STOMP Messaging
Testing Improvements
Spring 3.x which introduced lot of new features like:
Spring MVC Test Framework
Asynchronous MVC processing on Servlet 3.0
custom @Bean definition annotations in @Configuration classes
@Autowired and @Value to be used as meta-annotations
Concurrency refinements across the framework
loading WebApplicationContexts in the TestContext framework
JCache 0.5 (JSR-107)

Spring-boot-starter-web Vs Spring-boot-starter-tomcat


Spring Boot Starter Web Vs Spring Boot Starter Tomcat
Starter web mainly used for building web applications that include RESTful applications using Spring MVC. It uses Tomcat as the default embedded container .
single spring-boot-starter-web dependency can pull in all dependencies related to web development.
The spring-boot-starter-web auto-configures
Dispatcher Servlet
Error Page
Embedded servlet container
Web JARs for managing the static dependency
________
Spring Boot Starter Web is used for building RESTful applications using Spring MVC.Spring Boot Starter Tomcat is the default embedded container for Spring Boot Starter Web. We cannot exclude starter web dependency while using web services.We can exclude starter tomcat dependency when we want to use another embedded container.

Starter Dependencies


A starter dependency is nothing but a special dependency that aggregates commonly used dependencies for a particular feature. For example, suppose you are building a Spring based web application. For this, you will need to add dependencies for spring-core, spring-web, jackson, etc.
The spring-boot-starter-parent is a special starter that provides useful Maven defaults. It also provides a dependency-management section so that you can omit version tags for “blessed” dependencies. Spring-boot-starter-tomcat -
It is the most popular servlet container which was used to deploy java applications, by default spring boot is built the standalone application which was running on the desktop.
Starter for using Tomcat as the embedded servlet container. Default servlet container starter used by spring-boot-starter-web.

spring-boot-starter-jetty


To use Jetty in your Spring Boot application, we can use the spring-boot-starter-jetty starter. Spring Boot provides Tomcat and Jetty dependencies bundled together as separate starters to help make this process as easy as possible. Add the spring-boot-starter-jetty starter in your pom. xml file.
Jetty is user friendly and has a better interface than Tomcat. Better for handling simultaneous users compared to Tomcat. The conceptual weight of the framework is less, very fast, and thin. Small memory trace to work speedily.

spring-boot-starter-undertow


The undertow subsystem allows you to configure the web server and servlet container settings. It implements the Java Servlet 3.1 Specification as well as websockets and supports HTTP Upgrade and using high performance non-blocking handlers in servlet deployments.
Spring boot provides an easy way to configure undertow server as like jetty. undertow is web server written in Java and manage and sponsored by JBoss. Main advantages of undertow are HTTP/2 Support, HTTP Upgrade Support, Web Socket Support, Servlet 4.0, Embeddable, Flexible.
To use Undertow instead of tomcat, first, you need to exclude the spring-boot-starter-tomcat from spring-boot-starter-web. Then you should add the undertow starter (since Tomcat is the default web server).
Difference between Tomcat and UnderTow
Apache Tomcat powers numerous large-scale, mission-critical web applications across a diverse range of industries and organizations. What is Undertow? A flexible performant web server written in java. It is a flexible performant web server written in java, providing both blocking and non-blocking API's based on NIO.

Spring-boot-starter-web

For servlet stack applications, the spring-boot-starter-web includes Tomcat by including spring-boot-starter-tomcat , but you can use spring-boot-starter-jetty or spring-boot-starter-undertow instead.

spring-boot-starter-actuator


Spring Boot Actuator is a sub-project of the Spring Boot Framework. It includes a number of additional features that help us to monitor and manage the Spring.
To enable Spring Boot actuator endpoints to your Spring Boot application, we need to add the Spring Boot Starter actuator dependency in our build configuration file. Maven users can add the below dependency in your pom. xml file.
It uses HTTP endpoints to expose operational information about any running application. The main benefit of using this library is that we get health and monitoring metrics from production-ready applications.
Actuator endpoints let you monitor and interact with your application. Spring Boot includes a number of built-in endpoints and lets you add your own. For example, the health endpoint provides basic application health information. Each individual endpoint can be enabled or disabled.

spring-boot-starter-data-jpa


Spring Boot Starter Data JPA. Spring Boot provides spring-boot-starter-data-jpa dependency to connect Spring application with relational database efficiently.
Spring Data JPA focuses on using JPA to store data in a relational database. Its most compelling feature is the ability to create repository implementations automatically, at runtime, from a repository interface.
Difference between JPA and Hibernate
JPA uses EntityManager interface to create/read/delete operation and maintains the persistence context. Hibernate uses Session interface to create/read/delete operation and maintains the persistence context. JPA uses JPQL (Java Persistence Query Language) as Object Oriented Query language for database operations.

spring-boot-starter-jdbc


Spring Boot JDBC provides starter and libraries for connecting an application with JDBC. In Spring Boot JDBC, the database related beans such as DataSource, JdbcTemplate, and NamedParameterJdbcTemplate auto-configures and created during the startup. We can autowire these classes if we want to use it.

One of the key differences between Spring Data JPA and Spring Data JDBC –
there is no transaction context in Spring Data JDBC. The framework does not track entity state, does not fetch associations lazily on first access, and does not save changes when a transaction is closed

spring-boot-starter-ldap


Why LDAP is used for ?
The most common LDAP use case is providing a central location for accessing and managing directory services. LDAP enables organizations to store, manage, and secure information about the organization, its users, and assets–like usernames and passwords.
LDAP is used as a central repository for user information. Applications then connect to this repository for user searches and authentication. Spring Boot offers auto-configuration for any compliant LDAP server as well as support for the embedded in-memory LDAP server.


Spring Data LDAP provides similar abstraction which provides the automatic implementation of Repository interfaces that include basic CRUD operation for LDAP directories. Also, Spring Data Framework can create a custom query based on a method name.

spring-boot-starter-test


The spring-boot-starter-test “Starter” (in the test scope ) contains the following provided libraries: JUnit 4: The de-facto standard for unit testing Java applications. Spring Test & Spring Boot Test: Utilities and integration test support for Spring Boot applications. AssertJ: A fluent assertion library.
The @SpringBootTest annotation is a powerful annotation in Spring framework which is used to load entire application context for Spring Boot application and create integration test. It allows you to test your application in the same way as it runs on production.

With Spring Boot, we need to add starter to our project, for testing we only need to add the spring-boot-starter-test dependency.
dependency>
groupId>org.springframework.boot/groupId>
artifactId>spring-boot-starter-test/artifactId>
version>2.2.2.RELEASE/version>
scope>test/scope>
/dependency>
It pulls all the dependencies related to test. After adding it, we can build up a simple unit test.

spring-boot-starter-thymeleaf


Thymeleaf is a Java-based library used to create a web application.It is a Java template engine for processing and creating HTML, XML, JavaScript, CSS and text. It provides a good support for serving a XHTML/HTML5 in web applications.
Thymeleaf is use at the backend.It is a template generator. HTML pages are generated by Spring on the backend server.
Thymeleaf Advantage -
Its high-performance parsed template cache reduces I/O to the minimum. It can be used as a template engine framework if required. It supports several template modes: XML, XHTML, and HTML5. It allows developers to extend and create custom dialect.

Starter for building MVC web applications using Thymeleaf views
dependency>
groupId>org.springframework.boot/groupId>
artifactId>spring-boot-starter-thymeleaf/artifactId>
version>2.1.8.RELEASE/version>
/dependency>

spring-boot-starter-data-cassandra


Starter for using Cassandra distributed database and Spring Data Cassandra Reactive
dependency>
groupId>org.springframework.boot/groupId>
artifactId>spring-boot-starter-data-cassandra-reactive/artifactId>
version>2.4.3/version>
/dependency>

spring-boot-starter-data-mongodb

Starter for using Cassandra distributed database and Spring Data Mongo DB Reactive
dependency>
groupId>org.springframework.boot/groupId>
artifactId>spring-boot-starter-data-mongodb-reactive/artifactId>
version>2.4.3/version>
/dependency>

spring-boot-starter-data-redis


Redis(Remote Directory Server ) cache in spring
Redis cache helps us by minimizing the number of network calls while accessing the data from DB. Uses caching technique to make DB calls faster .apart from Cache, Redis can also be used as a database and Message Broker. Redis is an open source (BSD licensed) in-memory remote data structure store.Redis db can br used as an :

In- memory db - As an in memory db ,it stores data in memory rather than disk.Hence,is quicker compare to disk access. And also eliminates the seek/latency time in retrieving data. it do not persists the data in disk.
As an In-Memory database, We will get some empty memory to perform database operations. Moreover, it acts as No-SQL database and there are No Tables, No Sequences, No Joins concept.
Cache - Redis is normally used as a cache to store repeatedly accessed data in memory As a cache manager, it reduces network calls and improves the performance of an application.
Message broker - Pub/Sub[google] , is a messaging system in Redis where the senders send binary string messages to the receivers.
In Redis context, senders are named as Publishers and receivers are named as Subscribers.
This is how Redis acts as a message broker.
___________________________________
When we perform a DB retrieve operation via an Application, the Redis Cache stores the result in it’s cache. Further, when we perform the same retrieve operation, it returns the result from the cache itself and ignore the second call to database. To use it is , we need to download a Redis Server in our system. 
To access this use this artifacts -
artifactId>spring-boot-starter-data-redis/artifactIdb
_________________
Redis - remote Dictionary Server
Used because it is fast, scalable,
single threaded(so 1 action at a time)
Redis is an in-memory database and uses primary memory for data storage.
As a result, whenever you restart the server/computer in which Redis is running, there is a risk of losing data. As mitigation for this risk, Redis has the  Persistence feature. This involves writing the data into the disk in a compact format.
Appropriate memory usage in Redis ->
In Redis, storage happens in memory. For it's optimum use , Instead of getting new RAM, it is advisable to use appropriate data structures and optimize them.
Technique for memory optimization ->
Short structures
Sharded structures - Sharding is a technique of breaking down data into multiple parts called shards to increase data storage and for load balancing.
Packing data into string
________________________________________

spring-boot-starter-webflux


Spring WebFlux is the alternative to Spring MVC module. Spring WebFlux is used to create fully asynchronous and non-blocking application built on event-loop execution model.

with the spring-boot-starter-webflux dependency, which pulls in all other required dependencies:
spring-boot and spring-boot-starter for basic Spring Boot application setup
spring-webflux framework
reactor-core that we need for reactive streams and also reactor-netty
dependency>
groupId>org.springframework.boot/groupId>
artifactId>spring-boot-starter-webflux/artifactId>
version>2.6.4/version>
/dependency>
The latest spring-boot-starter-webflux can be downloaded from Maven Central. Default server for spring-boot-starter-webflux
Spring WebFlux is a part of the Spring framework and provides reactive programming support for web applications. If we're using WebFlux in a Spring Boot application, Spring Boot automatically configures Reactor Netty as the default server

spring-boot-starter-log4j2


Spring Boot also supports either Log4j or Log4j 2 for logging configuration, but only if one of them is on the classpath. If you are using the starter poms for assembling dependencies that means you have to exclude Logback and then include your chosen version of Log4j instead.
Spring boot starter projects enable quick development boot applications. Starter projects has a default dependency on spring-boot-starter-logging. This library configures logback as the default logging implementation.
spring boot starter Log4j2 vulnerability
The vulnerability has been reported with CVE-2021-44228 against the log4j-core jar and has been fixed in Log4J v2. 15.0. Spring Boot users are only affected by this vulnerability if they have switched the default logging system to Log4J2.
Open pom.xml file and add the following snippet to the dependencies section -
Exclude Spring Boot's Default Logging
dependency>
groupId>org.springframework.boot/groupId>
artifactId>spring-boot-starter/artifactId>
exclusions>
exclusion>
groupId>org.springframework.boot/groupId>
artifactId>spring-boot-starter-logging/artifactId>
/exclusion>
/exclusions>
/dependency>
Add Log4j2 Dependency
dependency>
groupId>org.springframework.boot/groupId>
artifactId>spring-boot-starter-log4j2/artifactId>
/dependency>

@bean Vs @component


@bean : The @Bean annotation returns an object that spring registers as a bean in application context .
This is the method level annotation.To declare a bean ,simply annotate the method with @Bean.When java config encounters such a method , it will execute the method and register the return value as a bean.

@Configuration
public class AppConfig{
@Bean
public TransferService trans(){
return nre TransferImpl();
}
}

@Component@Bean
It auto-detects and configure the bean using class path scanning. It explicitly declares a sinlge bean rather than letting spring do it automatically
It need not to be used with @COnfiguration annotation This has to be used within the class which is annotated with @Configuration
Auto-wiring is done to inject the bean Configuration bean is than call from a class using applicationContext.getBean method.


@Component : Indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and class path scanning.
@Component is a class-level annotation, but @Bean is at the method level, so @Component is only an option when a class's source code is editable. @Bean can always be used, but it's more verbose. @Component is compatible with Spring's auto-detection, but @Bean requires manual class instantiation.
@Component Preferable for component scanning and automatic wiring.
When should you use @Bean?
Sometimes automatic configuration is not an option. When? Let's imagine that you want to wire components from 3rd-party libraries (you don't have the source code so you can't annotate its classes with @Component), so automatic configuration is not possible.
The @Bean annotation returns an object that spring should register as bean in application context. The body of the method bears the logic responsible for creating the instance.