Ebook Spring Boot
Ebook Spring Boot
This book will cover the topic of Spring Boot with REST APIs and Microservices.
For a better understanding of the content, it is important to have the knowledge.
Contacts
https://github.com/michellibrito
The provided input is a URL and does not contain any text to translate.
[email protected]
Spring Boot from REST API to Microservices
Summary
Introduction
2. Spring Platform
2.1. Spring Framework. 3
2.2. Inversion of Control. 5
2.3.Dependency Injection. 6
2.4.Core Container. 7
2.5.Beans. 8
2.6.Configuring Beans in Spring. 9
2.7.@Bean - Producer Methods........................................................................... 13
3.Spring Boot...............................................................................................................14
3.1.Starting a Spring Boot project. 15
3.2. IDE. 16
3.3. Project Structure. 18
4. REST API with Spring Boot.....................................................................................21
4.1.REST API and RESTful. 21
4.1.1 REST Architecture. 21
4.1.2.Types of Representations in REST. 22
4.1.3. Resources, Methods, and Returns. 23
4.1.4. Richardson Maturity Model. 23
4.2.Creating a REST API with Spring Boot. 26
4.2.1.Creating connection with database. 26
4.2.2.Creating the Model and the Repository. 26
4.2.3. Creating the Controller. 29
4.2.4. Implementing the GET ALL and GET ONE methods. 30
4.2.5.Implementing the POST, DELETE, and PUT methods .................................. 32
4.2.6. Inserting HATEOASS .............................................................................. 35
5. Microservices with Spring Boot..............................................................................39
5.1.Microservices Architecture...............................................................39
5.2.Communication between Microservices
5.3.Example of Microservices with Spring Boot.......................................................43
www.michellibrito.com 1
Spring Boot from REST API to Microservices
1.Introduction
Many people who are starting in the field of programming or are looking
migrating from technology or language asks if it is still worth it nowadays
to study and invest in the Java language. The answer to this question is that it is worth it.
Even though Java has been a widely used and robust language for a long time
it is still widely used mainly with the help of frameworks
and well-rounded and updated platforms that present information in a simpler way
standardized projects capable of boosting development effectively
more productive, as is the case with Spring.
So that the professional or beginner in the career has a foundation of the concepts and
necessary practices to work with these technologies, in this book will be
first approached the Spring platform with the main concepts for
use the Spring Framework and Spring Boot. Then, the
concepts and patterns of REST architecture and demonstrated in practice how to create one
REST API with Spring Boot following the main principles and constraints.
involving HTTP methods, resources, returns, HATEOAS among others.
www.michellibrito.com 2
Spring Boot From REST API to Microservices
2.Spring Platform
Spring Framework;
Spring Boot;
Spring Web;
Spring Security;
Spring Data;
Spring Batch;
Spring Cloud
others.
To view and know all the available projects on the Spring platform,
just access the Spring by Pivotal website and check the complete list through the link
Invalid request. Please provide text for translation..
The Spring Framework is the foundational project for the entire Spring ecosystem and is divided
in 7 groups:
www.michellibrito.com 3
Spring Boot From REST API to Microservices
Core Container;
Data Access/Integration;
Web;
Aspect Oriented Programming (AOP);
Instrumentation;
Messaging;
Test.
Within the Core Container group, there are the modules responsible for containing the
fundamental parts of the framework, such as basic and advanced classes, their
implementations and control of runtime definitions of
settings by annotations or XML files.
others.
All the modules mentioned above, except for the Test module, are built
about the Core Container of the Spring Framework, highlighted in the image below.
www.michellibrito.com 4
Spring Boot From REST API to Microservices
As the Spring Framework project has the Core Container module, where is it
implemented Inversion of Control that uses Dependency Injection, it
it becomes the essential project to start an application, being thus the base of
the entire Spring platform.
2.2.Control Inversion
www.michellibrito.com 5
Spring Boot From REST API to Microservices
For example, let's consider that we have two classes, A and B, where class A
it has a dependency on class B, since it uses a method from B. Thus,
class A would always have to create a new instance of class B so that
could use your method, as shown in the image below.
Figure 2: Example of an application that does not use IoC (Inversion of Control)
2.3.Dependency Injection
www.michellibrito.com 6
Spring Boot from REST API to Microservices
2.4.Core Container
When the application is run, the Core Container is started, the configurations
the predefined application settings in classes or XML files are read and the
necessary dependencies are defined and created through the IoC and destroyed
when they are no longer used. These dependencies are called beans.
within the context of Spring, which consist of objects that have their
managed lifecycle by the IoC container/ID of Spring. These steps
define the life cycle of a Container, as it can also be shown in
image below.
www.michellibrito.com 7
Spring Boot from REST API to Microservices
2.5.Beans
Like the container, a bean also has its lifecycle, which is started
created by the container, the dependencies of this bean are injected, the method
initialization is called and then, the bean is sent to the client, in
if the class that has this dependency, to be used and then
discarded.
www.michellibrito.com 8
Spring Boot From REST API to Microservices
It is necessary for Spring to know which classes of the application will be beans.
managed by him so that IoC/ID can then be applied. For this, there are two
ways to configure and determine these beans, using configurations in
XML files or through annotations.
In XML configuration, not very commonly used nowadays, it is necessary to define tags.
inside a main tag passing the class path, like this
Spring will know which classes it will manage for instance creation and injection.
of its dependencies.
www.michellibrito.com 9
Spring Boot from REST API to Microservices
@Component;
@Service;
@Controller;
@Repository.
www.michellibrito.com 10
Spring Boot From REST API to Microservices
Considering that the beans managed by Spring have already been defined
the next question is to understand how Spring will know where to inject the instances that
it will create with its dependencies. For that, it is necessary to create the points of
www.michellibrito.com 11
Spring Boot from REST API to Microservices
Singleton;
Prototype;
Request;
Session.
Thus, it is possible to determine if a bean will be of the singleton type, for example, or
thus, the container will create a single instance of this bean that will be used for
all requests of the instance.
If the bean is configured as a prototype, the container will create multiple instances.
one for each request. The bean with request scope will have a
instance created for each HTTP request and finally, the bean with scope
session will have its instance preserved and used by the requests while
end the session.
www.michellibrito.com 12
Spring Boot from REST API to Microservices
of injection and Spring will control it like any other bean within the
application.
www.michellibrito.com 13
Spring Boot from REST API to Microservices
3.Spring Boot
Starting an application from scratch using the Spring Framework can be somewhat
how laborious it is, as it is necessary to make several configurations in XML files
or configuration class, configure the Dispatcher Servlet, generate a war file,
deploy the application inside a Servlet Container, such as Tomcat,
to then be able to run the application and begin implementing the rules
of business.
When starting a Spring Boot project, just one dependency in the pom.xml file is enough.
www.michellibrito.com 14
Spring Boot from REST API to Microservices
In summary, Spring Boot is the sum of the Spring Framework with a server.
embedded minus the XML configurations and configuration classes.
To start a Spring Boot project takes only a few minutes, using the
Spring Initializr through the websiteURL does not contain translatable text.. Just define a few
initial settings such as the dependency manager to be used, the
language and version of the language, the version of Spring Boot, basic data of
project as Group and Artifact and finally, select the initial dependencies that
will make up the project. Thus, when clicking the Generate button, a project
compressed is made available. So, it is necessary to uncompress this project in
a specific directory on the machine and import it into the chosen IDE for the
development.
In the image below, it is possible to visualize the generation of a Spring Boot project.
www.michellibrito.com 15
Spring Boot from REST API to Microservices
3.2. IDE
There are several IDEs that can be used to develop Java projects with
Spring, among the most well-known are Eclipse, IntelliJ IDEA, Netbeans and the
STS (Spring Tool Suite 4), being the latter an IDE based on Eclipse
suitable for Spring projects, which will be used in the examples throughout this
book.
But for those who prefer to use an IDE like Visual Studio Code or Theia, it is
It is also possible to download and install the Spring Tool according to the best IDE.
preference. To download and install the Spring Tool for one of these
The IDEs mentioned above can be accessed through the Spring by Pivotal website.
link https://spring.io/tools.
www.michellibrito.com 16
Spring Boot From REST API to Microservices
The IDE STS 4 interface after being downloaded and installed can be viewed below,
being quite similar to Eclipse itself.
www.michellibrito.com 17
Spring Boot from REST API to Microservices
After unpacking the project created with Spring Initializr, it is necessary to import it.
into the chosen IDE, in this case, STS. The project structure
initially it can be observed in the image below.
www.michellibrito.com 18
Spring Boot from REST API to Microservices
Just with the steps mentioned earlier, it was already possible to create a
Spring Boot project and start the application using STS as the IDE. That's why the
Spring Boot has been widely used by companies because it drastically reduces
www.michellibrito.com 19
Spring Boot From REST API to Microservices
www.michellibrito.com 20
Spring Boot from REST API to Microservices
REST API is a client/server application that sends and receives data through
HTTP protocol using communication standards such as XML and JSON and
can be implemented in the desired language. An API is developed to
allow interoperability between applications, for example, considering two
systems, a desktop and another mobile, both can consume the same API
to build your interfaces, that is, the same API can be used by
different systems.
The REST architectural model is nothing more than a set of best practices for
that a certain application can be built and documented from a
standardized way, easy and that generates greater productivity for both the
developers in construction, how much for the consumption of this application by
other systems.
One of the creators of this architectural model was Roy Fielding, who defined in
your doctoral thesis six constraints, that is, rules that must be
mandatory requirements for an application to be considered RESTful.
www.michellibrito.com 21
Spring Boot From REST API to Microservices
The first constraint states that an application, in this case an API, must be
client/server in order to separate responsibilities. The second constraint
It says that this application should be stateless, that is, it should not store state in
server, so that each request the client sends to the server has
relevant and unique information for the answer, thus it does not depend on which server.
The third constraint defines that the application must have the capability to perform
cache to reduce data traffic between client and server. The fourth constraint
it says that the application must have a uniform interface, where its modeling must
have well-defined resources, present hypermedia, use them correctly
HTTP methods and return codes.
The definition of the fifth constraint states that the system must be built on
layers, that is, the ability to scale the application across multiple
servers. And finally, the last constraint says that the application must have the
ability to evolve without breaking it, that is, code on demand.
A REST API can use 2 communication standards, XML and JSON. The standard
XML is based on tags, being a bit heavier compared to the
JSON.
product
1
Samsung S10
3,500.00
</product>
www.michellibrito.com 22
Spring Boot From REST API to Microservices
{
“codigo”: 1,
Samsung S10
“valor”:3.500,00
}
/products
/products/1
The methods used in the construction of a REST API are the methods of
HTTP protocol. To obtain a certain resource for example, the following is used
GET method, the POST method to create a new resource, the PUT method to
update this created resource and the DELETE to delete such resource. There are others
HTTP methods that can be used, but the ones mentioned earlier are
the most common.
The returns are the codes and responses that the server returns to the client.
in the face of a request. The main ones are:
1XX - Information;
2XX - Success;
3XX - Redirection;
4XX - Client error;
5XX - Server error.
www.michellibrito.com 23
Spring Boot from REST API to Microservices
There are cases where it is necessary to follow a less robust approach to the
building an API and following all six constraints proposed by Roy
Fielding may become unfeasible. Thinking from this perspective, for more cases
simple, Leonard Richardson proposed a maturity model composed of
four levels and the API that reaches these four levels can indeed be considered
a RESTful API.
An API reaches level 0, also known as POX level, when it uses the
HTTP protocol only as a communication mechanism and not as
semantics of its verbs. When an API reaches level 1, it uses the
resources correctly, clearly defining each resource uniquely and
using nouns to represent objects.
In the example below, it is possible to visualize an API that follows all these levels.
uses the HTTP GET method semantically with a 200 OK response, has its
well-defined resource, such as /produtose/produtos/1, has HATEOAS
as the links showing the relationship with the other URIs present in the API, and
thus, this API can be considered RESTful.
www.michellibrito.com 24
Spring Boot from REST API to Microservices
Example 1:
Example 2:
www.michellibrito.com 25
Spring Boot from REST API to Microservices
Returning to the project that was created in chapter 3 of this book, it is necessary to
dependencies in the pom.xml file, Spring Data and the Postgres dependency,
As shown in the example below.
After adding these dependencies to the project, it is necessary to configure the database.
www.michellibrito.com 26
Spring Boot From REST API to Microservices
new directory called models and inside it, create a new class
ProductModel.class annotate it with @Entity to make it an entity in
bank and @Table to define the name of the table. It is also necessary to note the
ProductIDcom@Ide@GeneratedValue(strategy=GenerationType.AUTO)
so that the id is generated automatically in each persistence of Product
in the bank.
www.michellibrito.com 27
Spring Boot From REST API to Microservices
Now that the connection with the database is ready and the entity created, it is necessary to
www.michellibrito.com 28
Spring Boot from REST API to Microservices
to Spring that this will be a bean managed by it and as such interface has
As a goal, transactions with the database, the best stereotype to be
used in this case is @Repository.
The next step in building the REST API is to create the controller, where it will be
implemented the application's endpoints. In a new controllers directory it is
I need to create a new class ProductController and annotate it with
@RestController. This annotation is a specific stereotype for creating
REST endpoints and shows Spring that such class will be a managed bean by
he through IoC/ID. As the ProductRepository has already been created which is also
a bean, it is necessary to create an injection point within the controller so that the
Spring injects the dependencies of ProductRepository when necessary.
www.michellibrito.com 29
Spring Boot from REST API to Microservices
Now that the Controller is ready, it is possible to start implementing the methods
from the API, starting with the endpoints that return the product listing and a
determined product by passing its id. Remember that it is necessary to define it well
resource, use nouns and define the possible returns using the
ResponsityEntity and HttpStatus to build the complete response with the
return codes and the resources expected by the client, and finally make use of
semantic form the HTTP method, in this case the GET method.
The code below shows the details of the implementation of the HTTP GET methods
that return first through the URI/product listing of products
and through the URI/products/{id}, a specific product, if it exists
in the database.
www.michellibrito.com 30
Spring Boot from REST API to Microservices
Figure 30: Implementation of the GET ALL and GET ONE methods
To search for the product listing, the method findAll() is used which returns
List<ProdutoModel> is used to search for a specific product through the id, uses-
if the method findById(Long id) is called by passing the id as an argument to the method and
returning an Optional<ProdutoModel>.
In order to test these created methods, it was inserted into the database via SQL commands.
www.michellibrito.com 31
Spring Boot from REST API to Microservices
The next step is to implement the POST, DELETE, and PUT methods. To save
a new product through the HTTP POST method, the method save is used
entity) in JPA and if the persistence occurs correctly in the database,
the return must be CREATED(202).
www.michellibrito.com 32
Spring Boot from REST API to Microservices
To delete a product using the HTTP DELETE method, it is necessary to pass the
the ID of this product only and use the delete method of JPA delete(S entity).
The return if the deletion occurs correctly should be OK(200).
All the step-by-step described above can be seen in the code below.
www.michellibrito.com 33
Spring Boot from REST API to Microservices
www.michellibrito.com 34
Spring Boot From REST API to Microservices
www.michellibrito.com 35
Spring Boot from REST API to Microservices
that through its method add() the ProductModel class traces the link of the
and build it within the controller methods and then add it to each
product.
For this, the method linkTo() can be used, which will build a url of
according to the controller and the defined method, methodOn() maps the
The method for the call ewithSelfRel()ewithRel() creates a self
link according to the relationship.
Each link created must be inserted into the product through the method add(), like
www.michellibrito.com 36
Spring Boot From REST API to Microservices
Figure 39: Creating and adding the link to the product listing.
Figure 40: Creating and adding the link for a single product.
When sending a request to the server requesting the product listing, now
In addition to the attributes of ProductModel, the link that shows will also be returned.
Figure 41: Postman test of the GET ALL method with HATEOAS
www.michellibrito.com 37
Spring Boot from REST API to Microservices
And in the same way, when sending a request to the server requesting a
a specified product by id will return the link showing the path
complete for o access e return a product listing
http://localhost:8080/products, as can be seen in the image
below.
Figure 42: Postman test of the GET ONE method with HATEOAS
Now yes, with the insertion of HATEOAS in the application and the configurations made.
necessary, it can be said that the product API has reached level 3 of maturity
and can be considered a RESTful API.
www.michellibrito.com 38
Spring Boot From REST API to Microservices
5.1.Microservices Architecture
www.michellibrito.com 39
Spring Boot from REST API to Microservices
consider now that this same system was built using the architecture
of microservices, each of the functionalities of this application would be a micro
independent and specific service according to your responsibility within
of the system, each using its own database, how can it be
observed in the image below.
www.michellibrito.com 40
Spring Boot From REST API to Microservices
Scaling an application is a process that is much more flexible and customizable when
microservices are used because it is possible to scale only the most
accessed for example, causing the application to perform well
performance control. When it comes to a monolithic system, there is no way to
to make this control, it is necessary to scale the application as a whole since there is no
how to divide the most accessed and least accessed modules and so on,
there is no good performance control.
In microservices, the deployment may initially seem a bit more robust, already
that the application as a whole includes several services, each with a
specific deployment. However, cloud platforms provide several facilities for
this process, such as the use of pipelines that after
www.michellibrito.com 41
Spring Boot From REST API to Microservices
www.michellibrito.com 42
Spring Boot From REST API to Microservices
How the process of starting an application with Spring Boot has become something quite
The Spring Cloud project has several specific modules for various
features in a distributed system. Among them, Spring Cloud Netflix,
which has integration with various components of Netflix OSS, such as Eureka,
Zuul, Hystrix, among others, the Spring Cloud Consul which is a service of
discovery of microservices in architecture and Spring Cloud Stream, which
provides support for messaging such as RabbitMQ and Apache Kafka.
The complete list of all Spring Cloud modules can be viewed at this
linkUnable to access the content of the link provided..
specific and independent services, one for product control, another for
inventory control and one for centralizing the entries in the application and
authentication (Gateway).
www.michellibrito.com 43
Spring Boot from REST API to Microservices
www.michellibrito.com 44
Spring Boot from REST API to Microservices
Thus, when the inventory control service returns the information to the control
of products, it will complete its processing, complete the response and
return to the customer the product listing with stock details.
www.michellibrito.com 45
Spring Boot from REST API to Microservices
Acknowledgments
If you have made it this far, it means you now have a good foundation of the main
concepts and technologies to become a Java Web developer using
Spring to build REST APIs and microservices with Spring Boot.
I can always improve and bring richer and more accurate content.
in the next editions.
Thank you!
www.michellibrito.com 46