0% found this document useful (0 votes)
29 views

Unit 5

This document provides information about Spring Boot including what it is, its advantages, limitations, prerequisites, architecture and common annotations used. Spring Boot makes it easier to create stand-alone and production-grade Spring based applications with minimal configuration.

Uploaded by

Himanshu Sharma
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)
29 views

Unit 5

This document provides information about Spring Boot including what it is, its advantages, limitations, prerequisites, architecture and common annotations used. Spring Boot makes it easier to create stand-alone and production-grade Spring based applications with minimal configuration.

Uploaded by

Himanshu Sharma
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/ 13

KIET Group of Institutions, Ghaziabad

Department of Computer Applications


(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology

Unit-5

Spring Boot

Spring Boot is a project that is built on the top of the Spring Framework. It provides an easier and faster
way to set up, confgure, and run both simple and web-based applicatons.

It is a Spring module that provides the RAD (Rapid Applicaton Development) feature to the Spring
Framework. It is used to create a stand-alone Spring-based applicaton that you can just run because it
needs minimal Spring confguraton.

What is Spring Boot

In short, Spring Boot is the combinaton of Spring Framework and Embedded Servers.

In Spring Boot, there is no requirement for XML confguraton (deployment descriptor). It uses
conventon over confguraton sofware design paradigm that means it decreases the efort of the
developer.

We can use Spring STS IDE or Spring Initaliier to develop Spring Boot Java applicatons.

Why should we use Spring Boot Framework?

The dependency injecton approach is used in Spring Boot.

It contains powerful database transacton management capabilites.

It simplifes integraton with other Java frameworks like JAAHiibernate ORM, Struts, etc.

It reduces the cost and development tme of the applicaton.

Advantages of Spring Boot

It creates stand-alone Spring applicatons that can be started using Java -jar.

It tests web applicatons easily with the help of diferent Embedded iTTA servers such as Tomcat, Jety,
etc. We don't need to deploy WAR fles.
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
It provides opinionated 'starter' AOMs to simplify our Maven confguraton.

It provides producton-ready features such as metrics, health checks, and externaliied confguraton.

There is no requirement for XML confguraton.

It ofers a CLI tool for developing and testng the Spring Boot applicaton.

It ofers the number of plug-ins.

It also minimiies writng multple boilerplate codes (the code that has to be included in many places
with litle or no alteraton), XML confguraton, and annotatons.

It increases productvity and reduces development tme.

Limitations of Spring Boot

Spring Boot can use dependencies that are not going to be used in the applicaton. These dependencies
increase the siie of the applicaton.

Prerequisite of Spring Boot

To create a Spring Boot applicaton, following are the prerequisites. In this tutorial, we will use Spring
Tool Suite (STS) IDE.

 Java 1.8
 Maven 3.0+
 Spring Framework 5.0.0. BUILD-SNAASiOT
 An IDE (Spring Tool Suite) is recommended

Spring Boot Architecture

Spring Boot is a module of the Spring Framework. It is used to create stand-alone, producton-grade
Spring Based Applicatons with minimum eforts. It is developed on top of the core Spring Framework.

Spring Boot follows a layered architecture in which each layer communicates with the layer directly
below or above (hierarchical structure) it.

 Aresentaton Layer
 Business Layer
 Aersistence Layer
 Database Layer
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology

Spring Boot Flow 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 one thing: there is no need for
DAO and DAOImpl classes in Spring boot.
 Creates a data access layer and performs CRUD operaton.
 The client makes the iTTA requests (AUT or GET).
 The request goes to the controller, and the controller maps that request and handles it. Afer
that, it calls the service logic if required.
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
 In the service layer, all the business logic performs. It performs the logic on the data that is
mapped to JAA with model classes.
 A JSA page is returned to the user if no error occurred.

Spring Boot Confguration:

 Follow the following steps:


 Create a maven project with the help of spring initaliier. htps:HHstart.spring.ioH
 Add the dependencies
o Spring Web
o MYSQL
o iibernate JAA
 Generate the project and download the iip
 Import that project as existng maven project into spring tool suite
 Wait for some tme for the installaton of dependencies (will take some tme)
 Remove it tll then you are not using JAA otherwise it may show errors from porm.xml
<dependency>
<groupId>org.springframework.boot<HgroupId>
<artfactId>spring-boot-starter-data- jpa<HartfactId>
<Hdependency>

 Execute it as spring boot app


 Send request using postman or browser localost:8080
 It returns not found error because we have not defned controller
 Create a class for controller use the @RestContoller annotaton with class
 Defne a method with GetMapping(“/Hhome)) annotaton

