0% found this document useful (0 votes)
2 views48 pages

Unit-5 Spring Boot

Spring Boot is a framework that simplifies the setup and configuration of Spring applications, enabling rapid application development with minimal configuration. It eliminates the need for XML configuration and allows for the creation of stand-alone applications with embedded servers. The document also covers RESTful web services, Spring Boot architecture, annotations, and the process of creating a Spring Boot application using REST APIs.

Uploaded by

Pankaj Garg
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)
2 views48 pages

Unit-5 Spring Boot

Spring Boot is a framework that simplifies the setup and configuration of Spring applications, enabling rapid application development with minimal configuration. It eliminates the need for XML configuration and allows for the creation of stand-alone applications with embedded servers. The document also covers RESTful web services, Spring Boot architecture, annotations, and the process of creating a Spring Boot application using REST APIs.

Uploaded by

Pankaj Garg
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/ 48

Spring BOOT

Using REST API


ABES Engineering College, Ghaziabad
Introduction
• Spring Boot is a project that is built on top of the Spring
Framework. It provides an easier and faster way to set up,
configure, and run both simple and web-based applications.
• It is a Spring module that provides the RAD (Rapid Application
Development) feature to the Spring Framework used to create a
stand-alone Spring-based application that you can just run
because it needs minimal Spring configuration.
As summarized in the below figure, Spring
Boot is the combination of Spring
Framework and Embedded Servers.
Spring Boot Architecture

• In Spring Boot, there is no requirement for XML configuration


(deployment descriptor). It uses convention over configuration software
design paradigm which means that it decreases the effort of the
developer.
• The main goal of Spring Boot is to reduce development, unit test, and
integration test time and leveraging the following features:
• Create stand-alone Spring applications
• Embed Tomcat, Jetty, or Undertow directly (no need to deploy WAR
files)
Spring Boot Architecture

• Automatically configure Spring whenever possible


• Provide production-ready features such as metrics, health checks, and
externalized configuration
• Absolutely no code generation and no requirement for XML
configuration
• Provide opinionated ‘starter’ POMs to simplify your Maven
configuration
Spring Boot Architecture
Spring Boot Architecture

• Presentation Layer: The presentation layer handles the HTTP


requests, translates the JSON parameter to object, and authenticates
the request, and transfer it to the business layer. In short, it consists of
views.
Business Layer: The business layer handles all the business logic. It
consists of service classes and uses services provided by data access
layers. It also performs authorization and validation.
Persistence Layer: The persistence layer contains all the storage logic
and translates business objects from and to database rows.
Database Layer: In the database layer, CRUD (create, retrieve,
update, delete) operations are performed.

Spring Boot Architecture

• Spring Boot uses all the modules of Spring-like Spring MVC, Spring Data, etc.
The architecture of Spring Boot is the same as the architecture of Spring
MVC, except for one thing: there is no need for DAO and DAOImpl classes in
Spring boot. As a summary, in a simple spring boot flow:
• Data access layer gets created and CRUD operations are performed.
• The client makes the HTTP requests.
• The request goes to the controller, and the controller maps that request and
handles it. After that, it calls the service logic if required.
• In the service layer, all the business logic performs. It performs the logic on
the data that is mapped to JPA with model classes.
• A response page is returned to the user if no error occurs.

Spring Boot Architecture

•The Client makes


an HTTP request(GET, PUT, POST,
etc.)
•The HTTP request is forwarded to
the Controller. The controller maps
the request. It processes the
handles and calls the server logic.
•The business logic is performed in
the Service layer. The spring boot
performs all the logic over the data
of the database which is mapped
to the spring boot model class
through Java Persistence
Library(JPA).
•The JSP page is returned as
Response from the controller.
Spring Boot Starters
• Spring Boot starters are dependency descriptors
• Dependency: External libraries
• Descriptor: Configuration specific JARS and their Versions.
• Spring boot starter combines all the necessary libraries for a
particular feature or technology into a single dependency.
• Example: web.jar, web-MVC.jar, validation.jar, tomcat.jar
Spring Tool Suite(STS)
Springboot code Structure App Name

