0% found this document useful (0 votes)
61 views50 pages

Ebook Spring Boot

1. The document presents a book about Spring Boot with REST APIs and microservices. It discusses the topics covered in the book and the skills necessary to understand it. 2. The author of the book is Michelli Brito, a fullstack Java developer with experience in Angular and Spring who creates IT content focused on Java and Spring. 3. The author's contact information is provided, including links to GitHub, YouTube, LinkedIn, and her website.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
61 views50 pages

Ebook Spring Boot

1. The document presents a book about Spring Boot with REST APIs and microservices. It discusses the topics covered in the book and the skills necessary to understand it. 2. The author of the book is Michelli Brito, a fullstack Java developer with experience in Angular and Spring who creates IT content focused on Java and Spring. 3. The author's contact information is provided, including links to GitHub, YouTube, LinkedIn, and her website.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

About the book

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.

about object-oriented programming, knowledge about the programming language


Java and also about HTML, CSS, and HTTP protocols.
All the code shown throughout this book is available on Github:
The provided text is a URL and cannot be translated..

About the author

Michelli Brito, Fullstack Java web developer with Angular working in


job market in São Paulo capital. Graduated in Engineering and Bachelor's
in Science and Technology from the Federal University of Alfenas, Unifal,
speaker and content creator on YouTube and blog about IT focused
mainly in the Java language and the Spring framework.

Contacts

https://github.com/michellibrito

The provided text is a URL and cannot be translated.

LinkedIn profile link provided, translation not applicable.

The provided input is a URL and does not contain any text to translate.

Unable to access the link provided.

[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.

Indeed, there is a great demand for these professionals in the market.


work, especially when it comes to Java for web using frameworks
like Spring for example and also using microservices architecture
with Spring Boot.

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.

The concept of microservices architecture will also be presented and the


communication between these services and how this type of architecture is nowadays
is being built using Spring Boot.

www.michellibrito.com 2
Spring Boot From REST API to Microservices

2.Spring Platform

Spring is a complete resource platform for building


Java applications, which came to simplify development in Java EE with
various modules that assist in building systems greatly reducing the
development time.

This platform features advanced resources that cover various areas of


an application with ready-to-use projects/modules, such as:

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..

With these projects, it is possible to build applications with functionalities


advanced and with much greater productivity, allowing for more focus on the rules
business and leave the low-level configurations to Spring.

2.1. Spring Framework

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.

The Data Access/Integration module is responsible for providing functionalities


for transactions with the database. The Web module contains the resources for
a web application, such as the implementation of MVC, REST Web Services, among others

others.

The AOP module provides the implementation for aspect-oriented programming.

aspects, the Instrumentation module provides instrumentation implementations


and finally the Messaging module contains implementation and support for
message-based programming.
The Test module has support for unit testing using JUnit and testing
of integration.

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

Figure 1: Spring Framework design highlighting the Core Container module

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.

Maybe this last paragraph has become a little difficult to understand.


of these terminologies. First, it is necessary to understand that every framework is
the application of an Inversion of Control. But what does this Inversion consist of?
Control after all?

2.2.Control Inversion

Inversion of Control (IoC) is a process in which a


object defines its dependencies without creating them. This object delegates the task of

build such dependencies for an IoC container.

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)

However, when using Inversion of Control, class A does not need to


to worry about creating an instance of B, as this responsibility becomes
the container of the Spring Framework that performs this Inversion of Control through
of Dependency Injection. And what would Dependency Injection be after all?

2.3.Dependency Injection

Dependency Injection consists of the way, that is, in the implementation


used by the Spring Framework to apply Inversion of Control when it is
necessary.

Dependency Injection defines which classes will be instantiated and in which


places will be injected when there is a need. Thus, it is enough that the class
Create an injection point of class B, for example, through the constructor, and when
if necessary, the Spring Framework container will create an instance

www.michellibrito.com 6
Spring Boot from REST API to Microservices

from class B so that class A can use the method m.metodoB(), as


show in the image below.

Figure 3: Example of Dependency Injection

2.4.Core Container

The Spring Framework uses Dependency Injection to apply Inversion


Control in the system and all this implementation is present in the Core
Container, where the configuration base of the Spring Framework is located.

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

