Mastering Spring Boot 2.0 - Dinesh Rajput - E-Book

Mastering Spring Boot 2.0 E-Book

Dinesh Rajput

0,0
39,59 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Learn to develop, test, and deploy your Spring Boot distributed application and explore various best practices.

Key Features

  • Build and deploy your microservices architecture in the cloud
  • Build event-driven resilient systems using Hystrix and Turbine
  • Explore API management tools such as KONG and API documentation tools such as Swagger

Book Description

Spring is one of the best frameworks on the market for developing web, enterprise, and cloud ready software. Spring Boot simplifies the building of complex software dramatically by reducing the amount of boilerplate code, and by providing production-ready features and a simple deployment model.

This book will address the challenges related to power that come with Spring Boot's great configurability and flexibility. You will understand how Spring Boot configuration works under the hood, how to overwrite default configurations, and how to use advanced techniques to prepare Spring Boot applications to work in production. This book will also introduce readers to a relatively new topic in the Spring ecosystem – cloud native patterns, reactive programming, and applications. Get up to speed with microservices with Spring Boot and Spring Cloud. Each chapter aims to solve a specific problem or teach you a useful skillset. By the end of this book, you will be proficient in building and deploying your Spring Boot application.

What you will learn

  • Build logically structured and highly maintainable Spring Boot applications
  • Configure RESTful microservices using Spring Boot
  • Make the application production and operation-friendly with Spring Actuator
  • Build modern, high-performance distributed applications using cloud patterns
  • Manage and deploy your Spring Boot application to the cloud (AWS)
  • Monitor distributed applications using log aggregation and ELK

Who this book is for

The book is targeted at experienced Spring and Java developers who have a basic knowledge of working with Spring Boot. The reader should be familiar with Spring Boot basics, and aware of its benefits over traditional Spring Framework-based applications.

Dinesh Rajput is the founder of Dineshonjava, a blog for Spring and Java techies. He is a Spring enthusiast and a Pivotal Certified Spring Professional. He has written a bestselling book, Spring 5 Design Patterns. He has more than 10 years of experience with different aspects of Spring and cloud-native development, such as REST APIs and microservices architecture. He is currently working as an architect at a leading product. He worked as a tech lead at Bennett, Coleman & Co. Ltd and Paytm. He completed his master's degree in computer engineering at JSS Noida, and he lives in Noida, India.

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 365

Veröffentlichungsjahr: 2018

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Mastering Spring Boot 2.0

 

 

 

 

 

Build modern, cloud-native, and distributed systems using Spring Boot

 

 

 

 

 

 

 

 

 

 

 

Dinesh Rajput

 

 

 

 

 

 

 

 

BIRMINGHAM - MUMBAI

Mastering Spring Boot 2.0

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: Merint MathewAcquisition Editor: Karan SadawanaContent Development Editor: Akshada IyerTechnical Editor: Supriya ThabeCopy Editor: Safis EditingProject Coordinator: Prajakta NaikProofreader: Safis EditingIndexer: Aishwarya GangawaneGraphics: Jisha ChirayilProduction Coordinator:  Shraddha Falebhai

First published: May 2018

Production reference: 1300518

Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.

ISBN 978-1-78712-756-2

www.packtpub.com

 

First, I want to dedicate this book to all the soldiers of the Indian Army.
To my parents, my lovely wife, and my kids, Arnav and Rushika.
Specially dedicated to my grandfather, the late Mr. Arjun Singh, and my maternal grandfather, the late Mr. Durjan Lal Rajput.
mapt.io

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.

Why subscribe?

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

PacktPub.com

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.

Contributors

About the author

Dinesh Rajput is the founder of Dineshonjava, a blog for Spring and Java techies. He is a Spring enthusiast and a Pivotal Certified Spring Professional. He has written a bestselling book, Spring 5 Design Patterns. He has more than 10 years of experience with different aspects of Spring and cloud-native development, such as REST APIs and microservices architecture.

He is currently working as an architect at a leading product. He worked as a tech lead at Bennett, Coleman & Co. Ltd and Paytm.

He completed his master's degree in computer engineering at JSS Noida, and he lives in Noida, India.

