Spring Boot Framework
Spring Boot Framework
Day 1
What is Spring Boot Framework?
Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications. It’s a Java-based
framework.
It provides production-ready features such as metrics, health checks, and externalized configuration.
For web applications, spring boot provides in built web servers (tomcat).
Its goal is to make Java EE (Enterprise Edition) Spring Boot provides the RAD(Rapid Application
development easier, allowing developers to be more Development) feature to the Spring framework for
productive. faster application development.
Spring framework helps to create a loosely coupled Spring Boot helps to create a stand-alone
application. application.
In the Spring framework to test the Spring Project, Spring Boot offers built-in or embedded servers such
we need to set up the servers explicitly. as Tomcat and jetty.
Why we are using Spring Boot Framework?
The dependency injection approach is used in Spring Boot.
It simplifies integration with other Java frameworks like JPA/Hibernate ORM, Struts, etc.
Java 1.8
PostgreSQL
Spring Boot Framework
Day 2
Spring Boot Features :
Web Development
Spring Application
Properties Files
YAML Support
Logging
Security
Web Development :
we can easily create an HTTP application with built-in servers like Tomcat, Jetty, or Undertow.
Use the spring-boot-starter-web module to start and run your application quickly.
Spring Boot Application :
The Spring Boot Application class makes it easy to start a Spring application.
we can start the application from the main method using a static run() method.
Properties Files :
It is a superset of JSON.
Day 3
Spring Boot
Architecture
There are four layers in Spring Boot are as follows:
Presentation Layer
Business Layer
Persistence Layer
Database Layer
Presentation Layer:
The presentation layer handles the HTTP requests, translates the JSON parameter to an object,
authenticates the request, and transfers it to the business layer.
Business Layer:
It consists of service classes and uses services provided by data access layers.
Database Layer:
In the database layer, CRUD (create, retrieve, update, delete) operations are performed.
The architecture of Spring Boot is similar to Spring MVC, but there is no need for DAO and DAOImpl classes.
The request goes to the controller, which maps and handles it, calling the service logic if needed.
The service layer performs all business logic on the data, which is mapped to JPA with model classes.
Spring Boot Framework
Day 4
What is Spring MVC?
So, Spring MVC is an integrated version of the Spring framework and Model View Controller.
It has all the basic features of the core Spring framework like Dependency Injection and Inversion of Control.
The MVC pattern segregates the application’s different aspects (input logic, business logic, and UI logic) while
providing a loose coupling between these elements.
The Model contains the core data of the application. In general, they consist of POJO (Plain Old Java Object).
The View is responsible for rendering the model’s data, and it generates HTML output that the client’s browser
can interpret.
Spring MVC is built around the Dispatcher Template that handles the HTTP requests and responses.
How does Spring MVC Works?
It then passes the request to a specific controller by finding it using Handler Mapping depending on the URL
requested using @RequestMapping and @Controller annotations.
Spring MVC Controller executes the business logic and then returns a logical view name and model to
Dispatcher Servlet.
The Dispatcher Servlet finds the right view (like Excel, Freemarker, JSP) to use based on configured rules.
Spring Boot is another popular Java framework used for building applications.
It is an extended version of the Spring framework that helps to reduce the development time.
Presentation layer
Business layer
Persistence layer
Database layer
The workflow goes like:
This request goes to the controller, and the controller maps and handles it.
The request is passed on to the service layer where all the business logic is performed on the data that is
mapped to JPA with model classes.
Day 5
How to create Spring Boot Application
&
@Bean
public PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder(); //BCryptPasswordEncoder function
provided by the spring security
}
@SpringBootApplication
@Configuration: It allows us to register extra beans in the context or import additional configuration classes.
@Required: It applies to the bean setter method.
It indicates that the annotated bean must be populated at configuration time with the required property,
else it throws an exception BeanInitilizationException.
@Required
public void setCost(Integer cost)
{
this. cost = cost;
}
It is a class-level annotation.
@Component
public class Student
{
.......
}
@Autowired :
@Component
public class Customer
{
@Autowired
public Customer(Person person)
{
this.person=person;
}
}
@Controller: The @Controller is a class-level annotation.
The @Controller annotation is a special type of @Component that is used to handle web requests and show
web pages.
@Controller
@RequestMapping("books")
public class BooksController
{
@RequestMapping(value = "/
{name}", method = RequestMethod.GET)
public Employee getBooksByName()
{
return booksTemplate;
}
}
@Service:
It is also used at the class level. It tells the Spring that the class contains the business logic.
package com.java;
@Service
public class TestService
{
public void service1()
{
//business code
}
@Repository:
The repository is a DAOs (Data Access Object) that access the database directly.
package com.java;
@Repository
public class TestRepository
{
public void delete()
{
//persistence code
}
}
@RequestMapping: It is used to map web requests.
It has many optional elements like consumes, header, method, name, params, path, produces, and value.
@Controller
public class BooksController
{
@RequestMapping("/computer-science/
books")
public String getAllBooks(Model model)
{
//application code
return "bookList";
}
@GetMapping: It maps the HTTP GET requests on the specific handler method. It is used to create a web
service endpoint that fetches It is used instead of using: @RequestMapping(method = RequestMethod.GET)
@PostMapping: It maps the HTTP POST requests on the specific handler method. It is used to create a web
service endpoint that creates It is used instead of using: @RequestMapping(method = RequestMethod.POST)
@PutMapping: It maps the HTTP PUT requests on the specific handler method. It is used to create a web
service endpoint that creates or updates It is used instead of using: @RequestMapping(method =
RequestMethod.PUT)
@DeleteMapping:
@RequestBody:
@PathVariable: It is used to extract the values from the URI. It is most suitable for the RESTful web service,
where the URL contains a path variable. We can define multiple @PathVariable in a method.
@RestController:
It can be considered as a combination of @Controller and @ResponseBody annotations.
The @RestController annotation is itself annotated with the @ResponseBody annotation.
It eliminates the need for annotating each method with @ResponseBody.
Spring Boot Framework
Day 6
Spring Boot Application Properties:
Spring Boot Framework comes with a built-in mechanism for application configuration using a file
called application.properties.
Spring Boot provides various properties that can be configured in the application.properties file.
The properties have default values. We can set a property(s) for the Spring Boot application.
#configuring port
server.port = 8081
YAML Properties File
Spring Boot provides another file to configure the properties is called yml file.
The Yaml file works because the Snake YAML jar is present in the classpath.
we can also use the application.yml file, but the Yml file should be present in the classpath.
Example of application.yml
spring:
application:
name: demo Application
server:
port: 8081
Spring Boot Property Categories:
• Templating Properties
• Core Properties • Server Properties
• Cache Properties • Security Properties
• Mail Properties • RSocket Properties
• JSON Properties • Actuator Properties
• Data Properties • DevTools Properties
• Transaction Properties • Testing Properties
• Data Migration Properties
• Integration Properties
• Web Properties
Spring Boot Framework
Day 7
Spring Boot Rest Concept
All kinds of applications can be designed using spring boot .
For web applications spring boot provides built in web servers (tomcat) .
Many things are auto configured . Each application can have its own server
Rest : - Representational state transfer Data received from the server depends on URL.
URL represents a particular page Whenever we change URL display to a new page.
JSON format
XML Format :
<employee>
</employee>
Multiple Object : [
]
How to create spring boot rest application project ?
spring web
dev tools
spring web is using means we are seeing the data in web pages based on URL
spring boot dev tools whenever makes the changes in code we can save the code that's it
automatic restart the code without using the stopping process
Day 8
Basic Spring Boot Application creation
Day 9
Spring Boot Data JPA
Create Entity classes with annotations
@Entity
@Id
@OneToOne
@OneToMany etc.,
swagger provides excellent UI for testing rest application spring boot does not provide swagger dependency
we need to add the swagger 2 and swagger dependencies
with swagger we can test rest application using any normal browser
url's :
http://localhost:port number/v2/api-docs
http://localhost:port number/swagger-ui-html
Day 10
Spring Boot exception
handling
@controllerAdvice :-
It is the class which handles all the Global exceptions in the application.
Day 11
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 Boot application.
It contains the actuator endpoints (the place where the resources live).
We can use HTTP and JMX endpoints to manage and monitor the Spring Boot application.
If we want to get production-ready features in an application, we should use the Spring Boot actuator.
Endpoints
Metrics
Audit
Endpoint:
The actuator endpoints allows us to monitor and interact with the application.
Spring Boot provides a number of built-in endpoints. We can also create our own endpoint.
Most of the application choose HTTP, where the Id of the endpoint, along with the prefix of /actuator, is
mapped to a URL.
For example, the /health endpoint provides the basic health information of an application.
Spring Boot Actuator provides dimensional metrics by integrating with the micrometer.
It is the instrumentation library powering the delivery of application metrics from Spring.
It provides vendor-neutral interfaces for timers, gauges, counters, distribution summaries, and long task
timers with a dimensional data model.
Audit:
Spring Boot provides a flexible audit framework that publishes events to an AuditEventRepository.
We can enable actuator by injecting the dependency spring-boot-starter-actuator in the pom.xml file.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
Id Usage Default
actuator It provides a hypermedia-based discovery page for the other endpoints. It True
requires Spring HATEOAS to be on the classpath.
auditevent It exposes audit events information for the current application. True
s
autoconfig It is used to display an auto-configuration report showing all auto- True
configuration candidates and the reason why they 'were' or 'were not'
applied.
beans It is used to display a complete list of all the Spring beans in your True
application.
configprop It is used to display a collated list of all @ConfigurationProperties. True
s
dump It is used to perform a thread dump. True
env It is used to expose properties from Spring's ConfigurableEnvironment. True
flyway It is used to show any Flyway database migrations that have been applied. True
health It is used to show application health information. False
info It is used to display arbitrary application info. False
loggers It is used to show and modify the configuration of loggers in the application. True
liquibase It is used to show any Liquibase database migrations that have been True
applied.
metrics It is used to show metrics information for the current application. True
mappings It is used to display a collated list of all @RequestMapping paths. True
shutdown It is used to allow the application to be gracefully shutdown. True
For Spring
Id Description Default MVC, the
docs It is used to display documentation,
including example requests and responses
False following
for the Actuator's endpoints. additional
heapdump It is used to return a GZip compressed
hprof heap dump file.
True endpoints are
jolokia It is used to expose JMX beans over HTTP True
used.
(when Jolokia is on the classpath).
Day 12
Application . properties file
v/s
Sequential format
Advantages :
Easy to modify
Disadvantages :
Repetition in keys
On increase in properties file, it becomes difficult to understand the keys and value.
Application . yml file : Disadvantages :
Yml stands for yet another markup language. Complex indentation formatting.
Hierarchical format.
Advantages :
Easy to modify.
No repetitions in keys.
Day 13
@Qualifier vs @Primary Annotations with
Examples
We can use @Qualifier and @Primary for the same bean.
Use @Qualifier to inject specific bean otherwise Spring injects bean by default which is annotated with
@Primary
Let us create an interface University,
University.java
package com.easy;
}
Now this university is implemented by couple of services, Alpha University and
Beta University
AlphaUniversity.java
package com.easy.service;
import com.easy.University;
import org.springframework.stereotype.Service;
@Service
public class AlphaUniversity implements University
{
@Override
public String display() {
}
BetaUniversity
package com.easy.service;
import com.easy.University;
import org.springframework.stereotype.Service;
@Service
public class BetaUniversity implements University {
@Override
public String display() {
}
Now let us have a controller,
UniversityController.java
package com.easy.controller;
import com.easy.University;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UniversityController {
@Autowired
private University university;
@GetMapping ("/university")
public String getUniversity() {
return university.display();
}
Now when we call “/univeristy” API which dependency will be actually called?
In the above example we have used both @Primary and @Qualifier together – Qualifier has taken
higher priority than @Primary.
Yes, Both annotations can be used together but only one can be executed at a time. (Qualifier first, if
qualifier not present it will execute primary)
Spring Boot Framework
Day 14
How to Use Profiles in Spring
Boot?
What Are Profiles?
Every enterprise application has many environments, like:
Each environment needs its own specific settings. For example, in DEV, we don't need to check database
consistency all the time.
But in Test and Acceptance, we do need to check it. These environments have specific configurations
called Profiles.
How to Use Profiles in Spring Boot?
Day 15
One-to-One Uni-directional
Mapping in Spring Boot
One-to-One Uni-directional Mapping
Table 1 Table 2
Where one entity has a reference to another entity, but the reverse is not true.
This is a unidirectional relationship because only one entity has knowledge of the other entity, and there is
no backward reference.
Example :
Employee has one Task reference task id, but the Task does not have a reference back to the Employee.
In JPA, the @GeneratedValue annotation is used to specify the primary key generation strategy for the @Id
field.
The strategy element of the @GeneratedValue annotation determines how the primary key values are
generated
@GeneratedValue(strategy = GenerationType.AUTO)
@GeneratedValue(strategy = GenerationType.IDENTITY)
Description: The persistence provider (e.g., Hibernate) will automatically choose the generation strategy
based on the underlying database.
Use Case: When you want the provider to decide the best generation strategy for the database.
GenerationType.IDENTITY
Description: The database generates the primary key values using an auto-increment column or a similar
mechanism.
Use Case: Suitable for databases that support auto-increment fields (e.g., MySQL, PostgreSQL).
GenerationType.SEQUENCE
Use Case: Suitable for databases that support sequence objects (e.g., Oracle, PostgreSQL).
GenerationType.TABLE
Description: Uses a database table to store and generate primary key values.
Use Case: Ideal for databases that do not support sequences or auto-increment columns.
It is more compatible across different databases.
Video link : https://youtu.be/JJwTNUPDSYE
The cascade attribute in the @OneToOne (or other relationship) annotation in JPA specifies the operations
that should be automatically propagated from the parent entity to the associated child entity.
Cascade Types :
CascadeType.PERSIST: When the parent entity is persisted, the related entity is also persisted.
CascadeType.MERGE: When the parent entity is merged, the related entity is also merged.
CascadeType.REMOVE: When the parent entity is removed, the related entity is also removed.
CascadeType.REFRESH: When the parent entity is refreshed, the related entity is also refreshed.
CascadeType.DETACH: When the parent entity is detached, the related entity is also detached.
CascadeType.ALL: All the above operations are cascaded to the related entity.
Spring Boot Framework
Day 16
One-to-One Bi-directional
Mapping in Spring Boot
One-to-One Bi-directional Mapping
Emp-Task
Table
EmpId TaskId
1 8
2 7
Video link : https://youtu.be/5ZZtdKghuiM
Spring Boot Framework
Day 17
One-to-Many Uni-
directional
Mapping in Spring Boot
One-to-Many Mapping
Day 18
Many-to-One Bi-
directional
Day 19
Many-to-Many Uni-
directional
1 2
1 3
4 5
6 7
6 8
Video link : https://youtu.be/7AA7-h7oLlM
Spring Boot Framework
Day 20
Many-to-Many Bi-
directional
Day 21
Project Deployment Using Tomcat Server
Setting up a Spring Boot Application
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application)
{
return application.sources(SpringBootWarDeploymentExampleApplication.class);
}
Update packaging JAR to WAR
Modify the final WAR file name by using the <finalName> tag to avoid including the version numbers.
<finalName>web-services</finalName>
Create a WAR file by using the following steps:
We found the WAR file inside the target folder with the same name as we have specified in the pom.xml file.
Deploy the WAR file to Tomcat
Copy the WAR file (web-services.war) and paste it inside the webapps folder of the Tomcat. In our case, the
location of the webapps folder is:
Now open the Command Prompt and type the following commands: