Spring Boot (1)

You might also like

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 43

Spring Boot

Spring Boot is an open-source Java framework which provides the RAD (Rapid Application Development)
feature to the Spring framework. Spring Boot is a project that is built on the top of the Spring Framework
and contains all the features of spring. It is becoming a favorite of developers these days because of its
rapid production-ready environment which enables the developers to directly focus on the logic instead of
struggling with the configuration and setup. It provides an easier and faster way to set up, configure, and
run both simple and web-based applications. it needs minimal Spring configuration.

Applications can freely focus on the business while Spring Boot takes care of the rest.

In short, Spring Boot is the combination of Spring Framework and Embedded Servers.
Spring Boot is yet another popular Spring project. In 2012, a feature request was
to enable container-less applications using Spring Framework. The Spring
Developers developed an entire framework around the feature request and
named it Spring Boot (2014).

You don’t need an external container to run a Spring Boot application. That is
because Spring Boot comes with an inbuilt container. A Spring Boot application
has the ‘public static void main(String[] a)‘ method that bootstraps various
Spring Boot beans, inbuilt containers, and other components.
You can choose Spring Boot because of the • It reduces the cost and development time of the
features and benefits it offers as given here application.

• It provides a powerful batch processing and manages
• In Spring Boot, there is no requirement for XML REST endpoints.
configuration (deployment descriptor).
• In Spring Boot, everything is auto configured; no
manual configurations are needed.
• It uses convention over configuration software
design paradigm that means it decreases the
• It offers annotation-based spring application
effort of the developer.
• Eases dependency management
• The dependency injection approach is used in
Spring Boot. • It includes Embedded Servlet Container

• It contains powerful database transaction


management capabilities.

• It simplifies integration with other Java


frameworks like JPA/Hibernate ORM, Struts, etc.
• We can use Spring STS(Spring Tool Suite) IDE or Spring Initializr to develop
Spring Boot Java applications.

• Spring Tools 4 is the next generation of Spring tooling for your favorite coding
environment. Largely rebuilt from scratch, it provides world-class support for
developing Spring-based enterprise applications, whether you prefer Eclipse,
Visual Studio Code, or Theia IDE.

• Initializr generates spring boot project with just what you need to start quickly.
Prerequisite of Spring Boot

Understanding of Java syntax and core concepts such as classes, objects,


inheritance, interfaces, and exception handling

Basic understanding of the Spring framework

Knowledge of Web Technologies

Familiarity with build tools such as Maven or Gradle


Spring Boot Features
Faster Development: Spring Boot cuts off the initial setup, development, and deployment
time. Because Spring Boot is capable of running on minimal configurations and gives a
hassle-free development experience.

Spring Boot is Opinionated: Spring Boot is so smart that if we don’t provide certain
configurations, Spring Boot uses defaults. For instance, even if you don’t provide a database
driver and respective configurations, Spring Boot will start with an in-memory database.
However, when you provide our configurations, Spring Boot will respect them and take out
the auto-configurations for the respective components.

Production Ready: Spring Boot applications are bootstrapped from the main method. How
you run a Spring Boot application locally is the same as you do for a Production Box. In
addition, having a Strong properties management mechanism provides a structured way to
externalise environment-specific properties making it easy to deploy the same jar to any
box. It only needs JRE to run a Spring Boot Application.
In-built Container: No need to deploy the application archive to any external
containers and configure the servers. Spring Boot has an inbuilt tomcat bootstrapped
from the application’s main method. Starting the whole application is as simple as
‘java -jar‘.

Version Management: Spring Boot uses the spring.io platform for version
compatibility. This means we need to specify the Spring Boot version we want to use,
and Spring will find and install compatible libraries.

Actuators: Visit our detailed posts on actuators: Spring Boot Actuator with Spring Boot
2 and Spring Boot Actuator in old Spring Boot (1.x).
Spring-Boot Build System
Any software system needs a build system to generate a deployable artefact.
For example, the artefact for java based applications can be JAR, WAR, or EAR.
The build tool helps in building the application and creating the artefact.
Though many build tools exist in the market, maven and Gradle are most
popular.

It is strongly recommended that you choose a build system that supports


dependency management and that can consume artifacts published to the
“Maven Central” repository.

We would recommend that you choose Maven or Gradle. It is possible to get


Spring Boot to work with other build systems (Ant, for example), but they are
not particularly well supported.
Maven

Maven is a build and dependency manager. Basically, it allows you to build your
code, while managing your dependencies for you so that you don't have to
download jars manually.

Maven is an open-source build automation and project management tool


widely used for Java applications. As a build automation tool, it automates the
source code compilation and dependency management, assembles binary
codes into packages, and executes test scripts.
Maven users can inherit from the spring-boot-starter-parent project to obtain
sensible defaults. The parent project provides the following features:

• Java 1.6 as the default compiler level.


• UTF-8 source encoding.
• A Dependency Management section, allowing you to omit <version> tags for
common dependencies, inherited from the spring-boot-dependencies POM.
• Sensible resource filtering.
• Sensible plugin configuration (exec plugin, surefire, Git commit ID, shade).
• Sensible resource filtering for application.properties and application.yml
On the last point: since the default config files accept Spring style placeholders
(${…​}) the Maven filtering is changed to use @..@ placeholders (you can
override that with a Maven property resource.delimiter).
Inheriting the starter parent
For Maven configuration, we should inherit the spring-boot-starter-parent project to manage the Spring Boot
Starters dependencies. For this, simply we can inherit the starter parent in our pom.xml file as shown below.

<!-- Inherit defaults from Spring Boot -->


<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.8.RELEASE</version>
</parent>

We should specify the version number for Spring Boot Parent Starter dependency. For other starter dependencies,
we do not need to specify the Spring Boot version number. Observe the code given below −
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
Using Spring Boot without the parent POM
Not everyone likes inheriting from the spring-boot-starter-parent POM. You may have your own corporate
standard parent that you need to use, or you may just prefer to explicitly declare all your Maven
configuration. If you don’t want to use the spring-boot-starter-parent, you can still keep the benefit of the
dependency management (but not the plugin management) by using a scope=import dependency:

<dependencyManagement>
<dependencies>
<dependency>
<!-- Import dependency management from Spring Boot -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>1.3.8.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
That setup does not allow you to override individual
<dependency>
dependencies using a property as explained above. To
<groupId>org.springframework.boot</groupId>
achieve the same result, you’d need to add an entry in
<artifactId>spring-boot-dependencies</artifactId>
the dependencyManagement of your project before
the spring-boot-dependencies entry. For instance, to <version>1.3.8.RELEASE</version>
upgrade to another Spring Data release train you’d <type>pom</type>
add the following to your pom.xml. <scope>import</scope>
</dependency>
<dependencyManagement> </dependencies>
<dependencies> </dependencyManagement>
<!-- Override Spring Data release train provided
by Spring Boot -->
<dependency>
<groupId>org.springframework.data</groupId>

<artifactId>spring-data-releasetrain</artifactId>
<version>Fowler-SR2</version>
<scope>import</scope>
<type>pom</type>
</dependency>
Changing the Java version
The spring-boot-starter-parent chooses fairly conservative Java compatibility. If
you want to follow our recommendation and use a later Java version you can
add a java.version property:

<properties>
<java.version>1.8</java.version>
</properties>
Using the Spring Boot Maven plugin
Spring Boot includes a Maven plugin that can package the project as an executable jar. Add
the plugin to your <plugins> section if you want to use it:

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

If you use the Spring Boot starter parent pom, you only need to add the plugin, there is no
need for to configure it unless you want to change the settings defined in the parent.
Gradle

Gradle is a build automation tool known for its flexibility to build software. A
build automation tool is used to automate the creation of applications. The
building process includes compiling, linking, and packaging the code. The
process becomes more consistent with the help of build automation tools.

It is popular for its ability to build automation in languages like Java, Scala,
Android, C/C++, and Groovy. The tool supports groovy based Domain
Specific Language over XML. Gradle provides building, testing, and deploying
software on several platforms.
We can import the Spring Boot Starters dependencies directly into build.gradle file.
We do not need Spring Boot start Parent dependency like Maven for Gradle. Observe the code given below −

buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}

repositories {
mavenCentral()
}

dependencies {
classpath("org.springframework.boot:spring-boot-gradle-plugin:1.3.8.RELEASE")
}
}

Similarly, in Gradle, we need not specify the Spring Boot version number for dependencies. Spring Boot
automatically configures the dependency based on the version.
The spring-boot-gradle-plugin is also available apply plugin: 'java'
and provides tasks to create executable jars apply plugin: 'spring-boot'
and run projects from source.
repositories {
It also provides dependency management jcenter()
that, among other capabilities, allows you to }
omit the version number for any
dependencies that are managed by Spring dependencies {
Boot: compile("org.springframework.boot:spring-boot-starter-
web")
buildscript { testCompile("org.springframework.boot:spring-boot-
starter-test")
repositories {
}
jcenter()
}

dependencies {

classpath("org.springframework.boot:spring-
boot-gradle-plugin:1.3.8.RELEASE")
}
}
Starter POMs

Starter POMs are a set of convenient dependency descriptors that you can include in your application. You
get a one-stop-shop for all the Spring and related technology that you need, without having to hunt through
sample code and copy paste loads of dependency descriptors. For example, if you want to get started using
Spring and JPA for database access, just include the spring-boot-starter-data-jpa dependency in your project,
and you are good to go.

The starters contain a lot of the dependencies that you need to get a project up and running quickly and
with a consistent, supported set of managed transitive dependencies.

All official starters follow a similar naming pattern; spring-boot-starter-*, where * is a particular type of
application. This naming structure is intended to help when you need to find a starter. The Maven
integration in many IDEs allow you to search dependencies by name. For example, with the appropriate
Eclipse or STS plugin installed, you can simply hit ctrl-space in the POM editor and type “spring-boot-starter”
for a complete list.

As explained in the Creating your own starter section, third party starters should not start with spring-boot
as it is reserved for official Spring Boot artifacts. A third-party starter for acme will be typically named acme-
spring-boot-starter.
The following application starters are provided by Spring Boot under the
org.springframework.boot group:
Name Description
spring-boot-starter The core Spring Boot starter, including auto-configuration support, logging and YAML.

spring-boot-starter-actuator Production ready features to help you monitor and manage your application.

spring-boot-starter-amqp Support for the “Advanced Message Queuing Protocol” via spring-rabbit.

spring-boot-starter-aop Support for aspect-oriented programming including spring-aop and AspectJ.

spring-boot-starter-artemis Support for “Java Message Service API” via Apache Artemis.

spring-boot-starter-batch Support for “Spring Batch” including HSQLDB database.


spring-boot-starter-cache Support for Spring’s Cache abstraction.
spring-boot-starter-cloud-connectors Support for “Spring Cloud Connectors” which simplifies connecting to services in cloud
platforms like Cloud Foundry and Heroku.

spring-boot-starter-data-elasticsearch Support for the Elasticsearch search and analytics engine including spring-data-
elasticsearch.
spring-boot-starter-data-gemfire Support for the GemFire distributed data store including spring-data-gemfire.

spring-boot-starter-data-jpa Support for the “Java Persistence API” including spring-data-jpa, spring-orm and Hibernate.
spring-boot-starter-data-mongodb Support for the MongoDB NoSQL Database, including spring-data-mongodb.

spring-boot-starter-data-rest Support for exposing Spring Data repositories over REST via spring-data-rest-
webmvc.
spring-boot-starter-data-solr Support for the Apache Solr search platform, including spring-data-solr.

spring-boot-starter-freemarker Support for the FreeMarker templating engine.


spring-boot-starter-groovy-templates Support for the Groovy templating engine.
spring-boot-starter-hateoas Support for HATEOAS-based RESTful services via spring-hateoas.

spring-boot-starter-hornetq Support for “Java Message Service API” via HornetQ.


spring-boot-starter-integration Support for common spring-integration modules.
spring-boot-starter-jdbc Support for JDBC databases.
spring-boot-starter-jersey Support for the Jersey RESTful Web Services framework.
spring-boot-starter-jta-atomikos Support for JTA distributed transactions via Atomikos.
spring-boot-starter-jta-bitronix Support for JTA distributed transactions via Bitronix.
spring-boot-starter-mail Support for javax.mail.
spring-boot-starter-mobile Support for spring-mobile.
spring-boot-starter-mustache Support for the Mustache templating engine.
spring-boot-starter-redis Support for the REDIS key-value data store, including spring-redis.

spring-boot-starter-security Support for spring-security.


spring-boot-starter-social-facebook Support for spring-social-facebook.
spring-boot-starter-social-linkedin Support for spring-social-linkedin.
spring-boot-starter-social-twitter Support for spring-social-twitter.
spring-boot-starter-test Support for common test dependencies, including JUnit, Hamcrest and Mockito along
with the spring-test module.

spring-boot-starter-thymeleaf Support for the Thymeleaf templating engine, including integration with Spring.

spring-boot-starter-velocity Support for the Velocity templating engine.


spring-boot-starter-web Support for full-stack web development, including Tomcat and spring-webmvc.

spring-boot-starter-websocket Support for WebSocket development.


spring-boot-starter-ws Support for Spring Web Services.
Spring Boot technical starters

Name Description
spring-boot-starter-jetty Imports the Jetty HTTP engine (to be used as an
alternative to Tomcat).
spring-boot-starter-log4j Support the Log4J logging framework.
spring-boot-starter-logging Import Spring Boot’s default logging framework (Logback).

spring-boot-starter-tomcat Import Spring Boot’s default HTTP engine (Tomcat).


spring-boot-starter-undertow Imports the Undertow HTTP engine (to be used as an
alternative to Tomcat).
Spring Boot Starter Security dependency is used for Spring Boot Starter Thyme Leaf dependency is used to
create a web application. Its code is shown below −
Spring Security. Its code is shown below −
<dependency>
<dependency> <groupId>org.springframework.boot</groupId>
<groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Spring Boot Starter Test dependency is used for
writing Test cases. Its code is shown below −
Spring Boot Starter web dependency is used to
write a Rest Endpoints. Its code is shown below − <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<dependency> </dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Spring Boot Code Structure
Spring Boot does not have any code layout to work with. However, there are
some best practices that will help us.
Default package
A class that does not have any package declaration is considered as a default
package. Note that generally a default package declaration is not
recommended. Spring Boot will cause issues such as malfunctioning of Auto
Configuration or Component Scan, when you use default package.

Note − Java's recommended naming convention for package declaration is


reversed domain name like moodle.kiet.edu\moodle

For example − com.tutorialpoint.myproject


The typical layout of Spring Boot application is shown in the image given below −

The Application.java file should declare the main


method along with @SpringBootApplication. Observe
the code given below for a better understanding −

package com.tutorialspoint.myproject;

import org.springframework.boot.SpringApplication;
import
org.springframework.boot.autoconfigure.SpringBootApplicatio
n;

@SpringBootApplication
public class Application {
public static void main(String[] args)
{SpringApplication.run(Application.class, args);}
}
Spring Boot Runners
Spring Boot provides two runner interfaces

1. ApplicationRunner and
2. CommandLineRunner

Being Functional Interfaces, both the runners have a single functional method,
run().
When we implement one of these runners, Spring Boot invokes its run() method
just after applicationcontext is created and before spring boot application startup.

That means we can use Spring Boot CommandLineRunner or ApplicationRunner to


execute a piece of code when launching an Application.
CommandLineRunner Interface used to indicate that a bean should run when it is contained within a
SpringApplication. Multiple CommandLineRunner beans can be defined within the same application
context and can be ordered using the Ordered interface or @Order annotation.

ApplicationRunner Interface used to indicate that a bean should run when it is contained within a
SpringApplication. Multiple ApplicationRunner beans can be defined within the same application
context and can be ordered using the Ordered interface or @Order annotation.

The only difference between the two interfaces is the signature of the run() method. The run() method
in the CommandLineRunner receives the application or program argument as an array of String.

void run(String... args)

However, the run() method in ApplicationRunner receives the program arguments wrapped in an
ApplicationArguments instance. The ApplicationArguments provides convenient methods to access the
program arguments.

void run(ApplicationArguments args)


Example of Spring Boot ApplicationRunner
To execute a block of code during a Spring Boot application startup using ApplicationRunner, we need
either a Spring Bean or the @SpringBootApplication class implementing the ApplicationRunner interface.
The following is an example of Spring Boot ApplicationRunner implementation that prints all the program
arguments to the console. Please note that the class uses one of Spring’s stereotype annotations.

import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

@Component
public class ApplicationRunnerImpl
implements ApplicationRunner {

@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner; arguments: ");
}}
Example of Spring Boot Command Line Runner
Similarly, to use a CommandLineRunner to invoke a block of code at a Spring Boot application startup, we
must have a Spring Bean or the @SpringBootApplication implementing the interface.

The following is an example of Spring Boot CommandLineRunner implementation that prints all the program
arguments to the console.
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class CommandLineRunnerImpl
implements CommandLineRunner {

@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner; arguments: ");
}
}
Multiple Spring Boot Runners and their Execution Order
Spring Boot allows us to have multiple implementations of both runners, and both CommandLineRunner and ApplicationRunner
can coexist in our application. When we have multiple Spring Beans implementing either of the runner interfaces, Spring
executes their run() method one after the other based on the order of the bean discovery. Spring, however, allows us to use the
@Order annotation to set a custom order of the execution for the Spring Boot Runners. To try it, let’s create a
CommandLineRunner implementation with @Order of 1, which indicates the highest priority.

@Order(1)
@Component
public class CommandLineRunnerImpl
implements CommandLineRunner {
...
}

Next, let’s create an ApplicationRunner implementation with @Order of 2, which is a lower priority.

@Order(2)
@Component
public class ApplicationRunnerImpl
implements ApplicationRunner {
...
}
When to use Spring Boot Runners?
As stated, we can use Spring Boot runners to run a piece of code at the application startup time. Although it
may sound simple, runners can perform crucial tasks. The most important thing about the Spring Boot
Runners is that they run only after the Spring context is entirely available. That means both
CommandLineRunner and ApplicationRunner interfaces can use powerful features like auto-wiring,
dependency injection etc. Following are a couple of Spring Boot Runner use cases.

Setting up Application Level Constants


Applications often must maintain constants or static variables that remain unchanged throughout the
application life cycle. Typically, such application-level constants are read from external entities like databases,
file systems, or a third-party data provider service. Spring Boot runners are the best place to fetch the
constants from external resources and build a local cache.

Initialize Resources
We can also use Spring Boot Runners to initialize various resources to the particular state required by the
application. For example, an application may want to execute a few database commands during the startup.

Creating Non-Web Console Application


Also, we can use Spring Boot Runners to build Console applications with Spring Boot. Console applications are
non-web applications that we can run to perform a particular task.
Example of non-web program in spring boot:

Service Class
Let’s create a Service component for our application. This service class is responsible for
performing application tasks. Thanks to Spring, we can use one of Spring’s stereotype
annotations to make this class a Spring bean and auto-wire it in the @SpringBootApplication
class.

@Service
public class NonWebService {
public void printMessage(String[] args) {
System.out.println("Started with arguments: ");
Arrays.stream(args).forEach(System.out::println);
}
}
Application Class
Lastly, we will create the Application class. All Spring Boot applications bootstrap from the main() method in the
@SpringBootApplication class. Our Application class implements the CommandLineRunner interface, one of the Spring Boot
Runners, and overrides its run() method. When we launch the Application, Spring Boot starts the Spring context, loads the
required beans and their dependencies and invokes the run method with the original arguments to the main() method.
We invoke our service method from the run() method.

@SpringBootApplication
public class Application implements CommandLineRunner {
@Autowired
private NonWebService ser;
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}

@Override
public void run(String... args) throws Exception {
ser.printMessage(args);
}
}
$ java -jar spring-boot-command-line.jar \
My first Spring Boot Non-Web Application
Spring Boot Logger
Logging in Spring Boot plays a vital role in Spring Boot applications for recording information, actions, and events
within the app.

It is also used for monitoring the performance of an application, understanding the behavior of the application,
and recognizing the issues within the application.

Spring Boot offers flexible logging capabilities by providing various logging frameworks and also provides ways to
manage and configure the logs.

Spring Boot uses Apache Commons Logging for internal logging but allows developers to configure the
underlying log implementation. Various logging providers are supported through simple configuration.

Spring Boot provides default configurations for Java Util Logging, Log4J2 and Logback. Each logging provider is
preconfigured to use console output with optional file output available as well. Spring Boot applications need to
collect log data to help troubleshoot and fix issues in code, as well as measure business metrics.
Logging refers to the practice of gathering and managing log messages
generated by a software application during its runtime. Spring Boot offers a
flexible logging framework that allows developers to configure and control how
log messages are generated, formatted, and stored. This logging framework is
built on top of the popular SLF4J (Simple Logging Facade for Java) and Logback
libraries.

In simple words, Logging is a basic practice in software development process


that offers developers an understanding of what is happening within a program.
Elements of Logging Framework
• Logger: It captures the messages.
• Formatter: It formats the messages which are captured by loggers.
• Handler: It prints messages on the console, stores them in a file or sends an
email, etc.

Java provides several logging frameworks, some of which are:

• Logback Configuration logging


• Log4j2 Configuration logging
• Logging with Lombok
• @Slf4j and @CommonsLog
Spring Boot contains different logging levels to classify the log messages.

The common log levels are DEBUG, INFO, WARN, ERROR, and TRACE.
We can choose the suitable log level for a specific message based on our
requirement & its importance.
By default, Spring Boot uses Logback as the default logging framework, but it is
also capable of supporting other common logging frameworks like Log4j2 and
JUL (Java Util Logging) etc. We can configure the required logging
implementation by adding the corresponding dependency to our project’s build
configuration.

Logger
A logger is an object that allows us to generate log messages within the
application. Loggers are part of the logging framework provided by Spring Boot
and are used to record various events, activities, and information during the
runtime of our application. These log messages provide information into the
behavior of our application, assist in troubleshooting, and help in monitoring
and maintaining the application’s health.
Logger Interface
Spring Boot internally uses the Logger interface from the SLF4J (Simple Logging
Facade for Java) library as the primary abstraction for creating log messages.
We need to connect with the logger interface to generate log messages in our
code.
Spring Boot – Annotations
Spring Boot Annotations are a form of metadata that provides data about a spring
application.

Spring Boot is a microservice-based framework and making a production-ready application


in it takes very little time. Following are some of the features of Spring Boot:

It allows for avoiding heavy configuration of XML which is present in the spring
It provides easy maintenance and creation of REST endpoints
It includes embedded Tomcat-server
Deployment is very easy, war and jar files can be easily deployed in the Tomcat server
Annotations are used to provide supplemental information about a program. 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. So in this article, we are going to discuss some important
Spring Boot Annotations that are available in Spring Boot with examples.

You might also like