Technically, I authored this book, but it was not possible without the unconditional support of my wife, Anamika, who helped me focus on this book. Thanks to my kids, Arnav and Rushika. I have taken away a lot of time that I'd spend playing with them to write this book.
A huge thanks go to my father, Shrikrashan Rajput, and mother, Indira Rajput, and Surendra Singh who encouraged me to do work that they can feel proud of.

About the reviewers

Samer ABDELKAFI has 13 years of experience as a software architect and engineer, a major in open source technologies. He has contributed to numerous and diverse projects in different sectors such as banking, insurance, education, public services, and utility billing. In 2016, he created DEVACT, a company specializing in information technology consulting. He has also reviewed two books related to Spring projects titled, Spring MVC Blueprints and Mastering Spring Cloud. In addition to this, he shares his experience on his blog and writes articles related to Java and web technologies.

 

 

Yogendra Sharma is a developer with experience of the architecture, design, and development of scalable and distributed applications. He was awarded a bachelor's degree from Rajasthan Technical University in computer science. With a core interest in microservices and Spring, he also has hands-on experience in technologies such as AWS Cloud, Python, J2EE, NodeJS, JavaScript, Angular, MongoDB, and Docker. Currently, he works as an IoT and cloud architect at Intelizign Engineering Services Pune.

 

 

 

 

Packt is searching for authors like you

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.

Table of Contents

Title Page

Copyright and Credits

Mastering Spring Boot 2.0

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

Getting Started with Spring Boot 2.0

Introducing Spring Boot

Simplifying Spring application development using Spring Boot

The essential key components of Spring Boot

Spring Boot Starters

Spring Boot Starter Parent POM

Spring Boot auto-configuration

Enabling Spring Boot auto-configuration

Spring Boot CLI

Spring Boot Actuator

Setting up a Spring Boot workspace

Setting up Spring Boot with Maven

Setting up Spring Boot with Gradle

Developing your first Spring Boot application

Using a web interface for Spring Initializr

Creating a Spring Boot project using the STS IDE

Implementing the REST service

New features in Spring Boot 2.0

Summary

Customizing Auto-Configuration in Spring Boot Application

Understanding auto-configuration

Learning how auto-configuration works

Customizing Spring Boot

Customizing using Spring Boot properties

Replacing generated beans

Disabling specific auto-configuration classes

Changing a library's dependencies

Externalizing configuration with properties

Order of evaluation for overridden properties

Renaming application.properties in the Spring application

Externally configuring application properties

Using the @EnableConfigurationProperties annotation

Fine-tuning with logging

Logging output

Using YAML for configuration

YAML for properties

Multiple profiles inside a single YAML file

Customizing application error pages

Summary

Getting Started with Spring CLI and Actuator

Getting started with using Spring Boot CLI

Installing the Spring Boot CLI

Manually installing from a downloaded distribution

Installation with SDKMAN!

Installing with OSX Homebrew

MacPorts installation

Command-line completion

Using the Initializr with the Spring Boot CLI

Spring Boot Actuator – taking Application's Insights

Enabling Spring Boot's Actuator in your application

Analyzing the Actuator's endpoints

Exposing configuration details

Exposing metrics endpoints

Exposing application information

Shutting down your application

Customizing your Actuator endpoints

Enabling or disabling endpoints

Changing endpoint IDs

Changing the sensitivity of the Actuator's endpoints

Writing custom health indicators

Creating a custom endpoint

Securing the Actuator endpoints

The Actuator with Spring Boot 2.X

Summary

Getting Started with Spring Cloud and Configuration

Cloud-native application architecture

Microservices architecture

Microservice benefits

Microservice challenges

Introduction to Spring Cloud

Building blocks of the cloud and microservice applications

Usages of Spring Cloud

Configuring the Spring Cloud application

Creating the configuration producer Spring Cloud Config Server

Project setup and dependencies

Implementing Cloud Config Server

Configuring the application.properties file

Creating a Git repository as configuration storage

Running your configuration application

Configuring multiple repositories using patterns

Authentication

Force-pull property

Creating the configuration consumer Spring Cloud Config client

Summary

Spring Cloud Netflix and Service Discovery

Introduction to Spring Cloud Netflix

The need for Service Discovery in the microservices architecture

Implementing Service Discovery – Eureka Server

The Maven build configuration file

The Gradle build configuration file

Enabling the Eureka server as a Discovery Service server

