Spring Boot
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
• 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
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.
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.
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-artemis Support for “Java Message Service API” via Apache Artemis.
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-thymeleaf Support for the Thymeleaf templating engine, including integration with Spring.
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).
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.
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.
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.
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.
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.
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.
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.
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.