Spring Boot Annotations

Spring Boot Annotatons is a form of metadata that provides data about a program. In other words,
annotatons are used to provide supplemental informaton about a program. It is not a part of the
applicaton that we develop. It does not have a direct efect on the operaton of the code they annotate.
It does not change the acton of the compiled program.

Core Spring Framework Annotatons can also use here. Apart from those following are exclusively used
with spring boot.

@EnableAutoConfguration: It auto-confgures the bean that is present in the classpath and confgures
it to run the methods. The use of this annotaton is reduced in Spring Boot 1.2.0 release because
developers provided an alternatve of the annotaton, i.e. @SpringBootApplicaton.
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
@SpringBootApplication: It is a combinaton of three annotatons @EnableAutoConfguraton,
@ComponentScan, and @Confguraton.

@RequestMapping: It is used to map the web requests. It has many optonal elements like consumes,
header, method, name, params, path, produces, and value. We use it with the class as well as the
method.

Example

@Controller

public class BooksController

@RequestMapping("Hcomputer-scienceHbooks")

public String getAllBooks(Model model)

HHapplicaton code

return "bookList";

@GetMapping: It maps the iTTA GET requests on the specifc handler method. It is used to create a
web service endpoint that fetches It is used instead of using: @RequestMapping(method =
RequestMethod.GET)

@PostMapping: It maps the iTTA AOST requests on the specifc handler method. It is used to create a
web service endpoint that creates It is used instead of using: @RequestMapping(method =
RequestMethod.AOST)

@PutMapping: It maps the iTTA AUT requests on the specifc handler method. It is used to create a
web service endpoint that creates or updates It is used instead of using: @RequestMapping(method =
RequestMethod.AUT)

@DeleteMapping: It maps the iTTA DELETE requests on the specifc handler method. It is used to
create a web service endpoint that deletes a resource. It is used instead of using:
@RequestMapping(method = RequestMethod.DELETE)

@AatchMapping: It maps the iTTA AATCi requests on the specifc handler method. It is used instead of
using: @RequestMapping(method = RequestMethod.AATCi)
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
@RequestBody: It is used to bind iTTA request with an object in a method parameter. Internally it uses
iTTA MessageConverters to convert the body of the request. When we annotate a method parameter
with @RequestBody, the Spring framework binds the incoming iTTA request body to that parameter.

@ResponseBody: It binds the method return value to the response body. It tells the Spring Boot
Framework to serialiie a return an object into JSON and XML format.

@PathVariable: It is used to extract the values from the URI. It is most suitable for the RESTful web
service, where the URL contains a path variable. We can defne multple @AathVariable in a method.

@RequestParam: It is used to extract the query parameters form the URL. It is also known as a query
parameter. It is most suitable for web applicatons. It can specify default values if the query parameter is
not present in the URL.

@RequestHeader: It is used to get the details about the iTTA request headers. We use this annotaton
as a method parameter. The optonal elements of the annotaton are name, required, value,
defaultValue. For each detail in the header, we should specify separate annotatons. We can use it
multple tme in a method

@RestController: It can be considered as a combinaton of @Controller and @ResponseBody


annotatons. The @RestController annotaton is itself annotated with the @ResponseBody annotaton. It
eliminates the need for annotatng each method with @ResponseBody.