Implementing Service Discovery – Eureka clients

Adding the Maven dependencies configuration

The Gradle build configuration

Registering a client with Eureka

Consuming the REST service

Using EurekaClient

Using DiscoveryClient

Client-side load balancing using Netflix Ribbon

Using the registry-aware Spring Cloud Netflix FeignClient client

Summary

Building Spring Boot RESTful Microservice

Microservices with Spring Boot

Brief introduction to bootstrap.yml and application.yml

A simple microservice example

Creating a discovery service

Creating a microservice (the Producer)

Creating microservice consumers

Load-balanced RestTemplate

Brief introduction to Spring Data

Apache Ignite repository

Spring Data MongoDB

Spring MongoDB data highlights

Spring Data JPA

Summary

Creating API Gateway with Netflix Zuul Proxy

The need for an API Gateway pattern

Pros of the API Gateway pattern

Cons of the API Gateway pattern

API Gateway pattern components

Implementing API Gateway using Netflix Zuul Proxy

Including Zuul using Maven dependency

Enabling the Zuul service proxy

Configuring Zuul properties

Adding Zuul filters

Registering Zuul filters

Summary

Simplify HTTP API with Feign Client

Declarative REST client – Feign basics

Including Feign in the cloud application

Overriding Feign defaults

Creating Feign clients

Feign inheritance support

Multiple interfaces

Advanced usage of the Feign client

Feign logging

Exception handling

Custom encoders and decoders

Custom encoder

Custom decoder

Feign and Hystrix

Unit testing Feign clients

Summary

Building Event-Driven and Asynchronous Reactive Systems

Event-driven architecture patterns

Mediator topology

Broker topology

Introduction to reactive programming

Spring Reactive

ReactiveX

Introduction to Command Query Responsibility Segregation

Introduction to the Event Sourcing pattern

Introduction to Eventual consistency

Building an event-driven Reactive Asynchronous System

Introducing Spring Cloud Streaming

Adding Kafka to your application

Installing and running Kafka

Configuration properties for Kafka

Service used to write to Kafka

Rest API controller

Listening to a Kafka topic

Summary

Building Resilient Systems Using Hystrix and Turbine

Circuit-breaker pattern

Using the Hystrix library with a reference implementation

Configuring Hystrix in your application

Maven dependency

Enabling circuit-breaker

Adding the Hystrix annotation in services

Error propagation

Implementing a REST controller in customer service

Building and testing customer service

Customizing the default configuration

Hystrix Metrics Stream

Implementing Hystrix Dashboard in our project

Turbine dashboard

Turbine stream

REST consumer with Hystrix and Feign

Summary

Testing Spring Boot Application

Test-driven development

Unit testing

Advantages

Disadvantages

Other mock libraries

Integration testing

Benefits of testing with Spring

Activating profiles for a test class

JUnit tests for the Spring Boot application

Using Mockito for mocking services

Postman for testing RESTful service contracts

Summary

Containerizing Microservice

Introducing containers to the microservice architecture

Virtual machines versus containers

Benefits of a container-oriented approach

Drawbacks of a container-oriented approach

Key concepts of the containers-oriented approach

Getting started with Docker

Installing Docker

Installing Docker on Linux

Installing Docker on Windows

Docker commands

Container-specific commands

Docker architecture

Docker Engine

Docker container

Writing Dockerfile

Dockerizing any Spring Boot application

Creating a Docker image using Maven

Getting started with Docker Compose

Installing Docker Compose

Using Docker Compose

Writing a docker-compose file

Orchestration using a docker-compose file

Scaling containers using docker-compose and load balancing

Introducing Kubernetes

Summary

API Management

API Management

Advantages of using API Management software tools

API Management tools

Rate limiting

Implementing rate limiting

Learning about KONG

Microservice REST APIs with the KONG architecture

Using APIs without the KONG architecture

Installing KONG

Using the KONG API

Features of the KONG API

Swagger

Usage of Swagger

Using Swagger in a microservice

Adding a Maven dependency

Configuring Swagger 2 in your project

Configuring Swagger UI in your project

Customizing the Swagger UI meta-configuration

Filtering an API from Swagger's documentation

Customizing with Swagger annotations

Advantages of Swagger

Summary

Deploying in Cloud (AWS)

