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

Spring Boot

Spring Boot is a Spring module that simplifies the setup and configuration of Spring applications, allowing for rapid application development with minimal configuration. It eliminates the need for XML configuration, supports embedded servers, and integrates easily with other Java frameworks, enhancing productivity and reducing development time. Key features include web development capabilities, externalized configuration, and a variety of annotations for managing application components.

Uploaded by

Amishree Talekar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Spring Boot

Spring Boot is a Spring module that simplifies the setup and configuration of Spring applications, allowing for rapid application development with minimal configuration. It eliminates the need for XML configuration, supports embedded servers, and integrates easily with other Java frameworks, enhancing productivity and reducing development time. Key features include web development capabilities, externalized configuration, and a variety of annotations for managing application components.

Uploaded by

Amishree Talekar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Spring Boot

Spring Boot is a Spring module that provides the RAD (Rapid Application
Development) feature to the Spring framework.

What is 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, 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. It is used to create a
stand-alone Spring-based application that you can just run because it
needs minimal Spring configuration.

In short, Spring Boot is the combination of Spring


Framework and Embedded Servers.

In Spring Boot, there is no requirement for XML configuration (deployment


descriptor). It uses convention over configuration software design
paradigm that means it decreases the effort of the developer.

We can use Spring STS IDE or Spring Initializr to develop Spring Boot
Java applications.

Why should we use Spring Boot Framework?

We should use Spring Boot Framework because:

o The dependency injection approach is used in Spring Boot.


o It contains powerful database transaction management capabilities.
o It simplifies integration with other Java frameworks like
JPA/Hibernate ORM, Struts, etc.
o It reduces the cost and development time of the application.

Along with the Spring Boot Framework, many other Spring sister projects
help to build applications addressing modern business needs. There are
the following Spring sister projects are as follows:

o Spring Data: It simplifies data access from the relational


and NoSQL databases.
o Spring Batch: It provides powerful batch processing.
o Spring Security: It is a security framework that provides
robust security to applications.
o Spring Social: It supports integration with social networking like
LinkedIn.
o Spring Integration: It is an implementation of Enterprise
Integration Patterns. It facilitates integration with other enterprise
applications using lightweight messaging and declarative
adapters.

Advantages of Spring Boot


o It creates stand-alone Spring applications that can be started using
Java -jar.
o It tests web applications easily with the help of
different Embedded HTTP servers such as Tomcat, Jetty, etc. We
don't need to deploy WAR files.
o It provides opinionated 'starter' POMs to simplify our Maven
configuration.
o It provides production-ready features such as metrics, health
checks, and externalized configuration.
o There is no requirement for XML configuration.
o It offers a CLI tool for developing and testing the Spring Boot
application.
o It offers the number of plug-ins.
o It also minimizes writing multiple boilerplate codes (the code that
has to be included in many places with little or no alteration), XML
configuration, and annotations.
o It increases productivity and reduces development time.

Limitations of Spring Boot


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

Goals of Spring Boot


The main goal of Spring Boot is to reduce development, unit
test, and integration test time.

o Provides Opinionated Development approach


o Avoids defining more Annotation Configuration
o Avoids writing lots of import statements
o Avoids XML Configuration.

By providing or avoiding the above points, Spring Boot Framework


reduces Development time, Developer Effort, and increases
productivity.

Spring Boot Features


o Web Development
o Spring Application
o Application events and listeners
o Admin features
o Externalized Configuration
o Properties Files
o YAML Support
o Type-safe Configuration
o Logging
o Security

Web Development
It is a well-suited Spring module for web application development. We can
easily create a self-contained HTTP application that uses embedded
servers like Tomcat, Jetty, or Undertow. We can use the spring-boot-
starter-web module to start and run the application quickly.

SpringApplication

The SpringApplication is a class that provides a convenient way to


bootstrap a Spring application. It can be started from the main method.
We can call the application just by calling a static run() method.

1. public static void main(String[] args)


2. {
3. SpringApplication.run(ClassName.class, args);
4. }

Application Events and Listeners

Spring Boot uses events to handle the variety of tasks. It allows us to


create factories file that is used to add listeners. We can refer it to using
the ApplicationListener key.

Always create factories file in META-INF folder


like META-INF/spring.factories.

Admin Support

Spring Boot provides the facility to enable admin-related features for the
application. It is used to access and manage applications remotely. We
can enable it in the Spring Boot application by
using spring.application.admin.enabled property.

Externalized Configuration

Spring Boot allows us to externalize our configuration so that we can work


with the same application in different environments. The application uses
YAML files to externalize configuration.

Properties Files

Spring Boot provides a rich set of Application Properties. So, we can


use that in the properties file of our project. The properties file is used to
set properties like server-port =8082 and many others. It helps to
organize application properties.

YAML Support
It provides a convenient way of specifying the hierarchical configuration. It
is a superset of JSON. The SpringApplication class automatically supports
YAML. It is an alternative of properties file.

Type-safe Configuration

The strong type-safe configuration is provided to govern and validate the


configuration of the application. Application configuration is always a
crucial task which should be type-safe. We can also use annotation
provided by this library.