Figure 4: Life Cycle with Container

2.5.Beans

As mentioned earlier, a bean is an object that is instantiated,


mounted and managed by a Spring container through Inversion of
Control (IoC) and Dependency Injection.

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.

In practice, using the previous example, when the container is instantiated it


create an instance of class B, call the constructor of class A to inject this
bean and then, class A uses this bean through deb.metodoB().This
the bean is then discarded when no longer used and such cycle can be
visualized in the image below.

www.michellibrito.com 8
Spring Boot From REST API to Microservices

Figure 5: Lifecycle of a Bean

2.6. Configuring Beans in Spring

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.

Figure 6: Bean configuration by XML

www.michellibrito.com 9
Spring Boot from REST API to Microservices

In annotation configuration, it is possible to use Spring stereotypes to


to determine in a more objective and specific way what type of bean each will be
class. There are four main types:

@Component;
@Service;
@Controller;
@Repository.

Thus, by annotating a certain class with one of these stereotypes, Spring


understand that such a class is a bean and will be managed by it. Below are
some examples of beans using annotation configuration.

Figure 7: Example of a Component type bean

Figure 8: Example of a Service type bean

Figure 9: Example of a Controller type bean

www.michellibrito.com 10
Spring Boot From REST API to Microservices

Figure 10: Example of a Repository type bean

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

injection, which consists of a way to deliver dependencies to the object


what is needed. The two most common types of injection points are the
constructors and setters, which can be viewed below.

Figure 11: Injection Point by the Constructor Method

Figure 12: Injection Point by the Setter method

www.michellibrito.com 11
Spring Boot from REST API to Microservices

Within Spring, there is another way to create injection points.


automatic, using the @Autowired annotation.

Figure 13: Injection Point using @Autowired

The lifecycle of a bean depends on its scope, which can be determined


In Spring through the @Scope annotation. The types of scopes in Spring
used for web are:

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

2.7.@Bean - Producer Methods

When it is necessary for an external class of the application to be a managed bean


through Spring, it is necessary to first create a producer method within the class
of the Spring configuration, which will return such an external class that will be

managed by the Spring container. And to configure this class as being


To create a bean, it is necessary to annotate the method with @Bean, thus it is possible to create points.

of injection and Spring will control it like any other bean within the
application.

Figure 14: Example of producer method with @Bean

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.

Spring Boot came as an extension of Spring, which is based on Spring.


Framework to start an application in a much simpler way,
reducing the complexity of initial configurations and the time to execute
a application and prepare it for the implementation of business rules.
It also comes with a built-in server that further simplifies this process.
start the application.

When starting a Spring Boot project, just one dependency in the pom.xml file is enough.

spring-boot-starter, so that it already brings internally all the


base dependencies of the Spring Framework, as can be seen in the image
below.

Figure 15: Initial dependencies of a Spring Boot project

www.michellibrito.com 14
Spring Boot from REST API to Microservices

Figure 16: Spring Core Container Modules - Framework Base

In summary, Spring Boot is the sum of the Spring Framework with a server.
embedded minus the XML configurations and configuration classes.

Figure 17: Spring Boot Summary

3.1.Starting a Spring Boot project

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.

through Spring Initializr, determining Maven as the management of


dependencies

www.michellibrito.com 15
Spring Boot from REST API to Microservices

such as 2.2.2, Group as com.example and Artifact as springboot and


selecting the first dependency of the project: Spring Web.

Figure 18: Spring Initializr to start a Spring Boot project

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

Figure 19: Spring Tools Site

The IDE STS 4 interface after being downloaded and installed can be viewed below,
being quite similar to Eclipse itself.

Figure 20: STS Interface

www.michellibrito.com 17
Spring Boot from REST API to Microservices

3.3. Project Structure

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.

Figure 21: Initial structure of a Spring Boot project

Within the root directory com.example.springboot, the class is located.


main application, SpringbootApplication, automatically generated by
Spring Boot is responsible for initializing the application. Just click on the
right mouse button, click on Run As => 2 Spring Boot App that the application
will be initiated.

www.michellibrito.com 18
Spring Boot from REST API to Microservices

Figure 22: Running the application