Spinning up an AWS EC2 instance

Microservices architecture on AWS

Publishing microservices to the Docker Hub

Installing Docker on AWS EC2

Running microservices on AWS EC2

Summary

Production Ready Service Monitoring and Best Practices

Monitoring containers

Logging challenges for the microservices architecture

Centralized logging solution for the microservices architecture

Log aggregation using the ELK stack

Install Elasticsearch

Install Logstash

Install Kibana

Requesting tracing using Sleuth

Requesting tracing with Zipkin

Adding the Zipkin server to your machine

Summary

Other Books You May Enjoy

Leave a review - let other readers know what you think

Preface

Mastering Spring Boot 2.0is for all Java developers who want to learn Spring Boot and Spring Cloud as enterprise-distributed cloud-based applications. Therefore, enterprise Java and Spring developers will find this book particularly useful in helping them understand cloud-native design patterns using the microservices architecture used by Spring Boot 2.0 and Spring Cloud, how the microservices architecture solves the common design problems of the cloud-native infrastructure in distributed applications, and they will appreciate the examples presented in this book. Before reading this book, readers should have basic knowledge of  the basics of Core Java, Spring Core Framework, and Spring Boot. You can read my other book, Spring 5 Design Patterns  to learn more about Spring Framework.

Spring Boot 2.0 has been newly launched by Pivotal with the reactive programming and the cloud. Spring Boot 2.0 introduces many new features and enhancements we will discuss in this book. Mastering Spring Boot 2.0 is a mastering book that will give you in-depth insight into the Spring Boot and cloud microservices architecture.

The great part of today's Spring Boot is that many companies have already adopted it as a primary framework for the development of the enterprise applications, especially for the REST APIs using the microservices architecture. For Spring Boot, no external enterprise servers are needed to start working with them.

The goal of writing this book is to discuss the common designs used behind cloud-native applications and how they are implemented in the Spring Cloud module of the Spring Boot 2.0. Here, the author has also outlined some best practices that should be used during logging of the distributed design and development of the application.

The book contains 15 chapters, which cover everything from the development of microservices-based cloud applications to the deployment of microservices by either using virtual machines or containers such as Docker.

Mastering Spring Boot 2.0 is divided into four parts. The first part introduces you to the essentials of Spring Boot 2.0, Spring Boot CLI, and Spring Cloud. Part 2 steps behind the interservice communication in the microservices architecture using Rest Template, Spring Cloud Netflix Feign. Part 3 expands on that by explaining how to build an event-driven resilient system with Spring Cloud Stream and Kafka. This part also shows you how to monitor using Hystrix and Turbine. Finally, part 4 explains how to test and build APIs, and deploy to containers such as Docker, and also to clouds, such as AWS.

Who this book is for

Mastering Spring Boot 2.0 is for all Java developers who want to learn Spring Boot and Spring Cloud in the enterprise-distributed cloud-based applications. Therefore, enterprise Java and Spring developers will find it particularly useful in understanding cloud-native design patterns using the microservices architecture used by Spring Boot 2.0 and Spring Cloud, how microservices architecture solves common design problems of the cloud-native infrastructure in the distributed application, and they will most fully appreciate the examples presented in this book. Before reading this book, readers should have basic knowledge of Core Java, Spring Core Framework, and Spring Boot basics.

What this book covers

Chapter 1, Getting Started with Spring Boot 2.0, will give you an overview of Spring Boot 2.0 and all its new features, including some essential key components. You'll also get an overview of the greater the Spring Boot.

Chapter 2, Customizing Auto-Configuration in Spring Boot Application, will give an overview of the Spring Boot auto-configuration feature and explains how you can override the default autoconfiguration.

Chapter 3, Getting Started with Spring CLI and Actuator, will show you several ways to create Spring Boot applications using Spring Boot's web-based interface, the STS IDE, and Spring Boot CLI. In this chapter, we will discuss Spring Boot CLI deeply and will also see how to install it on your machine and how to use it to create Spring Boot applications. Also, you'll see Spring Boot's production-ready features using the Actuator.

Chapter 4, Getting Started with Spring Cloud and Configuration, will explore how to create a configuration server to provide a set of configuration files from a Git repository to client applications. In this chapter, the reader will also learn about Spring Cloud configuration service and how to build and consume the configuration service.

