Spring Boot Notes 1
Spring Boot Notes 1
• Spring Boot is an open source Java-based framework used to create a micro Service.
• It is developed by Pivotal Team and is used to build stand-alone and production ready
spring applications.
• Spring Boot provides a good platform for Java developers to develop a stand-alone and
production-grade spring application that you can just run.
• You can get started with minimum configurations without the need for an entire Spring
configuration setup.
• It can build standalone application.
• It can create production ready package.
• It has embedded Tomcat Server.
• It is convention over configuration model.
Introduction to Microservices
• Micro Service is an architecture that allows the developers to develop and deploy
services independently.
• Each service running has its own process, and this achieves the lightweight model to
support business applications.
• Microservices are an architectural approach where a single application is composed of
many small, loosely coupled, and independently deployable components or services.
• Microservices are autonomous: Each microservice can be developed, deployed, and
operated independently without affecting other services.
• In a monolithic architecture, all processes run as a single service, tightly coupled.
• Microservices break down an application into independent components, each running
as a separate service.
Advantages of Microservices
• Simple scalability
• Compatible with Containers
• Minimum configuration
• Lesser production time
• Easy to understand and develop spring applications
• Increases productivity
• Reduces the development time
Spring Framework is a widely used Java Spring Boot Framework is widely used to
EE framework for building applications. develop REST APIs.
To test the Spring project, we need to set Spring Boot offers embedded server such
up the server explicitly. as Jetty and Tomcat, etc.
Spring Boot is a module of Spring for Spring MVC is a model view controller-
packaging the Spring-based application based web framework under the Spring
with sensible defaults. framework.
Handling dependency management is a difficult task for big projects. Spring Boot
resolves this problem by providing a set of dependencies for developers
convenience.
For example, if you want to use Spring and JPA for database access, it is sufficient
if you include spring-boot-starter-data-jpa dependency in your project.
Note that all Spring Boot starters follow the same naming pattern spring-boot-
starter- *, where * indicates that it is a type of the application.
Examples
Look at the following Spring Boot starters explained below for a better
understanding −
Spring Boot Starter Security dependency is used for Spring Security. Its code is
shown below −
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Spring Boot Starter web dependency is used to write a Rest Endpoints. Its code
is shown below −
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
1.https://www.springboottutorial.com/spring-boot-starter-projects
2.https://www.tutorialspoint.com/spring_boot/spring_boot_starters.htm
Project in Starter Project
Screenshot
The entry point of the spring boot application is the class contains
@SpringBootApplication annotation and the main method.
Spring Boot automatically scans all the components included in the project by using
@ComponentScan annotation.
The entry point of the Spring Boot Application is the class contains
@SpringBootApplication annotation. This class should have the main method to
run the Spring Boot application. @SpringBootApplication annotation includes
Auto- Configuration, Component Scan, and Spring Boot Configuration.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
@EnableAutoConfiguration
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
Spring Boot application scans all the beans and package declarations when the
application initializes. You need to add the @ComponentScan annotation for your
class file to scan your components added in your project.
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan;
@ComponentScan
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
We also need application.properties file to mention any configuration related details.
A web service is a set of open protocols and standards that allow data to be exchanged
between different applications or systems.
Suppose, we have an Application A which create a request to access the web services. The
web services offer a list of services. The web service process the request and sends the
response to the Application A. The input to a web service is called a request, and the
output from a web service is called response. The web services can be called from
different platforms.
There are two popular formats for request and response XML and JSON.
In this way, regardless of the configuration of the machine, both can interact on the
common grounds of the data format.
XML is a popular form as request and response in web services. Consider the following
XML code. The code shows that user has requested to access the Data Structure Course.
JSON(JavaScript Object Notation) format
JSON Format: JSON is a readable format for structuring data. It is used for transiting data
between server and web application.
Today, JSON is the universal standard of data exchange. It is found in every area of
programming, including front-end and server-side development, systems, middleware,
and databases.
Suppose, we have an Application A which create a request to access the web services. The
web services offer a list of services. The web service process the request and sends the
response to Application A. The input to a web service is called a request, and the output
from a web service is called a response. The web services can be called from different
platforms.
Now a question arises, how does the Application A know the format of Request and
Response?
The answer to this question is "Service Definition." Every web service offers a service
definition. It is like a table of contents for every web service that an application offers.
• Request/ Response format: Defines the request format made by consumer and
response format made by web service.
• Request Structure: Defines the structure of the request made by the application.
• Response Structure: Defines the structure of response returned by the web service.
• Endpoint: Defines where the services are available.
XML-based
A web service uses XML at information representation and record transportation layer. Using
XML, there is no need of networking, operating system, or platform binding. Web offering
based application is highly interoperable application at their middle level.
Loosely Coupled
A web service supports loosely coupled connections between systems. It communicates
by passing XML message to each other via a web API. Web API adds a layer of abstraction to
Web Service is the set of rules or guidelines which enable communication among different
applications via the World wide web (.i.e. the internet).
Before web service, there were other technologies but some of them have dependencies
such as EJB (enterprise java bean) which allows applications to communicate only if the
applications are working on Java, these dependencies make communication difficult. These
dependencies are removed by web services.
While working, some applications might need to use the service or functionality offered by
other applications. To use that service or functionality applications need to communicate
with each other.
Let us consider an example of a restaurant, when you visit the restaurant and ask for the
food(a service) then the waiter will be taking the order to the kitchen and serve you prepared
food from the kitchen. Here the waiter is like the web service which allows you(.i.e. client) to
communicate with the kitchen(.i.e. application).
The figure below shows another example of how the ICICI bank ATM used the service
provided by SBI bank to access the database of the customer which cannot be accessed by
the ICICI bank ATM directly.
How do web services work?
Web services use the request-response method to communicate among applications. For
any communication, we need a medium and a common format that can be understood by
everyone, in the case of web services medium is the internet and the common format is the
XML (Extensible Markup Language) format as every programming language can understand
the XML markup language.
1. SOAP web services: SOAP stands for Simple Object Access Protocol. These protocols
are based on XML which is a lightweight data exchange language. These protocols are
independent of language and can be run on any platform.
SOAP supports both stateful and stateless operations. Stateful means that the server keeps
track of the information received from the client on each request. While Stateless means
that each request contains enough information about the state of the client and thus server
does not need to bother about saving the state of the client thus increasing the speed of
communication.
Many companies such as IBM, Microsoft are producing an implementation of SOAP into their
systems.
2. RESTful web services: It stands for Representational State Transfer. They are also
language and platform-independent and are faster in comparison to SOAP. Nowadays
RESTful web services are more used than SOAP. They treat the data as resources. RESTful
web services return data in JSON format or XML format. These web services create the
object and send the state of the object in response to the client’s requests, that’s why known
as Representational State Transfer.
RESTful API
REST stands for REpresentational State Transfer. It is developed by Roy Thomas Fielding
who also developed HTTP.
The main goal of RESTful web services is to make web services more effective.
RESTful web services try to define services using the different concepts that are already
present in HTTP.
We can build REST services with both XML and JSON. JSON is more popular format with
REST.
When we request a resource, we provide the representation of the resource. The important
methods of HTTP are:
SOAP API
REST defines an architectural approach whereas SOAP poses a restriction on the format of
the XML. XML transfer data between the service provider and service consumer.
FOR EXAMPLE :
REST (Representational State Transfer) and SOAP (Simple Object Access Protocol) are the
most common methods for communication. These services enable the web to
communicate with the servers with HTTP protocol. REST is architectural style that works
over HTTP for communication while SOAP is a protocol with strict standards and is helpful
for complex system operations.
REST API
REST or Representational State Transfer is an architectural style for building the web
services. It is mostly used for lightweight and stateless communication. It uses simple
HTTP methods like GET, POST, PUT, and DELETE to perform operations on the data
resources.
Key Concepts
• Rest uses URI i.e. Uniform Resource Identifier and assume everything as a resource
• It do not store any past data, requests and do independent operations
• It relies on HTTP method to request any type of operation on the resource.
• Rest usually works with JSON and XML data formats.
SOAP API
SOAP or Simple Object Access Protocol is a messaging protocol. Is allows to exchange the
structure information without any platform. Soap uses the XML data fromat due to the
complexity. It is mostly used for complex systems with strict standards ensuring security
and reliability.
Key Concepts
• SOAP is a protocol as it has some strict rules for data fomat and communication.
• It manages the recods and maintain the state between the requests.
• SOAP relies on SSL and WS-Securiy for secured communication.
• SOAP works with the XML data format to handle the complex data.
• Resources
Resources are just consistence mappings from an identifier [such as a URL path ] to some
set of views on server-side state.
URI example :
http://localhost:9999/restapi/books/{id}
http://localhost:9999/restapi/books
REST technology is generally preferred to the more robust Simple Object Access Protocol
(SOAP) technology because REST uses less bandwidth, simple and flexible making it more
suitable for internet usage. It’s used to fetch or give some information from a web service.
All communication done via REST API uses only HTTP request.
Working: A request is sent from client to server in the form of a web URL as HTTP GET or
POST or PUT or DELETE request. After that, a response comes back from the server in the
form of a resource which can be anything like HTML, XML, Image, or JSON. But now JSON is
the most popular format being used in Web Services.
In HTTP there are five methods that are commonly used in a REST-based Architecture i.e.,
POST, GET, PUT, PATCH, and DELETE. These correspond to create, read, update, and
delete (or CRUD) operations respectively. There are other methods which are less
frequently used like OPTIONS and HEAD.
• GET: The HTTP GET method is used to read (or retrieve) a representation of a
resource. In the safe path, GET returns a representation in XML or JSON and an
HTTP response code of 200 (OK). In an error case, it most often returns a 404 (NOT
FOUND) or 400 (BAD REQUEST).
• POST: The POST verb is most often utilized to create new resources. It’s used to
create subordinate resources. That is, subordinate to some other (e.g. parent)
resource. On successful creation, return HTTP status 201, returning a Location
header with a link to the newly created resource with the 201 HTTP status.
• PUT: It is used for updating the capabilities. However, PUT can also be used to
create a resource in the case where the resource ID is chosen by the client instead
of by the server. In other words, if the PUT is to a URI that contains the value of a
non-existent resource ID. On successful update, return 200 (or 204 if not returning
any content in the body) from a PUT. If using PUT for create, return HTTP status 201
on successful creation.
• PATCH: It is used to modify capabilities. The PATCH request only needs to contain
the changes to the resource, not the complete resource. This resembles PUT, but
the body contains a set of instructions describing how a resource currently residing
on the server should be modified to produce a new version. This means that the
PATCH body should not just be a modified part of the resource, but in some kind of
patch language like JSON Patch or XML Patch.
• DELETE: It is used to delete a resource identified by a URI. On successful deletion,
return HTTP status 200 (OK) along with a response body.
Now we will see how request and response work for different HTTP methods. Let’s assume
we have an API( https://www.geeksforgeeks.org/api/students ) for all students data of gfg.
Request
GET:/api/students
Request
POST:/api/students
{“name”:”Raj”}
Request
PUT or PATCH:/api/students/1
{“name”:”Raj”}
Request
DELETE:/api/students/1
1.https://www.boltic.io/blog/web-api-vs-rest-api
2.https://positiwise.com/blog/web-api-vs-rest-api
Make sure that the version of Spring Boot is 3.3.4. Otherwise if not available ,kindly make
the changes in the pom.xml file. Kindly refer the screenshot below.
3.Also you need to add the following dependencies:
4.You can keep adding the dependencies according to the requirements by searching for
the dependency and clicking in explore.
5.You can copy paste the dependencies into the pom.xml file of your project
8.After you import the file, you might see a project architecture similar to the screenshot
attached below:
9. Once you import the file , you might experience some errors in the folder such as this:
10. You can resolve it with the help of the following steps:
-->Go to the pom.xml(Project Object Model) and replace all the http with https.
Screenshot is as follows:
-->Right click on the Project, navigate to Maven and then select update Project. As
mentioned in the screenshot select the project and select the option for FORCE UPDATE
OF SNAPSHOT OR RELEASES:
11.Check and verify the contents of application.properties in the resources folder of the
same.
The settings done till now is common for all kinds of SpringBoot Projects , post this you can
do settings as per the specific requirements of the Project.
12.Now create a Controller Package and create a respective class for the same.
13. You can try out the respective sample code in order to implement a rest API Endpoint
@RestController- The @RestController annotation in Spring Boot is used to create RESTful
web services that return JSON or XML data:
Used to create controllers for REST APIs that return data, such as JSON or XML, rather than
a view . Maps request data to the defined request handler method , and converts the
response body to JSON or XML . Combines the functionality of the @Controller and
@ResponseBody annotations, so methods in a @RestController class do not need to be
annotated with @ResponseBody to return data to the client.
14. In this controller , we are calling a URL Mapping which will give me the ArrayList data
that is returning a list of strings.
15.In order to implement Swagger API that is to include order to include a Request
Dashboard by including the following dependency in pom.xml file.
16.The URL to accessed for Swagger API URL once you run the project is
http://localhost:PortNumber/swagger-ui/index.html
Kindly do a maven rebuild if you the link is giving you some issue.
17.Execute the Project by doing a right click on the main application file and running it as
Maven Build(Command-> spring-boot:run).
18.Then you can open the Swagger URL and test the request.
Indicates that your application is running.
@ResponseBody –It is used for binding a return value from a resource method to a web
response body. This is done by the use of HTTP message converters. This conversion
is done by looking at the content-type value in the HTTP request header.
Make sure that the version of Spring Boot is 3.3.4. Otherwise if not available ,kindly make
the changes in the pom.xml file. Kindly refer the screenshot below.
3.Also, you need to add the following dependencies:
4.You can keep adding the dependencies according to the requirements by searching for
the dependency and clicking in explore.
5.You can copy paste the dependencies into the pom.xml file of your project
8.Add a Student Bean class under the main application package with the following code to
implement the bean class:
Controller annotation-It is used to determine that it can return a response as a model and
view as well whereas the RestController annotation can return the response in the form of
XML,HTML,HTTP etc.
RestController- RestController is used for making restful web services with the help of the
@RestController annotation. This annotation is used at the class level and allows the class
to handle the requests made by the client.
Make sure you include both the parametrized and non parametrized constructor in the
Student bean file.
10.After that right click on the project and run as Maven Build. You can mention spring-
boot:run as a part of Goals .
11. After the successful run, kindly hit the URL as http://localhost/getstudent in order to
demonstrate the get method without a DB in a sample format .Output is as follows:
12.As a part of Swagger API, you can hit the following URL
http://localhost:8080/swagger-ui/index.html
13. Now in out next example we will try to return a list of Students as a part of GetMapping.
You can add the following Code as a part of StudentController file.
You will see automatic changes in the console of the application because of Dev tool
dependency implementation.
14. After the successful run, kindly hit the URL as http://localhost/studentlist in order to
demonstrate the get method without a DB in a sample format. Output is as follows:
15. As a part of Swagger API, you can hit the following URL
Screenshot is as follow:
16.We can also implement GetMapping as of form of Path Variable or URL Based
arguments as shown in the code snippet below:
You can fill in the sample details and fetch it accordingly by clicking on execute button.
You can check the request URL and the corresponding response body afterwards. Refer
the screenshot:
Difference between pathVariable and requestparam-
PathVariable- The @PathVariable annotation is used to extract data from the URL
path. It allows you to define placeholders in your request mapping URL and bind those
placeholders to method parameters.
19. We can also implement Get Mapping in form of Request Parameter or URL Based
arguments as shown in the code snippet below:
20. As a part of Swagger API, you can hit the following URL
localhost:8080/students/query?id=4&firstName=TT&lastName=UU
21. We can also implement GetMapping in form of a method which takes up and returns
list of strings as shown in the code snippet below:
22. As a part of Swagger API, you can hit the following URL
http://localhost:8080/Stringaddquery?s=TCS,CTS,CAP,Adobe
which is a sample URL in order to demonstrate the get method without a DB in a sample
format.
Output is as follows:
24.In order to implement the Post Mapping ,we need to provide information in the form of
JSON which will be inserted into the Java Object using the method.
RequestBody annotation- @RequestBody is mainly used with CRUD Operations to read the
request body.
Here you can change the Status from OK 200 to CREATED 201 as well using Response
Status annotation.
25. As a part of Swagger API, you can hit the following URL
27. As a part of Swagger API, you can hit the following URL
29. As a part of Swagger API, you can hit the following URL
31. As a part of Swagger API, you can hit the following URL
Now this was all about creating the Endpoints. Now, we will see how to consume the
endpoints. This task is ideally done using RestTemplate Approach.
If you check the URL for both the URL, you will find the same content:
Configure JPA with SpringBoot
Spring Data JPA or JPA stands for Java Persistence API, so before looking into that, we
must know about ORM (Object Relation Mapping).
So ,Object relation mapping is simply the process of persisting any java object directly into
a database table. Usually, the name of the object being persisted becomes the name of
the table, and each field within that object becomes a column.
With the table setup, each row corresponds to a record in the application.
Hibernate is one example of ORM. In short, JPA is the interface while hibernate is the
implementation.
The java persistence API provides a specification for persisting, reading, and managing
data from your java object to your relational tables in the database.
JPA specifies the set of rules and guidelines for developing interfaces that follow
standards. Straight to the point: JPA is just guidelines to implement ORM and there is no
underlying code for the implementation. Spring Data JPA is part of the spring framework.
The goal of spring data repository abstraction is to significantly reduce the amount of
boilerplate code required to implement a data access layer for various persistence stores.
Spring Data JPA is not a JPA provider, it is a library/framework that adds an extra layer of
abstraction on the top of our JPA provider line Hibernate.
Syntax:
Where:
• T: Domain type that repository manages (Generally the Entity/Model class name)
• ID: Type of the id of the entity that repository manages (Generally the wrapper class
of your @Id that is created inside the Entity/Model class)
5.You can copy paste the dependencies into the pom.xml file of your project
8.After you import the file, you might see a project architecture similar to the screenshot
attached below:
9. Once you import the file , you might experience some errors in the folder such as this:
10. You can resolve it with the help of the following steps:
-->Go to the pom.xml(Project Object Model) and replace all the http with https.
Screenshot is as follows:
-->Go to the C Drive->Users->Your Employee ID Folder->Open .m2 folder which gets
created when you import the Folder into the Project Folder. After that you can check your
Employee ID and India Domain password accordingly. Make sure that the Settings file is
according to the sample shared with you. Kindly update the local Repository Path with your
own Repository File path in .m2 folder in your Employee ID Folder. Also update your
Username and Password in the same settings.xml file.
Screenshot is as follows:
-->Right click on the Project, navigate to Maven and then select update Project. As
mentioned in the screenshot select the project and select the option for FORCE UPDATE
OF SNAPSHOT OR RELEASES:
11.Import it to the Workspace using Existing Maven Project, change the Spring boot version
to 3.3.4 and do the Maven update project to get it up to date.
12.Add a WebApp Custom folder in the resources folder and add a JSP Page.
For example dependency could be like this, ignore/include the version part as per the
version compatibility.
Link- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper/10.1.30
13.Create a Controller class to handle the inputs given by the user under the same
package as of com.example.JSPDemo .This is going to access the JSP.
15. Next we are going to create our Entity File which will be the basis of Model.
16.Now Create a Java File named as EmpRepository which will be extending the class of
JpaRepository
Do a right click +CTRL on the JpaRepository , then you can see all the available functions
under JPA In-Built Library.
17.You can also login into the h2 Console on your browser with the help of the following
URL
https://localhost:8080/h2-console
You need to enter the credentials as per the application.properties file. You will find the
screen similar to the below screenshot.Test the connection once.
18.Upon connecting to the DB. You will find a screen similar to the one below:
19.Now you can Maven Build your application, you can try hitting the URL
https://localhost/8080/home
As home URL is mapped to home.jsp page so the below page will be loaded:
Upon filling the details, when we hit the submit button, then it will invoke /addemp URL
from controller, which will be saving the data into the DB as mentioned in the code
We can also fetch all the Data using Dao File inbuilt functions such as findAll for the
Datapoints to be displayed etc. You can check that in the Console.
Later you can go to the h2 console and run a Select query to check the data
As you can see, once we log out of the h2 console, we lost the old data because of it being
a in Memory Database.
API 1-
API 2-
There are many reasons why we use DTO's such as Instead of sending single entity as REST
API response to client, we can use DTO to combine and return multiple entities or multiple
attributes in one shot from server to client.
Project on DTO:
5.You can copy paste the dependencies into the pom.xml file of your project
8.After you import the file, you might see a project architecture similar to the screenshot
attached below:
9. Once you import the file , you might experience some errors in the folder such as this:
10. You can resolve it with the help of the following steps:
-->Go to the pom.xml(Project Object Model) and replace all the http with https.
Screenshot is as follows:
-->Go to the C Drive->Users->Your Employee ID Folder->Open .m2 folder which gets
created when you import the Folder into the Project Folder. After that you can check your
Employee ID and India Domain password accordingly. Make sure that the Settings file is
according to the sample shared with you. Kindly update the local Repository Path with your
own Repository File path in .m2 folder in your Employee ID Folder. Also update your
Username and Password in the same settings.xml file.
Screenshot is as follows:
-->Right click on the Project, navigate to Maven and then select update Project. As
mentioned in the screenshot select the project and select the option for FORCE UPDATE
OF SNAPSHOT OR RELEASES:
11.Check and verify the contents of application.properties in the resources folder of the
same.
The settings done till now is common for all kinds of Spring Boot Projects , post this you
can do settings as per the specific requirements of the Project. Because we are trying to
implement DTO, so we need to use the lombok dependency import which will be used to
include the annotations used for DTO.
Also do one last project setting by opening the properties of the project and enable the
Project Specific Settings under the Java Compiler tab.Please make sure , you import
lombok jar file which will be helpful for Entity Class annotation mapping
12. Create the Entity file in the SpringBoot application package:(Code is shown in the
package)
Now no need to getter and setter as we are using lombok for automatic generation of getter
and setter.
13. Now we will be writing the Repository file to implement JPA related functions.
14. Now we need to create the controller for endpoints. We are going to create a service
layer, controller, entity and a repository layer.
Now I will be using Dto in order to perform CRUD in the table not in the form of Post but in
the form of DTO Objects which are more secure and do not expose the information.
First the service class is created and then methods are implemented in the Post Service
Implementation.
Exception Handling
Exception handling in Spring Boot helps to deal with errors and exceptions present in APIs,
delivering a robust enterprise application. This article covers various ways in which
exceptions can be handled and how to return meaningful error responses to the client in a
Spring Boot Project. To create a user defined exception. For that we will create a class with
run time exception.
API 1-
API 2-
API 3-
API 4-
API 5-