When running the application through the class SpringbootApplication, a


Embedded Tomcat is initialized, making the application available on port 8080.
in this case, as shown in the image below.

Figure 23: Application available on port 8080

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

the start time of a project, since it provides many of the configurations


pre-defined initials ready for use.

www.michellibrito.com 20
Spring Boot from REST API to Microservices

4. REST API with Spring Boot

4.1. REST API and RESTful

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.

An API can be considered RESTful when it uses in its


implementation of the architectural concept REST. REST is something abstract, like a

architectural model while RESTful is something more concrete, like the


implementation of this model in some API. So, to create an API
RESTful is necessary to know the REST architecture and also to apply it.
correctly.

4.1.1 REST Architecture

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.

Will respond to this client if the application is scaled in multiples.


servers, ensuring scalability and availability.

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.

4.1.2.Types of Representations in REST

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>

The JSON standard works with key/value.

www.michellibrito.com 22
Spring Boot From REST API to Microservices

{
“codigo”: 1,
Samsung S10
“valor”:3.500,00
}

4.1.3. Resources, Methods, and Returns

A resource is used to uniquely identify an abstract or physical object.


it is represented by the API URI. Such a resource, as it is an object, must be
represented by a noun and never by a verb.

/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.

4.1.4. Richardson Maturity Model

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.

A level 2 API uses the HTTP protocol semantically with its


methods and also defines the return types for each possible response of
a request. And finally, an API that reaches level 3 has HATEOAS
What are the hypermedia that show their current state and their relationship?
with future elements or states, that is, the capability of a document
to relate to others.

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:

GET /products HTTP/1.1


HTTP/1.1 200 OK
[{
“codigo”: 1,
Samsung S10
“links”: {
“mostrarProduto”: {
/products/1
}
}
},
{
“codigo”: 2,
Iphone 10
“links”: {
“mostrarProduto”: {
/products/2
}
}
}]

Example 2:

GET /products/1 HTTP/1.1


HTTP/1.1 200 OK
{
“codigo”: 1,
Samsung S10
“links”: {
showProductList
/products
}
}
}

www.michellibrito.com 25
Spring Boot from REST API to Microservices

4.2.Creating a REST API with Spring Boot

4.2.1. Creating connection with database

Returning to the project that was created in chapter 3 of this book, it is necessary to

first, create a connection to the local database to save and


search for the API resources and the database used in this example will be
PostgreSQL. But before making the connection, it is necessary to insert two more.

dependencies in the pom.xml file, Spring Data and the Postgres dependency,
As shown in the example below.

Figure 24: Dependency of Spring Data and JPA

After adding these dependencies to the project, it is necessary to configure the database.

data in the application.properties file, defining database access URL, name


of the bank and its credentials, as shown in the code below.

Figure 25: Database Configuration

4.2.2.Creating the Model and the Repository

www.michellibrito.com 26
Spring Boot From REST API to Microservices

Then it is necessary to create a model, an object that will be the representation of


resource in the API URI and this model will be a Product that will have the attributes
productId, name and value. To do this, within the root directory it is necessary to create a

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.

Figure 26: Product Entity mapped to the database

www.michellibrito.com 27
Spring Boot From REST API to Microservices

How was the configuration spring.jpa.hibernate.ddl-auto=update defined?


no application.properties, when initializing the application with this new
implementation, the table tb_product must be created in the database in a way

automatic, which can be viewed in the pgAdmin interface of Postgres in


image below.

Figure 27: pgAdmin interface showing the details of tb_produto

Now that the connection with the database is ready and the entity created, it is necessary to

create a new directory called repositories and within it create an interface


ProductRepository that extends JpaRepository from Spring Data to use
the methods already ready for transactions with the database, as shown in the
the code below.

www.michellibrito.com 28
Spring Boot from REST API to Microservices

Figure 28: ProductRepository Interface

Thus, methods such as findAll(), findById(Long id), save(S entity),


delete(S entity), among others can be used without the need for
implementation from scratch. The interface has been annotated with @Repository to show

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.

4.2.3.Creating the Controller

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

Figure 29: ProductController Class

4.2.4. Implementing the GET ALL and GET ONE methods

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.

some products were tested for these two endpoints