Chapter 5,Spring Cloud Netflix and Service Discovery, will explore Spring Cloud Netflix and Service Discovery with Eureka.

Chapter 6, Building Spring Boot RESTful Microservice, will build a RESTful atomic microservice that performs CRUD operations on an in-memory database, either HSQL or H2, using Spring Cloud and Spring Data, enable the service for service discovery registration to the Eureka server.

Chapter 7, Creating API Gateway with Netflix Zuul Proxy, will explore the need of the API gateway pattern for microservices communication, either from UI components or from inter service calls. We will implement an API gateway using the Netflix API Zuul. We will see how to set up a Zuul proxy in your application.

Chapter 8, Simplify HTTP API with Feign Client, will explore what Feign is and how it works. It gives a detailed explanation of how Feign can be extended/customized for business needs, with a reference implementation for a custom encoder, decoder, Hystrix, and exception handling with unit testing.

Chapter 9, Building Event-Driven and Asynchronous Reactive Systems, will provide a detailed overview of how to use event-driven architectures to build event-driven microservices as cloud-native applications. We will look at some of the important concepts and themes behind handling data consistency in distributed systems.

Chapter 10, Building Resilient Systems Using Hystrix and Turbine, will explore the circuit breaker pattern with a reference implementation using the Netflix Hystrix library, touching base on configuring the Turbine dashboard to aggregate hystrix streams from multiple services.

Chapter 11, Testing Spring Boot Application, will explore unit testing Spring Boot Services using JUnit and Mockito. All our reference implementation will have unit testing done, so this chapter is more of an aggregation of the different testing mechanisms available for microservices.

Chapter 12, Containerizing Microservice, will provide an introduction to containers, dockerizing the services built in the previous chapter, writing a Dockerfile, orchestrating the containers using docker-compose, and providing an orchestration example in Kubernetes.

Chapter 13, API Management, will explore the need for an API manager in distributed systems, setting up KONG open source API manager, configuring the API endpoints built in the previous chapters in the KONG API Manager, introducing Swagger for API standards, and finally closing with demonstrating rate limiting and logging using KONG.

Chapter 14, Deploying in Cloud (AWS), will explore deploying microservices in AWS EC2 instances manually and using cloudformation scripts. You will learn how to run a Docker-enabled Spring Boot microservice application on Amazon EC2 instances.

Chapter 15, Production Ready Service Monitoring and Best Practices, will elaborate on some of the best practices in building distributed systems and also will elaborate on performance monitoring for production ready services. We will introduce log aggregation using the ELK(Elasticsearch/Logstash/Kibana) stack for a distributed application.

To get the most out of this book

This book can be read without a computer or laptop at hand, in which case you need nothing more than the book itself. However, to follow the examples in the book, you need Java 8, which you can download from http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html, and you will also need your favorite IDE. I have used the Software Spring Tool Suite; download the latest version of Spring Tool Suite (STS) from https://spring.io/tools/sts/all according to your OS. Java 8 and STS work on a variety of platforms—Windows, macOS, and Linux.

Download the example code files

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 athttps://github.com/PacktPublishing/Mastering-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!

Conventions used

There are a number of text conventions used throughout this book.

CodeInText: Indicates code words in the text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: "Let's configure Zuul properties in our application using theapplication.ymlconfiguration file."

A block of code is set as follows:

@RestController class HelloController { @GetMapping("/") String hello() { "Hello World!!!" } }

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

<dependencies>

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-web</artifactId>

</dependency>

</dependencies>

Any command-line input or output is written as follows:

$ Spring run HelloController.groovy

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: "Click the Generate Project button, and we have a ready-to-run application."

Warnings or important notes appear like this.
Tips and tricks appear like this.

Get in touch

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.

Reviews

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.

Getting Started with Spring Boot 2.0

As we know, the Spring Framework makes development very easy for both core and enterprise Java applications. Spring has settled, and is now a very popular framework. The Spring team is continuously inventing something new to enhance software development and they are focused on making software development easy. The Spring team released one of its major projects for the Spring Framework in 2013, Spring Boot.

This project from the Spring team makes software development with Java easy. Spring Boot is built on top of the existing Spring Framework. So basically, Spring Boot is not a separate framework, but it is similar. It's a collection of ready-made things to just pick and use without taking any overhead configuration.