Source package Main class

Properties file

Pom file for


dependencies
Spring Boot Annotations

• Spring Boot Annotations is a form of metadata that provides data about


a program. Spring Boot Annotations are mostly placed in the following
packages:
• org.springframework.boot.autoconfigure
• org.springframework.boot.autoconfigure.condition

Spring Boot Annotations


Spring Boot run() method


Spring Boot resources folder


Spring Boot Normal Application
“pom.xml”


Spring Boot Web Application “pom.xml”


Spring Boot Runners
• In Spring Boot, runners are components used to execute code when
the application is started. They are typically implemented using
Spring's ApplicationRunner or CommandLineRunner interfaces. These
runners allow you to perform tasks such as database initialization,
data loading, or any custom startup logic.
Application Runner

• The
ApplicationRunner
interface in Spring
Boot provides a way
to execute code
after the
application context
is initialized and
before Spring Boot
starts servicing
incoming requests
CommandLine Runner
• Similar to
ApplicationRunner, import org.springframework.boot.CommandLineRunner;
CommandLineRunn import org.springframework.stereotype.Component;
er is an alternative
interface that @Component
provides a run public class MyCommandLineRunner implements
method with an CommandLineRunner {
array of String
arguments. These @Override
arguments are public void run(String... args) throws Exception {
passed directly to // Code to execute on application startup
the application System.out.println("CommandLineRunner is running...");
when it is started }
from the command }
line.
Springboot Logger

• In Spring Boot applications, logging is an essential aspect of monitoring and


debugging. Spring Boot integrates with popular logging frameworks like Logback,
Log4j2, and Java Util Logging (JUL). Here’s a guide on how to use logging in a Spring
Boot application with an example using Logback.
Steps to add Logger in Springboot App
Step1: Add dependency in POM.XML File
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-api -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>2.0.13</version>
</dependency>
• Step2: import relevant package in either Controller , Service or
repositories etc.
• Example Use Cases
• Database Initialization: Load initial data or perform schema setup.
• External Service Initialization: Connect to external services or
APIs.
• Cache Warming: Preload caches on application startup.
• Logging: Output informational messages or logs about application
state.
• MVC Design Pattern
Restful Web Services

• 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. REST is
an architectural approach, not a protocol.
Restful Web Services

• It does not define the standard message exchange format. We can build REST
services with both XML and JSON. JSON is more popular format with REST. The key
abstraction is a resource in REST. A resource can be anything. It can be accessed
through a Uniform Resource Identifier (URI). For example:
• The resource has representations like XML, HTML, and JSON. The current state
capture by representational resource. When we request a resource, we provide the
representation of the resource.
Restful Web Services

• The important methods of HTTP


are:
POST /users: It creates a user.
• GET: It reads a resource. GET /users/{id}: It retrieves the detail of a user.
• PUT: It updates an existing GET /users: It retrieves the detail of all users.
resource. DELETE /users: It deletes all users.
DELETE /users/{id}: It deletes a user.
• POST: It creates a new resource. GET /users/{id}/posts/post_id: It retrieve the detail of a
• DELETE: It deletes the resource. specific post.
Restful Web Services

• Advantages of RESTful web services


• RESTful web services are platform-independent.
• It can be written in any programming language and can be executed on any platform.
• It provides different data format like JSON, text, HTML, and XML.
• It is fast in comparison to SOAP because there is no strict specification like SOAP.
• These are reusable.
• They are language neutral.

Spring Boot Annotations
1. Spring – REST Controller
• 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. Let’s understand @RestController
annotation using an example. The RestController allows to handle all REST APIs such
as GET, POST, Delete, PUT requests.
Create a Rest Controller

