46,44 €
Develop diverse real-life projects including most aspects of Spring Boot
Key Features
Book Description
Spring is one of the best tools available on the market for developing web, enterprise, and cloud-ready software. The goal of Spring Boot is to provide a set of tools for quickly building Spring applications that are easy to configure, and that make it easy to create and run production-grade Spring-based applications. Spring Boot 2.0 Projects will get you acquainted with important features of the latest version of this application-building tool and will cover basic, as well as advanced topics.
The book starts off by teaching you how to create a web application using Spring Boot, followed by creating a Spring Boot-based simple blog management system that uses Elasticsearch as the data store. As you make your way through the chapters, you'll build a RESTful web services application using Kotlin and the Spring WebFlux framework. Spring WebFlux is a new framework that helps in creating a reactive application in a functional way. Toward the end of the book, you will build a taxi-hailing API with reactive microservices using Spring Boot and a Twitter clone with a Spring Boot backend. Finally, you'll learn how to build an asynchronous email formatter.
What you will learn
Who this book is for
This book is for competent Spring developers who wish to understand how to develop complex yet scalable applications with Spring Boot. You must have a good knowledge of Java programming and be familiar with the basics of Spring.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 296
Veröffentlichungsjahr: 2018
Copyright © 2018 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Richa TripathiAcquisition Editor: Sandeep MishraContent Development Editor: Tiksha SarangTechnical Editor: Supriya ThabeCopy Editor: Safis EditingProject Coordinator: Prajakta NaikProofreader: Safis EditingIndexer: Rekha NairGraphics: Jisha ChirayilProduction Coordinator: Aparna Bhagat
First published: July 2018
Production reference: 1260718
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78913-615-9
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com, and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
Mohamed Shazin Sadakath is an experienced software engineer with over 9 years of software development experience in J2SE-, J2EE-, and Spring-based applications. He is a BSc (Hons) software engineering graduate, having achieved first class honors. He has worked in different domains, ranging from telecommunications to real estate. In his spare time, he contributes to open source projects, such as Spring Security, and writes technical articles for blogs. He is a Stack Overflow Moderator and loves answering Java-related questions.
Gunith Eranda Devasurendra is a senior software engineer with 10 years, professional development experience, specializing in Java. Born in Sri Lanka, he became interested in programming as he considers elegant programming and design to be an art form. Gunith has a master's in computer science awarded by the University of Colombo. He is a speaker and a trainer on technical topics including Spring, and Git. He is also an advocate of FOSS. Gunith also helps out in the Stack Overflow community.
Biharck Araújo has been working as a principal software architect and lead programmer for the past 15 years. He is passionate about technology and academic research. He has been working with JavaEE technology for web projects that demand high-security standards in terms of information transmission for companies across different sectors. He has extensive experience in activities regarding software architecture. He works in bioinformatics using technology in life's favor.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Spring Boot 2.0 Projects
Dedication
Packt Upsell
Why subscribe?
PacktPub.com
Contributors
About the author
About the reviewers
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
Introduction
Technical requirements
Generating Spring Boot Projects
Opening the generated project with IntelliJ
Opening the generated project with STS
Getting started with Spring Boot
Learning about Spring Boot
Anatomy of a Spring Boot application
Supporting the Spring Framework ecosystem in Spring Boot
Changes since Spring Boot 1.x
Registering a Spring Bean using ApplicationContextInitializer
Configuration property binding
New property binding API
Property origin
Tightened rules for governing relaxed property binding
Environment variables with indices
Direct binding of property type java.time.Duration in the ISO-8601 form
Custom endpoints for Spring Boot Actuator using annotations
Exposing a custom Spring Boot Actuator endpoint
Extending a custom endpoint with a specialized implementation for the web
Connecting to a custom endpoint using monitoring and management tools
Custom metrics using Micrometer
Custom health indicator
Using the HTTP/2 protocol
Securing applications with Spring Security
The next milestone
Migration
Using the correct JDK and JVM
Running on Java 9
Tackling JAXBException
Using the correct AspectJ version
Being aware of limitations on Apache Cassandra drivers
Being aware of issues with the Maven Surefire Plugin
Using the upgraded Spring Framework 5.0
Modified CORS support behavior
Removed packages, classes, and methods
Dropped support for frameworks
Using the updated configuration properties
Using the changed servlet-specific server properties
Using the modified template engine extension handling
Using the changed actuator configuration properties
Using the changed actuator base path
Using the renamed actuator endpoints
Using the changed Embedded Container Configuration 
Using the changed default behavior for path mapping
Using the changed default dispatcher types for the servlet filter 
Using the modified transitive dependency to spring-boot-web-starter
Using the changed default proxying strategy 
Using the modified configuration location strategy
Using the changed Jackson/JSON support
Using the changed Spring Boot Actuator security
Using the changed HikariCP default connection pool for JPA
Using the changed default database initialization strategy
Using the changed database schema creation strategy
Using the changed testing support
Using the revised Spring Security
Using the changed default security auto-configuration strategy
Spring Security OAuth2 is migrated to Spring Security core 
Using the AuthenticationManager bean 
Understanding removed features
Summary
Questions
Further reading
Building a Basic Web Application
Technical requirements
Getting started
Web application architecture
Workflow of Spring Web MVC 
Requirements for our web application
The use case diagram 
Using Spring Data JPA for persistence
Understanding the Java Persistence API (JPA)
Understanding Spring Data JPA
Class diagram for the domain model
Implementation of the domain model using JPA annotations
Setting up dependencies and configuration
Implementing the domain model
Implementation of Spring Data JPA repositories
Testing Spring Data JPA repositories
Using Spring Boot Devtools for database visualization
Using Services to encapsulate business logic
Testing Services
Using Spring Thymeleaf for the view
Understanding template engines
Spring Thymeleaf 
UI design for the Retro Board
UI implementation for the Retro Board using Spring Thymeleaf
Using Spring Web MVC with servlet 3.x for the controller
Implementation of Controllers annotations
Testing controllers
Using Spring Security for authentication and authorization
Demonstrating the Retro Board
Summary
Questions
Further reading
Building a Simple Blog Management System
Technical requirements
Getting started
Web application architecture
Workflow of Spring WebFlux
Requirements of the Bloggest system
The use case diagram 
Using Spring Data Elasticsearch for persistence
Understanding Elasticsearch
Understanding Spring Data Elasticsearch
Class diagram for the domain model
Implementation of the domain model using Spring Data Elasticsearch annotations
Setting up dependencies and configuration classes
Implementing the domain model
Implementation of Spring Data Elasticsearch repositories
Using Apache FreeMarker for the view
Understanding template engines
Apache FreeMarker
UI design for Bloggest
UI implementation for Bloggest using Apache FreeMarker
Implementing a common layout using Apache FreeMarker
Implementing a List Articles page
Implementing a Create Article page
Implementing a Show Article page
Implementing an error page
Using Spring WebFlux for controller
Implementation of controllers
Implementation of ControllerAdvice
Using Spring Security for authentication and authorization
Demonstrating Bloggest
Summary
Questions
Further reading
Introduction to Kotlin
Technical requirements
Getting started with Kotlin
Default imports
Basic data types
Numeric data types
Learning numeric literals
Numeric representation
Numeric operations
String literals
The syntax for Kotlin code
The Kotlin packages
String interpolation
Functions in Kotlin
Variables in Kotlin
Conditional statements
The if statement
The when statement 
Type checking and automatic casting
Nullable values and compile-time null safety 
The for loop
The for loop with an array
The for loop with a collection
The for loop with a value range
The while loop
Object-oriented programming with Kotlin
Learning about visibility modifiers
Classes in Kotlin
Abstract classes
Concrete classes
The concept of interfaces in Kotlin
Learning about extensions
Generic types in Kotlin
Enums in Kotlin
Objects in Kotlin
Object expressions
Object declarations
Companion objects
Advanced programming with Kotlin
Functions
Infix notation in functions
Local functions in Kotlin
Default arguments in functions
Named arguments in functions
Generics in functions
Variable number of arguments (vararg) in functions
Summary
Questions
Further reading
Building a Reactive Movie Rating API Using Kotlin
Technical requirements
Getting started
REST architecture
Requirements of REST architecture
The use case diagram
Using Spring Data MongoDB for persistence
Understanding MongoDB 
Understanding Spring Data MongoDB
Class diagram for the domain model
Implementation of the domain model using Spring Data MongoDB annotations
Setting up dependencies and configuration
Implementing the domain model
Implementing of Spring Data MongoDB repositories
Using a service to encapsulate business logic
Testing Services
Using Spring WebFlux for controllers
Implementation of controllers
Testing controllers
Using Spring Security for basic authorization
Demonstrating Moviee
Integration testing
Demonstrating the use of Postman
Accessing the List Movies endpoint
Accessing the Get Movie endpoint
Accessing the Get Movie endpoint with an invalid Movie ID
Accessing the Rate Movie endpoint
Summary
Questions
Further reading
Building an API with Reactive Microservices
Technical requirements
Getting started
Microservices architecture
The requirements of microservices architecture
The use case diagram
The project structure to develop microservices
Using Spring Data Redis for persistence
Understanding Redis
Understanding Spring Data Redis
Class diagram for the domain model
Implementation of domain model using Spring Data Redis annotations
Setting up dependencies and configuration
 Implementing the domain model