using Postman, obtaining the following result below.

www.michellibrito.com 31
Spring Boot from REST API to Microservices

/products HTTP GET

Figure 31: Postman test of the GET ALL method

/products/8 HTTP GET

Figure 32: Postman test of the GET ONE method

4.2.5. Implementing the POST, DELETE, and PUT methods

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).

And finally, to update a specific product, it is necessary to provide its id.


product for an initial search to be made for it in the database and if
exist, set the already existing id and then use the methodsave(S entity) to
save the product with the same existing id, that is, update it in the database
data.

All the step-by-step described above can be seen in the code below.

Figure 33: Implementation of POST, DELETE, and PUT methods

Carrying out tests of these latest implementations in Postman, the responses


for requests to the POST, PUT, and DELETE methods of products can be
visualized in the images below.

www.michellibrito.com 33
Spring Boot from REST API to Microservices

/products HTTP POST

Figure 34: Test in Postman for the POST method

/products/9 HTTP PUT

Figure 35: Test in Postman of the PUT method

www.michellibrito.com 34
Spring Boot From REST API to Microservices

/products/9 HTTP DELETE

Figure 36: Test in Postman of the DELETE method

Now for this Products API to be considered a RESTful API


to reach level 3 of Richardson maturity, it is necessary to include hypermedia
HATEOAS.

4.2.6. Inserting HATEOAS

To implement HATEOAS in the API, it is necessary to add one more dependency.


in the project pom.xml file, as shown in the code below.

Figure 37: HATEOAS Dependencies

According to Richardson's Maturity Model, an API must have


the hypermedia that show its current state and its relationship with the
elements or future states for it to be considered RESTful. Thus,
for this API to reach this level, the Product resource must present its
attributes and also the links, where the relationship path will be shown
with the other elements.

www.michellibrito.com 35
Spring Boot from REST API to Microservices

For this, in the ProductModel entity it is necessary to extend ResourceSupport to

that through its method add() the ProductModel class traces the link of the

other related urls, as shown in the code below.

Figure 38: ProdutoModel extends ResourceSupport

When a request is made to return a list of products or a


For a specific product, it is necessary to define the link that will be added in each case.

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

can be observed in the code below.

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.

the path and relationship to access each product individually, through


from the urlhttp://localhost:8080/products/{id}.

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. Microservices with Spring Boot

5.1.Microservices Architecture

More and more companies are adopting microservices architecture as


a new option to replace the monolithic architecture, which is based on
various modules in a single system, that is, it is defined as being a large
code block where all business rules are present and
application functionalities. Generally, an application that was built in
the top of the monolithic architecture usually has a single database used and
accessed by the entire system.

As an example of an application with a monolithic architecture, imagine a system


ERP, which is responsible for controlling purchasing, sales, finance,
accounting, among other operations within a corporation. Each one
these functionalities are based on a module, however all these modules
make up a single application, being strongly coupled and accessing the
same database, as can be seen in the image below.

Figure 43: Example of monolithic architecture

www.michellibrito.com 39
Spring Boot from REST API to Microservices

The microservices architecture is based on building an application


divided into several smaller, very specific and objective services also being
independent from each other. So going back to the example of the ERP system, if

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.

Figure 44: Example microservices architecture

When is it necessary to perform maintenance on the system or a new one?

implementation, whether to fix a bug in production or to insert a new one


functionality, using a microservices architecture this process becomes
much simpler, as there is no need to stop the entire system but rather,
only the microservice in question to make the correction or implementation. The
the service that will be unavailable will not affect the operation of the others and thus,
the other services that have different functionalities will be able to continue
responding to your customers normally.

www.michellibrito.com 40
Spring Boot From REST API to Microservices

Thus, the application's availability is much greater when compared to


a system built in a monolithic way, which to perform the same
the process would require stopping the application as a whole.

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.

Another relevant point is that in microservices architecture, as each micro


service usually has its own database, in case there is any change in
current data modeling in any of the services, such modification does not affect the
besides. This does not happen in monolithic architecture, where all the modules
they access the same database and thus become prone to errors or rule violations
in case there are changes in the data modeling.

Another advantage of microservices architecture is that each microservice can