Create a new package as com.example.demo.controller and create a new class as SampleController , now
make this class as RestController using @RestController annotation

Now, Apply @GetMapping annotation to create an end point to access this controller, given below is
code:
2. PostMapping
3. Spring – Request Body
• @RequestBody: Annotation is used to get the request body
in the incoming request.
4. Spring – Request Mapping and
ResponseBody
• @RequestMapping Annotation which is used to map HTTP requests to
handler methods of MVC and REST controllers.
• The @RequestMapping annotation can be applied to class-level and/or
method-level in a controller.
• The class-level annotation maps a specific request path or pattern onto a
controller.
• You can then apply additional method-level annotations to make mappings
more specific to handler methods.
• @ResponseBody annotation tells a controller that the object returned is
automatically serialized into JSON and passed back into the HttpResponse
object. When you use the @ResponseBody annotation on a method, Spring
converts the return value and writes it to the HTTP response automatically.
5. Spring – Request Mapping and
ResponseBody
6. Spring – PathVariable
• The @PathVariable annotation is used to extract the value from the URI. It is
most suitable for the RESTful web service where the URL contains some
value. Spring MVC allows us to use multiple @PathVariable annotations in
the same method. A path variable is a critical part of creating rest resources.
@GetMapping(path="/hello-world/path-variable/{name}")
public HelloWorldBean helloWorldPathVariable(@PathVariable String name)
{
return new HelloWorldBean(String.format("Hello World, %s", name));
}
URL: http://localhost:8080/hello-world/path-variable/ABES O/P- {“message”:”Hello World,
ABES”}
7. Spring – Request Parameter
• The @RequestParam annotation is used to extract data from
the query parameters in the request URL. Query parameters
are the key-value pairs that appear after the ? in a URL.
Rest API

• REpresentational State Transfer (REST) is a software architectural


style that developers apply to web application programming interfaces
(APIs).
• REST APIs are the most common APIs used across the web today
because the REST pattern provides simple, uniform interfaces. These
can be used to make data, content, algorithms, media, and other digital
resources available through web URLs, so that they can be consumed
within web, mobile, and device applications.
Rest API
• let’s consider my own personal Facebook presence, where I
am a resource. I can view an HTML representation of my
resource at:
• GET https://www.facebook.com/prashant.tomer.946/
• My profile is a single resource available on Facebook. I can
view a representation of that resource in HTML using that URL
in my web browser. I can also view another representation of it
using the Facebook Graph API.
• GET https://graph.facebook.com/v7.0/me
Rest API
• This is just one resource Facebook provides, offering up a buffet of digital resources for
me to consume as a developer.
• Comments: GET https://graph.facebook.com/v7.0/comments
• Friends: GET https://graph.facebook.com/v7.0/friends
• Images: GET https://graph.facebook.com/v7.0/images
• Links: GET https://graph.facebook.com/v7.0/links
• Likes: GET https://graph.facebook.com/v7.0/likes
Rest API
• This allows for a handful of operations on each resource using HTTP
methods:
• GET: https://graph.facebook.com/v7.0/images
• POST: https://graph.facebook.com/v7.0/images
• PUT: https://graph.facebook.com/v7.0/images
• DELETE: https://graph.facebook.com/v7.0/images
Create Spring boot App using Rest API
• Tools Required in this Soring Boot Application:
Eclipse IDE: For project development
Postman Application: Rest API Testing
Spring Boot API: For Spring boot libraries
JDK 8: base of java core development
Steps to Create SpringBoot project and use
RestAPI

Step1: Download springboot skeleton from spring initializer.


Step 2: import step1 project in eclipse IDE.
Step3: Open main file where you get main method and run that class as usual
do in eclipse to run the normal class.
 Step4: Observe the output.
Project Skeleton
Run Application
• To test your REST end point, need to run your springboot application
and check on which port your application is running (check console
and analyse the output , port number is also there), now go to
browser and access using your end point name:
Thank You

You might also like