The Spring team is introducing many exciting things to the Spring ecosystem to sustain it in the market. There are many new things such as cloud computing, big data, schemaless data persistence, and reactive programming. But one of the most exciting and game changing features has come with Spring Boot in the past year. Spring Boot is a great invention for the Spring Framework by the Spring team. That is why Spring has settled for a long time and is winning major laurels.

Spring Boot is a tricky framework to understand. This chapter will help you to understand Spring Boot 2.0 and the underlying important concepts—starter projects, auto-configuration, and starter parents. You will also understand how Spring Boot makes software development easy. As a bonus, I will discuss the story behind the success of Spring Boot. This chapter will cover a demo application with Spring Boot and create a REST service.

At the end of this chapter, you will understand how Spring Boot develops Spring applications with agility and provides an already prepared menu for creating a REST service. You will learn how Spring Boot solves common problems at the configuration level of an enterprise application by using auto-configure.

This chapter will cover the following points:

Introducing Spring Boot

Simplifying Spring application development using Spring Boot

The essential key components of Spring Boot

Spring Boot Starter projects

Auto-configuration

Spring Boot CLI

Spring Boot Actuator

Setting up a Spring Boot workspace

Developing your first Spring Boot application

New features in Spring Boot 2.0

Let's look at these topics in detail.

Introducing Spring Boot

In my opinion, Spring Boot is like a cooked meal waiting to be eaten. In terms of Spring application development, Spring applications typically require a lot of setup. Suppose you are working with JPA. You need DataSource, TransactionManager, EntityManagerFactory, and so on. If you are working with a web MVC application, you need WebApplicationInitializer/web.xml, ContextLoaderListener, and DispatcherServlet. If you are working on an MVC application using JPA, you would need all of these. But much of this is predictable. Spring Boot can do most of this setup for you.

Spring Boot provides a new strategy for application development with the Spring Framework, with minimal fuss. It enables you to focus only on the application's functionality rather than Spring metaconfiguration. Spring Boot requires either minimal or zero configuration in the Spring application.

According to the Spring Boot documentation:

"Spring Boot makes it easy to create stand-alone, production-grade Spring based Applications that you can "just run.""

Spring Boot has changed the way Spring applications are being developed. If you look at the initial versions of the Spring Framework, Spring was a very lightweight and POJO-oriented framework. That means it was decoupled and had less component code, with configurations being set up using XML. As of Spring version 2.5, annotations were introduced, which reduced the XML configurations by using component-scanning. Spring 3.0 came with Java configuration; do note that there was still no escape from configuration. Eventually, with the latest Spring version, component-scanning reduced configuration and Java configuration made it less time-consuming, but Spring still required a lot of configuration.

All these configurations in the Spring application affect the development of actual business functionality. It works as a source of friction in Spring application development. There is no doubt the Spring Framework does much more for us in the area of application development using Java. But if a mistake happened in the configuration level, it required a lot of time to debug and solve it.

Another point of friction is project dependency management. Adding dependencies is very hectic work that gives developers headaches when it comes to deciding what libraries need to be part of the project build. It is even more challenging to identify the versions of depending libraries.

Overall, you can see that configurations, dependency management, and deciding versions of depending libraries consume a lot of the development time of the software engineer. Finally, it reduces the productivity of developers.

Spring Boot has changed all of that, but remember it is not a code generator or an IDE plugin.

Spring Boot has an opinionated view of the Spring application. An opinionated runtime for Spring Projects supports different project types, such as Web and Batch, and it handles most low-level, predictable setup for you.

What is an opinionated runtime? Spring Boot uses sensible defaults, opinions, mostly based on the classpath contents. For example, it sets up a JPA Entity Manager Factory if a JPA implementation is on the classpath. Spring Boot uses a default Spring MVC setup if Spring MVC is on the classpath. Still, everything can be overridden easily, but most of the time there is no need to override anything.

Let's see how Spring Boot simplifies Spring application development.

Simplifying Spring application development using Spring Boot

As we have discussed in the previous section, the Spring Framework provides lot of flexibility to configure beans in the Spring application in multiple ways such as XML, annotation, and Java configuration. But remember, if the number of modules and features increases in the Spring application, it also increases the complexity in the configuration. After a point, your Spring application tends to become tedious and error-prone.