to be built using the programming language that is most suitable
for each case generating a low coupling in the application, what is the most
adequate by design standards. As the services are independent, a
It is not necessary to know how the other was built, they just need to communicate.
whenever there is a need regardless of the language. When it comes to
monolithic style, the system as a whole needs to be built on top of the
same language, since it is not possible to divide it into modules and thus the
the application has a high coupling.

A positive point of monolithic architecture is that to deploy the


an application in a cloud just needs to generate a single war or jar file. In the architecture

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

configured generate automatic deploys with every push to git at a certain


environment. Thus, after being configured once, the deployment of these microservices
becomes something simpler and easier to control, however it is necessary to follow the good
practices and tools that cloud platforms offer to facilitate and
control these processes.

5.2.Communication between Microservices

In microservices architecture, the services are independent of each other, however


most of the time there is a need for communication between them. Among the
the most commonly used ways for this communication are communication through the
HTTP protocol using REST APIs for example, and communication through
of the AMPQ protocol, using messaging.

The type of communication between the microservices to be used in this type of


architecture should be defined according to the operation of the system and of the
main needs. In the case of synchronous systems, it can be used to
communication via the HTTP protocol creating an API for communication using
the JSON or XML standards, and in this case, communication is made between two
services, where the requester needs to receive feedback on the requested service
to complete your process.

In systems that operate asynchronously, the most appropriate way


communication is done through messaging via the AMQP protocol, cases in which
communication is made for the delivery of a message from a service to
others, without the need for returns, only the guarantee of delivery of such
message.

www.michellibrito.com 42
Spring Boot From REST API to Microservices

5.3.Example of Microservices with Spring Boot

How the process of starting an application with Spring Boot has become something quite

simple and quick, companies choose to use this framework to build


this microservices architecture, where besides Spring Boot brings this high
Productivity initially, the Spring platform already has several projects.
ready to be used in distributed systems, allowing for
applications ranging from the simplest to the most complex are built with
based on this framework.

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..

As a practical example, let's consider a product control application.


that provides APIs so that a front-end application with Angular can
build the interface of a system that displays the list of products of a
certain online store and also, which unit has stock of such
product in stock.

For this, it is necessary to first build a back-end application that


return these product APIs with the inventory details. Thinking about
distributed system, in principle it is already possible to divide this application into three

specific and independent services, one for product control, another for
inventory control and one for centralizing the entries in the application and
authentication (Gateway).

In this case, the product controls service receiving a request to


return to the client (angular application) the listing of products or the details of
a specific product needs to check the stock data which is from

www.michellibrito.com 43
Spring Boot from REST API to Microservices

responsibility of the stock control service, since they are services


different, each has its own database. Thus, analyzing the
functioning of this application in terms of communication, the control service
of products sends an internal request to the control service of
stock waiting for a response with the necessary data. In this case,
how the system is characterized synchronous the type of communication most appropriate
it would be using the HTTP protocol, where through a GET request via
HTTP REST or the product control service sends to the inventory control service
an order with the stock details for this product. Such flow can be
shown in the image below.

Figure 45: Flow of communication between 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.

Each of these microservices can be built as a


Spring Boot application and these services, product control and control of
stock will be nothing more and nothing less than a REST API similar to the one that was

built in chapter 4 of this book, which provides endpoints for its


resources. Thus, both the Angular application and the internal services themselves
They will be able to send and receive requests using the HTTP protocol.

Spring Cloud can be used to control the gateway with Spring.


Cloud Netflix Zuul for example, use Spring Netflix Eureka or Spring Cloud.
Consul for service discovery and Spring Cloud Config for configurations.
Also use Spring MVC since it is a web application and Spring Data for
communication/transaction with the database, among other modules of the
Spring platform.

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.

It is always important to reconcile the theory learned with practical examples, so


applying the concepts in practice will always reinforce learning and improve the
understanding. It is essential that the studies continue, after all the Spring platform
brings many different projects and modules that can be studied and used
in the construction of applications.

For anyone with questions, suggestions or criticism, you can contact us at


through the accesses or social networks presented at the beginning of the book for what

I can always improve and bring richer and more accurate content.
in the next editions.

Thank you!

www.michellibrito.com 46

You might also like