@RequestAttribute: It binds a method parameter to request atribute. It provides convenient access to


the request atributes from a controller method. With the help of @RequestAtribute annotaton, we
can access objects that are populated on the server-side.

Spring Boot Actuator

Spring Boot Actuator is a sub-project of the Spring Boot Framework. It includes a number of additonal
features that help us to monitor and manage the Spring Boot applicaton. It contains the actuator
endpoints (the place where the resources live). We can use iTTA and JMX endpoints to manage and
monitor the Spring Boot applicaton. If we want to get producton-ready features in an applicaton, we
should use the Spring Boot actuator.

Spring Boot Actuator Features

There are three main features of Spring Boot Actuator:

 Endpoints
 Metrics
 Audit

Endpoint: The actuator endpoints allows us to monitor and interact with the applicaton. Spring Boot
provides a number of built-in endpoints. We can also create our own endpoint. We can enable and
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
disable each endpoint individually. Most of the applicaton choose iTTA, where the Id of the endpoint,
along with the prefx of Hactuator, is mapped to a URL.

For example, the Hhealth endpoint provides the basic health informaton of an applicaton. The actuator,
by default, mapped it to HactuatorHhealth.

Metrics: Spring Boot Actuator provides dimensional metrics by integratng with the micrometer. The
micrometer is integrated into Spring Boot. It is the instrumentaton library powering the delivery of
applicaton metrics from Spring. It provides vendor-neutral interfaces for tmers, gauges, counters,
distributon summaries, and long task tmers with a dimensional data model.

Audit: Spring Boot provides a fexible audit framework that publishes events to an
AuditEventRepository. It automatcally publishes the authentcaton events if spring-security is in
executon.

Spring Boot Runners

Spring Boot provides two runner interfaces, which are ApplicatonRunner and CommandLineRunner.
Both of these runners are used to execute piece of code when a Spring Boot Applicaton starts.

Both of these interfaces are Functonal Interfaces, which means they have only one functonal method.
In order to execute specifc piece of code when Spring Boot Applicaton starts, we need to implement
either of these functonal interfaces and override the single method of run.

Applicaton Runner is an interface used to execute the code afer the Spring Boot applicaton started.
The example given below shows how to implement the Applicaton Runner interface on the main class
fle.

package com.kiet.demo;

import org.springframework.boot.ApplicatonArguments;

import org.springframework.boot.ApplicatonRunner;

import org.springframework.boot.SpringApplicaton;

import org.springframework.boot.autoconfgure.SpringBootApplicaton;

@SpringBootApplicaton