Here, Spring Boot comes into the picture to address the complexity of the configuration of your Spring application.

Spring Boot does exactly what you are looking for. It will do things automatically for you but allows you to override the defaults if required. (Remember the point about it being an opinionated framework?)

Spring Boot is not a separate framework, but it is Spring at heart. It is built on top of the Spring Framework to remove tedious work from the developer end and allow developers to focus on the business code with minimal or zero configurations.

See the following diagram that shows what Spring Boot is exactly:

In the preceding diagram, you can see that Spring Boot is the surface layer over the Spring Framework, with all of the modules such as Web (MVC), JDBC, Security, Batch, and so on. It presents a small surface area for User to approach and extract value from the rest of Spring.

Suppose you are working with a task, a Hello World web application. If you are choosing to develop with the Spring Framework, what would you need to do?

The following are the bare minimum configurations required for a small web application:

Creating a project structure either by using Maven or Gradle and defining required dependencies such as Spring MVC and the Servlet API dependencies for your case.

A deployment descriptor file, that is, 

web.xml

. In the case of Java configuration, you require the 

WebApplicationInitializer

implementation class that declares Spring's

DispatcherServlet

.

The Spring MVC configuration class to enable the Spring MVC module for your

Hello World

application.

You have to create a controller class that will respond to your request.

You require a web application server such as Tomcat.

Of these points, most are generic boilerplate code and common configuration for a Spring web application, except writing application-specific controllers. So, Spring Boot provides all common configurations and boilerplate code based on the available library of the classpath. You don't need to take responsibility for writing this common and generic code.

Let's create the same Hello World application using Spring Boot. Suppose for a moment we are using a Groovy-based controller class as follows:

@RestController class HelloController { @GetMapping("/") String hello() { "Hello World!!!" } }

This code is a complete Spring web application, with nothing required to configure. No web.xml file, no build specification, and not even an application server. This is the entire application. We can run this application using Spring Boot CLI with the following command:

$ Spring run HelloController.groovy

So, you can see how Spring Boot simplifies Spring application development. We will also see the same application using Java in the next section of this chapter.

Spring Boot does not compete with the Spring or Spring MVC Framework. It makes it easy to use them in the Spring application.

The essential key components of Spring Boot

You have seen how Spring Boot simplifies Spring application development. But how does Spring Boot make it possible? What is the magic behind it? Spring Boot brings this magic to Spring application development. The following are essential key components of Spring Boot:

Spring Boot Starters

Automatic configuration

Spring Boot CLI 

Spring Boot Actuator

These four core key components are the reason behind Spring Boot's magic. These components make Spring application development easy. Let's see these components in detail.

Spring Boot Starters

Starter is like a small Spring project for each module such as web MVC, JDBC, ORM, and so on. For your Spring application, you just add the starters of the respective module in the classpath, and Spring Boot will ensure that the necessary libraries are added to the build by using Maven or Gradle. As a developer, you don't need to worry about the module libraries and dependent versions of libraries, that is, transitive dependencies.

Spring Boot documentation says Starters 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 technologies that you need, without having to hunt through sample code and copy-paste loads of dependency descriptors.

Suppose you want to create a web application or an application to expose RESTful services using the Spring web MVC module to your Spring application; just include the spring-boot-starter-web dependency in your project, and you are good to go.

Let's see what it would look like in the Spring application:

<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>

This starter dependency resolves the following transitive dependencies:

spring-web-*.jar

spring-webmvc-*.jar

tomcat-*.jar

jackson-databind-*.jar

See the following diagram about spring-boot-starter-web:

The spring-boot-starter not only reduces the build dependency count, but also adds specific functionality to your build. In your case, you added the web starter to your Spring application, so it provides web functionality that your application needs. Similarly, if your application will use ORM, then you can add the orm starter. If it needs security, you can add the security starter.

Spring Boot provides a wide range of Starter projects. Spring Boot provides the following application Starters under the org.springframework.boot group:

spring-boot-starter-web-services

: For building applications exposing SOAP web services

spring-boot-starter-web

: Build web applications and RESTful applications

spring-boot-starter-test

: Write great unit and integration tests

spring-boot-starter-jdbc