Logging

Spring Boot uses Common logging for all internal logging. Logging
dependencies are managed by default. We should not change logging
dependencies if no customization is needed.

Security

Spring Boot applications are spring bases web applications. So, it is secure
by default with basic authentication on all HTTP endpoints. A rich set of
Endpoints is available to develop a secure Spring Boot application.

Spring vs. Spring Boot

Spring: Spring Framework is the most popular application development


framework of Java. The main feature of the Spring Framework
is dependency Injection or Inversion of Control (IoC). With the help of
Spring Framework, we can develop a loosely coupled application. It is
better to use if application type or characteristics are purely defined.

Spring Boot: Spring Boot is a module of Spring Framework. It allows us


to build a stand-alone application with minimal or zero configurations. It is
better to use if we want to develop a simple Spring-based application or
RESTful services.

Spring Spring Boot

Spring Framework is a widely used Spring Boot Framework is widely


Java EE framework for building used to develop REST APIs.
applications.

It aims to shorten the code length and


It aims to simplify Java EE provide the easiest way to
development that makes developers develop Web Applications.
more productive
The primary feature of Spring Boot
primary feature of the Spring is Autoconfiguration. It
Framework is dependency injection. automatically configures the classes
based on the requirement.

It helps to make things simpler by It helps to create a stand-


allowing us to develop loosely alone application with less
coupled applications. configuration.

The developer writes a lot of code It reduces boilerplate code.


(boilerplate code) to do the minimal
task.

To test the Spring project, we need to Spring Boot offers embedded


set up the sever explicitly. server such as Jetty and Tomcat,
etc.
Spring Boot comes with the concept
Developers manually define of starter in pom.xml file that
dependencies for the Spring project internally takes care of downloading
in pom.xml. the dependencies JARs based on
Spring Boot Requirement.

Creating Project

Spring Initializr
Spring Initializr is a web-based tool provided by the Pivotal Web
Service. With the help of Spring Initializr, we can easily generate the
structure of the Spring Boot Project. It offers extensible API for creating
JVM-based projects.

It also provides various options for the project that are expressed in a
metadata model. The metadata model allows us to configure the list of
dependencies supported by JVM and platform versions, etc. It serves its
metadata in a well-known that provides necessary assistance to third-
party clients.

Skip 10s
Generating a Project
Before creating a project, we must be friendly with UI. Spring Initializr UI
has the following labels:

o Project: It defines the kind of project. We can create either Maven


Project or Gradle Project. We will create a Maven
Project throughout the tutorial.
o Language: Spring Initializr provides the choice among three
languages Java, Kotlin, and Groovy. Java is by default selected.
o Spring Boot: We can select the Spring Boot version. The latest
version is 2.2.2.
o Project Metadata: It contains information related to the project,
such as Group, Artifact, etc. Group denotes
the package name; Artifact denotes the Application name. The
default Group name is com.example, and the default Artifact name
is demo.
o Dependencies: Dependencies are the collection of artifacts that
we can add to our project.

There is another Options section that contains the following fields:

o Name: It is the same as Artifact.


o Description: In the description field, we can write a description of
the project.
o Package Name: It is also similar to the Group name.
o Packaging: We can select the packing of the project. We can
choose either Jar or War.
o Java: We can select the JVM version which we want to use. We will
use Java 8 version throughout the tutorial.

There is a Generate button. When we click on the button, it starts


packing the project and downloads the Jar or War file, which you have
selected.

Creating a Spring Boot Project


Following are the steps to create a simple Spring Boot Project.

Step 1: Open the Spring initializr https://start.spring.io.

Step 2: Provide the Group and Artifact name. We have provided Group
name com.javapoint and Artifact spring-boot-example.

Step 3: Now click on the Generate button.


When we click on the Generate button, it starts packing the project in
a .rar file and downloads the project.

Step 4: Extract the RAR file.

Step 5: Import the folder.

File -> Import -> Existing Maven Project -> Next -> Browse -> Select the
project -> Finish

It takes some time to import the project. When the project imports
successfully, we can see the project directory in the Package Explorer.
The following image shows the project directory:
Spring Boot Annotations
Spring Boot Annotations is a form of metadata that provides data about a
program. In other words, annotations are used to
provide supplemental information about a program. It is not a part of the
application that we develop. It does not have a direct effect on the
operation of the code they annotate. It does not change the action of the
compiled program.

In this section, we are going to discuss some important Spring Boot


Annotation that we will use later in this tutorial.

Core Spring Framework Annotations


@Required: It applies to the bean setter method. It indicates that the
annotated bean must be populated at configuration time with the required
property, else it throws an exception BeanInitilizationException.

Example

1. public class Machine


2. {
3. private Integer cost;
4. @Required
5. public void setCost(Integer cost)
6. {
7. this.cost = cost;
8. }
9. public Integer getCost()
10.{
11. return cost;
12.}
13. }

@Autowired: Spring provides annotation-based auto-wiring by providing