public class DemoApplicaton implements ApplicatonRunner {


KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
public statc void main(String[] args) {

SpringApplicaton.run(DemoApplicaton.class, args);

@Override

public void run(ApplicatonArguments arg0) throws Excepton {

System.out.println("iello World from Applicaton Runner");

Logger:

Logging is an AAI that provides the ability to trace out the errors of the applicatons. When an
applicaton generates the logging call, the Logger records the event in the LogRecord. Afer that, it sends
to the corresponding handlers or appenders.

RestAPI Application:

Follow the basic steps for creatng the springboot applicaton.

Now Create a class as MyController as follows.

MyController.java

package com.kiet.rest.kietrest.controller;

import java.utl.List;
import org.springframework.beans.factory.annotaton.Autowired;
import org.springframework.htp.itpStatus;
import org.springframework.htp.ResponseEntty;
import org.springframework.web.bind.annotaton.DeleteMapping;
import org.springframework.web.bind.annotaton.GetMapping;
import org.springframework.web.bind.annotaton.AathVariable;
import org.springframework.web.bind.annotaton.AostMapping;
import org.springframework.web.bind.annotaton.AutMapping;
import org.springframework.web.bind.annotaton.RequestBody;
import org.springframework.web.bind.annotaton.RestController;

import com.kiet.rest.kietrest.enttes.Course;
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
import com.kiet.rest.kietrest.services.CourseService;

@RestController
public class MyController {

@Autowired
private CourseService courseService;

@GetMapping("Hhome")
public String home() {
return "Welcom to my frst AAA";
}

HHget the courses


@GetMapping("Hcourses")
public List<Course> getCourses(){

return this.courseService.getCourses();

@GetMapping("HcoursesH{courseId}")
public Course getCourse(@AathVariable String courseId) {
return this.courseService.getCourse(Integer.parseInt(courseId));
}

@AostMapping("Hcourses")
public Course addCourse(@RequestBody Course course ) {

return this.courseService.addCourse(course);
}

HHUpdate Apis

@AutMapping("Hcourses")
public Course updateCourse(@RequestBody Course course) {
return this.courseService.updateCourse(course);

HHdelete apis

@DeleteMapping("HcoursesH{courseId}")
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
public ResponseEntty<itpStatus> deleteCourse(@AathVariable String courseId){

System.out.println("Delete course Invoked");

try {
this.courseService.deleteCourse(Integer.parseInt(courseId));

return new ResponseEntty<>(itpStatus.OK);


}
catch(Excepton e) {
return new ResponseEntty<>(itpStatus.INTERNAL_SERVER_ERROR);
}
}

Create a bean class with getter and setters

package com.kiet.rest.kietrest.enttes;

public class Course {

private int id;


private String tltle;
private String descripton;
public Course(int id, String tltle, String descripton) {
super();
this.id = id;
this.tltle = tltle;
this.descripton = descripton;
}
public Course() {
super();
HH TODO Auto-generated constructor stub
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTiltle() {
return tltle;
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
}
public void setTiltle(String tltle) {
this.tltle = tltle;
}
public String getDescripton() {
return descripton;
}
public void setDescripton(String descripton) {
this.descripton = descripton;
}
@Override
public String toString() {
return "Course [id=" + id + ", tltle=" + tltle + ", descripton=" + descripton + "]";
}

Now create the business logic into service

Create an interface
package com.kiet.rest.kietrest.services;

import java.utl.List;

import com.kiet.rest.kietrest.enttes.Course;

public interface CourseService {


public List<Course> getCourses();

public Course getCourse(int courseId);

public Course addCourse(Course course);

public Course updateCourse(Course course);

public void deleteCourse(int id);

Implement it into a service class

package com.kiet.rest.kietrest.services;
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology
import java.utl.ArrayList;
import java.utl.List;
import org.springframework.stereotype.Service;
import com.kiet.rest.kietrest.enttes.Course;

@Service
public class CourseServiceImpl implements CourseService {

List<Course> list;

public CourseServiceImpl() {
HH TODO Auto-generated constructor stub
list = new ArrayList<>();
list.add(new Course(123, "JAVA", "Best Course of Spring Boot"));
list.add(new Course(124, "Node", "Best Course of SNode JS"));
}

@Override
public List<Course> getCourses() {
HH TODO Auto-generated method stub
return list;
}

@Override
public Course getCourse(int courseId) {
Course c = null;

for(Course course:list) {
if(course.getId()==courseId) {
c = course;
break;
}

return c;
}

@Override
public Course addCourse(Course course) {
list.add(course);
return course;
}
KIET Group of Institutions, Ghaziabad
Department of Computer Applications
(An ISO – 9001: 2008 Certified & ‘A’ Grade accredited Institution by NAAC)
Session 2021-2022 Odd Sem
KCA021: Web Technology

@Override
public Course updateCourse(Course course) {

for(Course e:list) {
if(e.getId()==course.getId()) {
e.setTiltle(course.getTiltle());
e.setDescripton(course.getDescripton());

}
}

return course;
}

@Override
public void deleteCourse(int id) {
HH TODO Auto-generated method stub
Course c = getCourse(id);
list.remove(c);

Now execute the springboot app and test the api using postman tool.

You might also like