: Traditional JDBC applications

spring-boot-starter-hateoas

: Make your services more RESTful by adding HATEOAS features

spring-boot-starter-security

: Authentication and authorization using Spring Security

spring-boot-starter-data-jpa

: Spring Data JPA with Hibernate

spring-boot-starter-cache

: Enabling the Spring Framework's caching support

spring-boot-starter-data-rest

: Expose simple REST services using Spring Data REST

Spring Boot Starter Parent POM

The Starter Parent POM defines key versions of dependencies and Maven plugins. It typically uses spring-boot-starter-parent as the parent in the pom.xml file:

<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.2.RELEASE</version> <relativePath/> <!-- lookup parent from repository --> </parent>

Spring Boot Starter Parent POM allows us to manage the following things for multiple child projects and modules:

Configuration

: Java version and other properties

Dependency m

anagement

: Version of dependencies

Default plugin configuration

: This includes configurations such as build plugins

It is an easy way to bring in multiple coordinated dependencies including transitive dependencies.

Let's see the Spring Boot auto-configuration.

Spring Boot auto-configuration

Spring Boot can automatically provide configuration for application functionality, which is common to many Spring applications. Auto-configuration works by analyzing the classpath as follows:

If you forget a dependency, Spring Boot can't configure it

A dependency management tool is recommended

Spring Boot Parent and Starters make it much easier

Spring Boot works with Maven, Gradle, and Ant/Ivy

Spring Boot offers auto-configuration of those modules in your Spring application based on the JAR dependencies that you have added. Suppose you added the JPA starter dependency (spring-boot-starter-data-jpa) in your Spring application classpath; Spring Boot attempts to automatically configure JPA to your Spring application. Now, you have not manually configured any database connection beans related to JPA. Similarly, if you want to add an in-memory database such as HSQLDB, just add it (org.hsqldb) in the classpath of your Spring application, and it will auto-configure an in-memory database.

Spring Boot provides the auto-configuration feature in the following ways:

First, Spring Boot looks for frameworks available on the classpath

After that, it checks existing configuration for the application

Based on these points, Spring Boot provides the basic configuration needed to configure the application with these frameworks. This is called auto-configuration.

In another book, Spring 5 Design Patterns, I have written an application related to the backend that accesses a relational database by using JDBC. As we know that the Spring Framework provides JdbcTemplate, we have to register this JdbcTemplate as a bean in the application context of our application as follows:

@Bean public JdbcTemplate jdbcTemplate(DataSource dataSource) { return new JdbcTemplate(dataSource); }

This configuration creates an instance of JdbcTemplate and injects it with another bean dependency, DataSource. So, also we have to register this DataSource bean to be met. Let's see in the following configuration how the HSQL database is configured with a DataSource bean:

@Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.HSQL) .addScripts('schema.sql', 'data.sql') .build(); }

This configuration creates an instance of DataSource specifying the SQL scripts schema.sql and data.sql with the HSQL embedded database.

You can see that the two bean methods are not too complex to define, but are also not part of the application logic. This represents just a fraction of application configuration. If you add the Spring MVC module to the same application, then you have to register another corresponding bean method. These methods will be the same for each Spring application where you want to use the same modules. We can say that this is boilerplate configuration code in each Spring application.

In short, the configuration, whatever we have defined, is a common configuration for each application. Ideally, we should not have to write it for each application.

Spring Boot addresses this problem of common configuration. It can automatically configure these common configuration bean methods. Spring Boot provides this auto-configuration based on the available library in your application's classpath. So, if we have to add the HSQL database library in your application's classpath, then it will automatically configure an embedded HSQL database.

If a Spring JDBC-related library is in the classpath of your Spring application, then it will also configure a JdbcTemplate bean for your application. There is no need to configure these beans manually in your Spring application. These beans will be automatically configured for you; just use them for business logic. Spring Boot reduces such boilerplate code configuration at the developer's end.

Spring Boot CLI

Spring Boot also provides a command-line tool that can be used to quickly write Spring applications. You can run Groovy scripts with Spring Boot CLI. Groovy code has almost zero boilerplate code compared with Java.

The Spring Boot documentation says:

"You don't need to use the CLI to work with Spring Boot but it's definitely the quickest way to get a Spring application off the ground."