@Autowired annotation. It is used to autowire spring bean on setter
methods, instance variable, and constructor. When we use @Autowired
annotation, the spring container auto-wires the bean by matching data-
type.

Example

1. @Component
2. public class Customer
3. {
4. private Person person;
5. @Autowired
6. public Customer(Person person)
7. {
8. this.person=person;
9. }
10.}

@Configuration: It is a class-level annotation. The class annotated with


@Configuration used by Spring Containers as a source of bean definitions.

Example

1. @Configuration
2. public class Vehicle
3. {
4. @BeanVehicle engine()
5. {
6. return new Vehicle();
7. }
8. }
@ComponentScan: It is used when we want to scan a package for
beans. It is used with the annotation @Configuration. We can also specify
the base packages to scan for Spring Components.

Example

1. @ComponentScan(basePackages = "com.javapoint")
2. @Configuration
3. public class ScanComponent
4. {
5. // ...
6. }

@Bean: It is a method-level annotation. It is an alternative of XML


<bean> tag. It tells the method to produce a bean to be managed by
Spring Container.

Example

1. @Bean
2. public BeanExample beanExample()
3. {
4. return new BeanExample ();
5. }

Spring Framework Stereotype Annotations


@Component: It is a class-level annotation. It is used to mark a Java
class as a bean. A Java class annotated with @Component is found
during the classpath. The Spring Framework pick it up and configure it in
the application context as a Spring Bean.

Example

1. @Component
2. public class Student
3. {
4. .......
5. }

@Controller: The @Controller is a class-level annotation. It is a


specialization of @Component. It marks a class as a web request
handler. It is often used to serve web pages. By default, it returns a string
that indicates which route to redirect. It is mostly used
with @RequestMapping annotation.

Example

1. @Controller
2. @RequestMapping("books")
3. public class BooksController
4. {
5. @RequestMapping(value = "/{name}", method = RequestMethod.G
ET)
6. public Employee getBooksByName()
7. {
8. return booksTemplate;
9. }
10.}

@Service: It is also used at class level. It tells the Spring that class
contains the business logic.

Example

1. package com.javapoint;
2. @Service
3. public class TestService
4. {
5. public void service1()
6. {
7. //business code
8. }
9. }

@Repository: It is a class-level annotation. The repository is


a DAOs (Data Access Object) that access the database directly. The
repository does all the operations related to the database.

1. package com.javapoint;
2. @Repository
3. public class TestRepository
4. {
5. public void delete()
6. {
7. //persistence code
8. }
9. }

Spring Boot Annotations


o @EnableAutoConfiguration: It auto-configures the bean that is present
in the classpath and configures it to run the methods. The use of this
annotation is reduced in Spring Boot 1.2.0 release because developers
provided an alternative of the annotation, i.e. @SpringBootApplication.
o @SpringBootApplication: It is a combination of three
annotations @EnableAutoConfiguration,
@ComponentScan, and @Configuration.

Spring MVC and REST Annotations


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

Example

1. @Controller
2. public class BooksController
3. {
4. @RequestMapping("/computer-science/books")
5. public String getAllBooks(Model model)
6. {
7. //application code
8. return "bookList";
9. }
o @GetMapping: It maps the HTTP GET requests on the specific handler
method. It is used to create a web service endpoint that fetches It is used
instead of using: @RequestMapping(method = RequestMethod.GET)
o @PostMapping: It maps the HTTP POST requests on the specific
handler method. It is used to create a web service endpoint
that creates It is used instead of using: @RequestMapping(method =
RequestMethod.POST)
o @PutMapping: It maps the HTTP PUT requests on the specific handler
method. It is used to create a web service endpoint
that creates or updates It is used instead of
using: @RequestMapping(method = RequestMethod.PUT)
o @DeleteMapping: It maps the HTTP DELETE requests on the specific
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)
o @PatchMapping: It maps the HTTP PATCH requests on the specific
handler method. It is used instead of using: @RequestMapping(method
= RequestMethod.PATCH)
o @RequestBody: It is used to bind HTTP request with an object in a
method parameter. Internally it uses HTTP MessageConverters to
convert the body of the request. When we annotate a method parameter
with @RequestBody, the Spring framework binds the incoming HTTP
request body to that parameter.
o @ResponseBody: It binds the method return value to the response body.
It tells the Spring Boot Framework to serialize a return an object into JSON
and XML format.
o @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 define multiple @PathVariable in a method.
o @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
applications. It can specify default values if the query parameter is not
present in the URL.
o @RequestHeader: It is used to get the details about the HTTP request
headers. We use this annotation as a method parameter. The optional
elements of the annotation are name, required, value,
defaultValue. For each detail in the header, we should specify separate
annotations. We can use it multiple time in a method
o @RestController: It can be considered as a combination
of @Controller and @ResponseBody annotations. The @RestController
annotation is itself annotated with the @ResponseBody annotation. It
eliminates the need for annotating each method with @ResponseBody.
o @RequestAttribute: It binds a method parameter to request attribute. It
provides convenient access to the request attributes from a controller
method. With the help of @RequestAttribute annotation, we can access
objects that are populated on the server-side.

You might also like