Implementation of Spring Data Redis repositories
Using a Service to encapsulate business logic 
Using Spring WebFlux for a controller
Implementation of controllers
Using asynchronous data transfer for cross-microservice communication
Asynchronous data transfer using Redis
Using Docker to support microservices
Understanding Docker
Using Maven to build Docker images
Building a system of microservices with Docker
Deploying microservices with Docker
Demonstrating Saber
Submitting to the Register Taxi endpoint
Submitting location to update Taxi Location endpoint
Submitting to Update Taxi Status endpoint
Accessing the Get Taxi Status endpoint
Accessing the GET available Taxis endpoint
Submitting to Book Taxi endpoint
Submitting to Accept Taxi Booking endpoint
Submitting to cancel Taxi Booking endpoint
Accessing Taxi Bookings endpoint
Summary 
Questions
Further reading
Building a Twitter Clone with Spring Boot
Technical requirements
Getting started
Beginning with the Tweety architecture
Tweety requirements
The use case diagram
Using Spring Data JPA for persistence
Class diagram for the domain model
Implementation of the domain model using Spring Data JPA annotations
Setting up dependencies and configuration
Implementing the domain model
Implementing Spring Data JPA repositories
Caveat for going reactive with blocking JDBC 
Using Service to encapsulate business logic 
Using Angular 5 for the frontend
Getting started with Angular 5 application development
Generating Angular services
Generating the users service
Generating Angular page components
Generating the Tweets Add page
Generating the User Profile page
Using Spring Web Flux for the REST controller
Implementing controllers
Enabling Angular frontend access to controllers
Using Spring Security for authentication and authorization
Understanding OAuth2 
Setting up dependencies and configuration
Configuring the Resource Server
Configuring the Authorization Server
Configuring web security
Using an Angular service for OAuth2 authentication and authorization
Demonstrating Tweety
Accessing the login page
Accessing the List Tweets page
Accessing the Send Tweet page
Accessing the User Profile page
Summary
Questions
Further reading
Introducing Spring Boot 2.0 Asynchronous
Technical requirements
Getting started
Synchronous applications
Asynchronous applications
The requirement of asynchronous applications
The use case diagram
The architecture of an image resizing application
Using Spring Kafka for communication
Understanding Apache Kafka
Setting up dependencies and configuration
Configuration for the Image Resize Request Producer
Configuration for Image Resize Request Consumer
Starting Spring Boot applications in a non-web mode
Using Quartz for scheduling
Understanding Quartz
Setting up dependencies and configuration
Configuration for Quartz scheduling
Demonstrating Image Resizer
Building all dependencies 
Running Apache Kafka
Running Apache ZooKeeper on Windows
Running Apache Kafka on Linux/Unix
Running Apache Kafka on Windows
Running Image Resize Request Consumer
Running Image Resize Request Producer
Summary
Questions
Further reading
Building an Asynchronous Email Formatter
Technical requirements
Getting started
Why Email Formatter is useful
The use case diagram
The architecture of the Email Formatter application
Using Spring Data JPA for persistence
Class diagram for the domain model
Implementation of the domain model using JPA annotations
Setting up dependencies and the configuration class
Implementing the domain model
Implementation of Spring Data JPA repositories
Using Services to encapsulate business logic
Using Apache FreeMarker for templates
Using Spring Kafka for communication
Setting up dependencies and the configuration class
Configuration for User Registration
Configuration for the Email Formatter consumer
Configuring Java Mail
Using Spring Web MVC for the REST controller
Implementation of controller annotations
Using Spring Security for authentication and authorization
Demonstrating Email Formatter
Building all dependencies 
Running Apache Kafka
Running Apache ZooKeeper on Windows
Running Apache Kafka on Linux/Unix
Running Apache Kafka on Windows
Running SMTP server
Running the Email Formatter consumer
Running the User Registration microservice
Summary
Questions
Further reading
Assessments
Chapter 1, Introduction
Chapter 2, Building a Basic Web Application
Chapter 3, Building a Simple Blog Management System
Chapter 4, Introduction to Kotlin
Chapter 5, Building a Reactive Movie Rating API Using Kotlin
Chapter 6, Building an API with Reactive Microservices
Chapter 7, Building a Twitter Clone with Spring Boot
Chapter 8, Introducing Spring Boot 2.0 Asynchronous
Chapter 9, Building an Asynchronous Email Formatter
Other Books You May Enjoy
Leave a review - let other readers know what you think
This book is about Spring Boot 2.0 hands-on development for beginners, intermediate, and expert-level software developers. The purpose of this book is to increase the practical knowledge of the readers by going through the practical uses of the features introduced in Spring Boot 2.0.
This book covers vast topics with example applications so that it is much easier to grasp and use in real-life projects.
This book is for anyone interested in developing applications using the Spring Framework, and specifically, Spring Boot 2. The readers may have prior experience of Spring Boot, but it is not compulsory, as even beginners can benefit from the content of this book.
This book expects the readers to have some level of understanding of software development using Java.
Chapter 1, Introduction, outlines the Spring Boot 2.0 application development framework and compares its features with the previous version of Spring Boot. It also talks about configuration property changes, API changes, platform changes, and more in Spring Boot 2.0. Furthermore, it explains how to migrate from the previous version of Spring Boot application to Spring Boot 2.0 application.
Chapter 2, Building a Basic Web Application, begins with the practical side of developing a basic web application using the Spring Boot 2.0 Framework. It also talks about Spring Data JPA persistence, Spring Thymeleaf view, and Spring WebFlux controllers.
Chapter 3, Building a Simple Blog Management System, presents the practical side of developing a simple blog management system using the Spring Boot 2.0 framework. It also talks about Spring Data Elasticsearch for persistence, Apache FreeMarker view, and Spring WebFlux controllers.
Chapter 4, Introduction to Kotlin, introduces the programming language Kotlin by comparing it with Java programming language side by side. It will help to get started with Kotlin programming, subsequently moving into advanced topics in Kotlin such as OOP and other features.
Chapter 5, Building a Reactive Movie Rating API Using Kotlin, discusses reactive movie rating API development using Kotlin programming language with Spring Boot 2.0. It talks about Spring Data MongoDB persistence, Spring WebFlux controllers, and Spring Security authentication and authorization.
Chapter 6, Building an API with Reactive Microservices, explains reactive microservices development using Spring Boot 2.0. It also talks about Spring Data Redis persistence, Spring Web Flux controllers, Asynchronous data transfer among microservices, and Docker deployment of microservices.
Chapter 7, Building a Twitter Clone with Spring Boot, covers Angular application acting as a client for Spring Boot 2.0 REST API. It also talks about Spring Data JPA persistence, Angular 5 frontend, Spring Web Flux controllers, and Spring Security OAuth2 authentication and authorization.
Chapter 8, Introducing Spring Boot 2.0 Asynchronous, Quartz Scheduler introduces asynchronous application development using Spring Boot 2.0. It also talks about Apache Kafka as a message broker that enables decoupled, asynchronous communication between applications.
Chapter 9, Building an Asynchronous Email Formatter, explains details of how to build an Asynchronous Email Formatter, using Spring Boot 2 as the backend development framework and Apache Kafka as a message queue. It will also explain how to use JPA as the persistence layer, which is a widely used data source. It will use Apache FreeMarker to create the email templates and show how to use placeholders to provide dynamic data to email templates.
You need knowledge of the following:
The Java programming language
Spring Framework
Web application concepts
The following tools will be used throughout chapters:
Java Development Kit 8+
Maven 3
IntelliJ
IDEA or
Spring Tool Suite
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Spring-Boot-2.0-Projects-Fundamentals-of-Spring-Boot-2.0. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
There are a number of text conventions used throughout this book.
CodeInText: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "An ApplicationStartedEvent will be sent right after the application context is refreshed but before any command-line runners run. "
A block of code is set as follows:
public class
Address {
private
String
number
;
private
String
street
;
private
String
city
;
private
String
country
;
private
String
zipCode
;
// Getters, Setters, Equals, Hashcode}
Any command-line input or output is written as follows:
$ jconsole
Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select File | Open from the menu bar."
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
This chapter will introduce the reader to Spring Boot and explain how it stands out from other competing frameworks. It will begin by explaining how to get started developing applications using Spring Boot. Also, it will explain about Spring Boot 1.x and the improvements introduced in Spring Boot 2.0. Furthermore, it will walk through the most noticeable features and/or improvements of Spring Boot 2.0. Continuing on, it will explain progress with Spring Boot 2.0 and supply tips on migration from the older versions to Spring Boot 2.0.
This chapter covers the following topics:
Understanding Spring Boot
Generating Spring Boot Projects
Getting started with Spring Boot
Changes since Spring Boot 1.x
The next milestone
Migration
Technical requirements for this chapter are as follows:
To install
Java Development Kit
(
JDK
) 8, it can be downloaded from its official page at
http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
To install Maven 3, download it from its official page at
https://maven.apache.org/download.cgi
To install IntelliJ IDEA, download it from its official page at
https://www.jetbrains.com/idea/download/
To install
Spring Tool Suite
(
STS
), download it from its official page at
https://spring.io/tools
In this book, we will be using http://start.spring.io, which is a convenient tool for generating Spring Projects with the required dependencies to get started. This tool supports multiple Spring Boot versions, programming languages (Java, Groovy, Kotlin), project types (Maven, Gradle), and dependencies. Learning to use this tool will help readers to get started quickly with Spring Projects. The following is a screenshot of the tool to help us get familiarized with it:
This tool allows the selection of a Project type (Maven Project, Gradle Project), programming language (Java, Groovy, Kotlin), Spring Boot version (2.0.*, 1.5.*), project artifact group, artifact name, and project dependencies. After selecting the correct options, click on Generate Project will download a ZIP file of the project.
The ZIP file needs to be extracted first before being used. The extracted ZIP file will have the following structure:
<Project Name>/├── src/├── pom.xml├── mvnw└── mvnw.bat
To open the generated project with IntelliJ, we perform the following steps:
Open IntelliJ IDE.
Select
File
|
Open
from the menu bar as shown in the following screenshot:
Navigate to the location where the
extracted project
is and click on
OK
after selecting the project, shown as follows:
The IDE will show the opened project.
To open the generated project the Spring Tool Suite, we perform the following steps:
Open STS.
Select
File
|
Open Projects from File Sys
tem...
from the menu bar, as shown in the following screenshot:
From the dialog box that launched, click on the
Directory...
button:
Navigate to the extracted project location and Click on
OK
after selecting the project:
Finally, click on
Finish
on the import projects dialog box.
The IDE will show the opened project.
The source code for this chapter can be found at https://github.com/PacktPublishing/Spring-Boot-2.0-Projects-Fundamentals-of-Spring-Boot-2.0, in the Chapter01 directory.
This section will enable readers to get started with Spring Boot by explaining its features in detail. Furthermore, it will help you get started with Spring Boot application development by explaining the bare-bones of a Spring Boot application. Furthermore, it will explain the Spring Framework ecosystem and how it can be used in the Spring Boot application to harness the power of time-tested, industry-standard databases, messaging systems, and so on.
Spring Boot is an application development framework for the Java virtual machine (JVM) that enables users to write stand-alone, production-grade, flexible, and extensible Spring-based applications with minimum code and configurations. This follows the Rapid application development (RAD) paradigm where the focus is on writing business logic that matters. With the introduction of cloud-based hosting services and microservice architectures, Spring Boot has been further elevated into a must-know technology platform. The following are some of its features:
Standalone
: A Spring Boot application is self-contained and easily deployable. It can start with its own embedded Tomcat, Jetty, Undertow web container, or as a console application from a just standard file such as
Java Archive
(
JAR
) or
Web Archive
(
WAR
). An example of this would be an application that has
spring-boot-starter-web
as a dependency, which when run will by default inside an embedded Tomcat web container.
Production-grade
: A Spring Boot application enables most of the features required for production, such as monitoring, connection pools, externalized configurations, and so on, out of the box, and ships with industry-standard, time-tested, and proven third-party applications such as Tomcat.
Flexible
: A Spring Boot application will have most of its settings auto-configured with default settings based on the dependencies available in the classpath of the application. But the auto-configuration will step back whenever a custom configuration is made. An example for this would be w
hen a Spring Boot application finds a MySQL JDBC driver in the classpath; it auto-configures DataSource, which connects to the host localhost and port
3306
, as those will be the settings for a MySQL Server with a default installation.
Extensible
: A Spring Boot application will have most core functionalities implemented out of the box, but also has a lot of
Service Provider Interfaces
(
SPI
), which are used by third-party developers to implement or modify functionality. An example of this would be when a requirement arises for a custom endpoint in Spring Boot Actuator; extending and overriding the
AbstractEndpoint.invoke
method in a Spring Bean will expose it as a new endpoint under Spring Boot Actuator.
Spring Boot does not do any code generation and does not require any XML files to be configured in order to run. Spring Boot is ideal for on-premise and cloud-based deployments with a quick boot-up time and a good memory footprint. The uniqueness of Spring Boot comes from its ecosystem of Spring modules, which covers security, data persistence, batch processing, and so on and from the highly active, competent community of developers who keep on improving the Spring Boot Framework.
The anatomy of a Spring Boot application will be that it will be inheriting from a spring-boot-starter-parent project that will in return have all the common dependencies available for a Spring Boot application. Apart from this, there will be one or more spring-boot-starter POM such as spring-boot-starter-web, spring-boot-starter-jpa, and so on. The following example excerpt from pom.xml shows the basic dependencies of a Spring Boot application:
<parent>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter-parent
</artifactId>
<version>
1.5.9.RELEASE
</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>
org.springframework.boot
</groupId>
<artifactId>
spring-boot-starter
</artifactId>
</dependency>
...
</dependencies>
The minimum bootstrapping point of a Spring Boot application will be a class with a main method that will be annotated with a @SpringBootApplication annotation along with the main method body, which calls the SpringApplication.run static method, for which a configuration class (a class with @Configuration annotation—the @SpringBootApplication annotation transitively has one) needs to be passed, along with a String array of arguments. The following code shows the minimum bootstrapping point of a Spring Boot application:
import
org.springframework.boot.ApplicationRunner
;
import
org.springframework.boot.SpringApplication
;
import
org.springframework.boot.autoconfigure.
SpringBootApplication
;
import
org.springframework.context.annotation.
Bean
;
@SpringBootApplication
public class
SpringBootIntroApplication {
public static void
main
(String[] args) { SpringApplication.
run
(SpringBootIntroApplication.
class,
args)
;
}
@Bean
public
ApplicationRunner
applicationRunner
() {
return
args -> { System.
out
.println(
"Hello, World!"
)
;
}
;
}}
By running the preceding class, a Spring Boot application can be provisioned and executed. There are several ways to run a Spring Boot application; some of them are mentioned here:
Running the Spring Boot application
main
class using an IDE.
Building a JAR or WAR file using the following Maven command and then running:
$ mvn clean install
$ java -jar target/<package-name>.[jar|war]
Run this using the Spring Boot Maven plugin:
$ mvn clean spring-boot:run
The @SpringBootApplication annotation comprises of @EnableAutoConfiguration and @ComponentScan annotations that do the heavy lifting of auto-configuring the Spring Boot application with the default settings and scanning the packages for any Spring-specific components such as services, components, repositories, and so on.
What made the Spring Boot application development framework stand out from other competing alternatives is the fact that it has a lot of supporting frameworks for easing development, with starter dependencies that cover industry-standard, enterprise-grade methodologies and tools such as Web MVC, JPA, MongoDB, Elasticsearch, Redis, and many more.
This makes Spring Boot a unique solution for day-to-day programming needs. By including a starter dependency, a Spring Boot application will have all the necessary dependencies and auto-configurations included in the application without any developer intervention.
This makes the life of a developer easy and enables us to focus on the business logic of the application instead of configurations and dependency management. At the time of writing, there are more than thirty of these starters available to be used in a Spring Boot application. The complete list can be found at https://github.com/spring-projects/spring-boot/tree/master/spring-boot-project/spring-boot-starters.
Spring Boot is a powerful framework as it has a very gradual learning curve and is built on the basis of the ability to write applications that just run with minimal effort. Having said that, Spring Boot should not be mistaken for a silver-bullet solution for all problems. In the areas of memory utilization, optimization, latency reduction, and many more, work may be needed, so developer commitment and effort are still required. But all in all, Spring Boot can be considered as a very good solution as it enables users to develop a minimum viable product (MVP) that is production-ready within maybe a couple of days or hours.
The last released version of Spring Boot 1.x was 1.5.10.RELEASE, after which Spring Boot 2.0 was released in early 2018. As Spring Boot 2.0 is a major release it has JVM level, platform level, application programming interface (API) level, and dependencies level changes, which must be taken into account when developing applications with Spring Boot 2.0.
The major changes from Spring Boot 1.x to Spring Boot 2.0 are listed as follows:
