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

SpringBoot-Training 1.0

This document provides an overview of Spring Boot training, including what Spring Boot is, its advantages and limitations, prerequisites, and features. It discusses how Spring Boot starters work and popular starters and their transitive dependencies. It also covers auto-configuration, embedded servers, bootstrapping applications, and important Spring Boot annotations.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
459 views

SpringBoot-Training 1.0

This document provides an overview of Spring Boot training, including what Spring Boot is, its advantages and limitations, prerequisites, and features. It discusses how Spring Boot starters work and popular starters and their transitive dependencies. It also covers auto-configuration, embedded servers, bootstrapping applications, and important Spring Boot annotations.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Spring Boot Training

Introduction

Spring Boot Tutorial provides basic and advanced concepts of Spring Framework. Our
Spring Boot Tutorial is designed for beginners and professionals both.

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

Our Spring Boot Tutorial includes all topics of Spring Boot such, as features, project,
maven project, starter project wizard, Spring Initializr, CLI, applications, annotations,
dependency management, properties, starters, Actuator, JPA, JDBC, etc.

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.

A spring module 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/Intellij Idea 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.

Prerequisite of Spring Boot

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

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

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
Spring Boot Modules

1. What is starter template?

Spring Boot starters are templates that contain a collection of all the relevant
transitive dependencies that are needed to start a particular functionality. For example,
If you want to create a Spring WebMVC application then in a traditional setup, you
would have included all required dependencies yourself. It leaves the chances of version
conflict which ultimately result in more runtime exceptions.

With Spring boot, to create MVC application all you need to import is spring-boot-
starter-web dependency.
Above spring-boot-starter-web dependency, internally imports all given dependencies and
add to your project. Notice how some dependencies are direct, and some dependencies further
refer to other starter templates which transitively downloads more dependencies.

Also, notice that you do not need to provide version information into child dependencies.
All versions are resolved in relation to version of parent starter (in our example
it’s 2.0.4.RELEASE).
2. Spring boot auto configuration

Auto configuration is enabled with @EnableAutoConfiguration annotation. Spring boot


auto configuration scans the classpath, finds the libraries in the classpath and then
attempt to guess the best configuration for them, and finally configure all such beans.

Auto-configuration tries to be as intelligent as possible and will back-away as you define


more of your own configuration.

Auto-configuration is always applied after user-defined beans have been registered.


3. Embedded server

Spring boot applications always include tomcat as embedded server dependency. It


means you can run the Spring boot applications from the command prompt without
needling complex server infrastructure.

You can exclude tomcat and include any other embedded server if you want. Or you can
make exclude server environment altogether. It’s all configuration based.

For example, below configuration exclude tomcat and include jetty as embedded
server.

4. Bootstrap the application

To run the application, we need to use @SpringBootApplication annotation. Behind

the scenes, that’s equivalent to @Configuration, @EnableAutoConfiguration,


and @ComponentScan together.

It enables the scanning of config classes, files and load them into spring context. In
below example, execution start with main() method. It start loading all the config files,
configure them and bootstrap the application based on application

properties in application.properties file in /resources folder.

To execute the application, you can run the main() method from IDE such eclipse, or you can
build the jar file and execute from command prompt.

How starter template work?

Spring Boot starters are templates that contain a collection of all the relevant transitive
dependencies that are needed to start a particular functionality. Each starter has a
special file, which contains the list of all the provided dependencies Spring provides.

These files can be found inside pom.xml files in respective starter module. e.g.

The spring-boot-starter-data-jpa starter pom file can be found at github.

This tells us that by including spring-boot-starter-data-jpa in our build as a


dependency, we will automatically get spring-orm, hibernate-entity-
manager and spring-data-jpa. These libraries will provide us all basic things to start
writing JPA/DAO code .

So next time when you want to give your project any specific functionality, I will suggest
to check for existing starter templates to see if you can use it directly. Ongoing
community additions are always on, so this list is already growing and you can
contribute to it as well.

Popular templates and their transitive dependencies

I am listing down some very frequently use spring starters and what dependencies they
bring along, for information only.
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.

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

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


used by Spring Containers as a source of bean definitions.

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

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

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

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

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

Spring Boot Annotations

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

@SpringBootApplication: It is a combination of three


annotations @EnableAutoConfiguration, @ComponentScan, and @Configuration.

Spring MVC and REST Annotations

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

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

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

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

@PatchMapping: It maps the HTTP PATCH requests on the specific handler method. It is
used instead of using: @RequestMapping(method = RequestMethod.PATCH)

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

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

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

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

@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

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

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

Spring boot @Scheduled annotation

Spring provides excellent support for both task scheduling and asynchronous method
execution based on cron expression using @Scheduled annotation. The @Scheduled
annotation can be added to a method along with trigger metadata.

Spring @Scheduled Annotation

To schedule job in spring boot application to run periodically, spring boot


provides @EnableScheduling and @Scheduled annotations. Lets learn to use Spring boot
@Scheduled annotation.

Let’s say you want to run job at every 10 seconds interval. You can achieve this job
scheduling in below steps:

1. Add @EnableScheduling to Spring Boot Application class

Add @EnableScheduling annotation to your spring boot application


class. @EnableScheduling is a Spring Context module annotation. It internally imports
the SchedulingConfiguration via the @Import(SchedulingConfiguration.class) instruction
2. Add Spring boot @Scheduled annotations to methods

Now you can add @Scheduled annotations on methods which you want to schedule. Only
condition is that methods should be without arguments.

ScheduledAnnotationBeanPostProcessor that will be created by the


imported SchedulingConfiguration scans all declared beans for the presence of
the @Scheduled annotations.

For every annotated method without arguments, the appropriate executor thread pool will
be created. This thread pool will manage the scheduled invocation of the annotated method.

2.1. Schedule task at fixed rate

Execute a task at a fixed interval of time:


@Scheduled(initialDelay = 1000, fixedRate = 10000)

public void run() {

logger.info("Current time is :: " + Calendar.getInstance().getTime());

2.2. Schedule task at fixed delay

Configure a task to run after a fixed delay. In given example, the duration between the
end of last execution and the start of next execution is fixed. The task always waits until
the previous one is finished.
@Scheduled(fixedDelay = 10000)

public void run() {

logger.info("Current time is :: " + Calendar.getInstance().getTime());

}
2.3. Spring boot cron job example

@Scheduled annotation is very flexible and may take cron expression as well.
@Scheduled(cron = "0 10 10 10 * ?")

public void run() {

logger.info("Current time is :: " + Calendar.getInstance().getTime());

You might also like