Discover millions of ebooks, audiobooks, and so much more with a free trial

Only €10,99/month after trial. Cancel anytime.

Spring Boot in Practice
Spring Boot in Practice
Spring Boot in Practice
Ebook1,082 pages8 hours

Spring Boot in Practice

Rating: 0 out of 5 stars

()

Read preview

About this ebook

Go beyond the basics with Spring Boot! This practical guide presents dozens of relevant scenarios in a convenient problem-solution-discussion format.

In Spring Boot in Practice you will learn:

    Spring Boot’s features from an expert’s perspective
    Configuring, logging, and monitoring Spring Boot applications
    Effective methods for database communication
    Utilizing Spring Security and securing your Spring application in production
    Designing and developing microservices and RESTful APIs with Spring Boot
    Microservice versioning, documentation, and security
    Reactive application development and reactive data access with WebSocket and RSocket
    Deploying Spring Boot applications on Kubernetes and major cloud platforms
    Implementing containerization in a Spring Boot application
    Using Spring Boot with Kotlin and GraalVM

Spring Boot in Practice is full of practical recipes for common development problems in Spring Boot. Author Somnath Musib has spent years building applications with Spring, and he shares that extensive experience in this focused guide. You’ll master techniques for using Spring Data, Spring Security, and other Spring-centric solutions. Learn how to work with Spring Boot and Kotlin, handling connections for multiple platforms, and how Spring Boot can simplify building microservices and APIs. Each recipe is built around a real-world problem, complete with a full solution and thoughtful discussion.

About the technology
With Spring Boot, it’s a snap to create standalone Spring applications that require minimal manual setup. Spring Boot directly embeds a server like Tomcat or Jetty into your project and preconfigures core Spring settings, third-party libraries, security, and other key elements. It’s a big framework, with lots of powerful features. This book provides a rich collection of techniques to help you get the most out of Spring Boot.

About the book
Spring Boot in Practice is a cookbook-style guide to Spring application development. Following a convenient Problem-Solution-Discussion format, it takes you technique-by-technique through Spring Boot fundamentals. You’ll dive deep into auto-configuration, security, microservices, and more. Along the way, you’ll also discover numerous advanced and hidden features. All the book’s source code is open source, so you can integrate the detailed samples into your own projects.

What's inside

    Instantly useful techniques with reusable source code
    Configuring, logging, and monitoring Spring Boot applications
    Effective methods for database communication
    Securing Spring applications in production
    Microservices and RESTful APIs

About the reader
For Spring Boot beginners with some Spring experience.

About the author
Somnath Musib has over a decade of development experience, and has been actively working with Spring Boot since 2015.

Table of Contents
PART 1
1 Booting Spring Boot
PART 2
2 Common Spring Boot tasks
3 Database access with Spring Data
4 Spring Boot: Autoconfiguration and Actuator
5 Securing Spring Boot applications
6 Implementing additional security with Spring Security
7 Developing RESTful Web services with Spring Boot
PART 3
8 Reactive Spring Boot application development
PART 4
9 Deploying Spring Boot applications
PART 5
10 Spring Boot with Kotlin, Native Image, and GraphQL
LanguageEnglish
PublisherManning
Release dateAug 30, 2022
ISBN9781638350699
Spring Boot in Practice

Related to Spring Boot in Practice

Related ebooks

Programming For You

View More

Related articles

Reviews for Spring Boot in Practice

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Spring Boot in Practice - Somnath Musib

    Spring Boot in Practice

    Somnath Musib

    Foreword by Josh Long

    To comment go to liveBook

    Manning

    Shelter Island

    For more information on this and other Manning titles go to

    www.manning.com

    Copyright

    For online information and ordering of these  and other Manning books, please visit www.manning.com. The publisher offers discounts on these books when ordered in quantity.

    For more information, please contact

    Special Sales Department

    Manning Publications Co.

    20 Baldwin Road

    PO Box 761

    Shelter Island, NY 11964

    Email: orders@manning.com

    ©2022 by Manning Publications Co. All rights reserved.

    No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher.

    Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps.

    ♾ Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine.

    ISBN: 9781617298813

    dedication

    To my parents—for sacrificing everything to raise us

    and

    To my son, Abhirup—for adding new meaning and purpose to my life

    brief contents

    Part 1.

      1 Booting Spring Boot

    Part 2.

      2 Common Spring Boot tasks

      3 Database access with Spring Data

      4 Spring Boot: Autoconfiguration and Actuator

      5 Securing Spring Boot applications

      6 Implementing additional security with Spring Security

      7 Developing RESTful Web services with Spring Boot

    Part 3.

      8 Reactive Spring Boot application development

    Part 4.

      9 Deploying Spring Boot applications

    Part 5.

    10 Spring Boot with Kotlin, Native Image, and GraphQL

    Appendix A. Generating and building Spring Boot projects

    Appendix B. Spring MVC and Thymeleaf Template Engine

    contents

    Front matter

    foreword

    preface

    acknowledgments

    about this book

    about the author

    about the cover illustration

    Part 1.

      1 Booting Spring Boot

    1.1   Introducing Spring Boot

    Why Spring Boot?

    What is Spring Boot?

    Spring Boot core features

    Spring Boot components

    1.2  Code examples

    Maven vs. Gradle

    Java vs. Kotlin

    Database support

    Lombok

    1.3  Getting started with Spring Boot

    Your first Spring Boot project

    Spring Boot project structure

    Creating an executable JAR file

    Exploring the JAR file

    Shutting down a Spring Boot application

    1.4  Spring Boot additional concepts

    Spring Boot startup events

    Listening events in a Spring Boot application

    Custom Spring Boot starters

    Custom autoconfiguration

    Failure analyzers

    Spring Boot actuator

    Spring Boot developer tool

    Part 2.

      2 Common Spring Boot tasks

    2.1  Managing configurations

    Using the SpringApplication class

    Using @PropertySource

    Config data file

    OS environment variable

    2.2  Creating custom properties with @ConfigurationProperties

    Technique: Defining custom properties with @ConfigurationProperties in a Spring Boot application

    2.3  Executing code on Spring Boot application startup

    Technique: Using CommandLineRunner to execute code at Spring Boot application startup

    2.4  Customizing logging in a Spring Boot application

    Technique: Understanding and customizing default Spring Boot logging in a Spring Boot application

    Technique: Using Log4j2 to configure logging in a Spring Boot application

    2.5  Validate user data using Bean Validation

    Technique: Using built-in Bean Validation annotations to validate business entity in a Spring Boot application

    Technique: Defining and using custom Bean Validation annotation to validate a POJO in a Spring Boot application

      3 Database access with Spring Data

    3.1  Introducing Spring Data

    Why Spring Data?

    Spring Data modules

    3.2  Configuring a database in a Spring Boot application

    Technique: Configuring a relational database in a Spring Boot application

    Technique: Configuring MongoDB database in a Spring Boot application

    Technique: Initializing a relational database schema with a Spring Boot application

    3.3  Understanding the CrudRepository interface

    Technique: Managing domain objects in a relational database with Spring Data JPA

    Technique: Creating a custom Spring Data repository with Spring Data JPA to manage domain objects in a relational database

    3.4  Retrieve data from a database using Spring Data

    Defining query methods

    Technique: Defining custom query methods to retrieve domain objects from a relational database with Spring Data JPA

    Implementing pagination with PagingAndSortingRepository

    Technique: Using PagingAndSortingRepository interface to paginate and sort the data

    Specifying query using @NamedQuery

    Technique: Using a named query to manage domain objects in a relational database with Spring Data JPA

    3.5  Specifying query using @Query

    Technique: Using @Query annotation to define queries and retrieve domain objects in a relational database with Spring Data JPA

    3.6  Using Criteria API with Spring Data JPA

    Technique: Using Criteria API to manage domain objects in a relational database with Spring Data JPA

    3.7  Using QueryDSL with Spring Data JPA

    Technique: Using QueryDSL to manage domain objects in a relational database with Spring Data JPA

    3.8  Managing domain object relationships

    Technique: Managing domain objects with many-to-many relationships in a relational database with Spring Data JPA

      4 Spring Boot: Autoconfiguration and Actuator

    4.1  Understanding Spring Boot autoconfiguration

    Understanding @Conditional annotation

    Deep dive into autoconfiguration

    4.2  Using Spring Boot DevTools

    Property defaults

    Automatic restart

    Live reload

    4.3  Creating a custom failure analyzer

    Technique: Creating a custom Spring Boot FailureAnalyzer

    4.4  Spring Boot Actuator

    Technique: Configuring Spring Boot Actuator in a Spring Boot application

    Understanding Spring Boot Actuator endpoints

    Managing Spring Boot Actuator endpoints

    Health endpoint deep dive

    Creating a custom Spring Boot HealthIndicator

    Technique: Defining a custom Spring Boot actuator HealthIndicator

    4.5  Info endpoint deep dive

    Technique: Configuring info Spring Boot Actuator endpoint

    Technique: Configuring a custom info contributor to provide custom application info in the Spring Boot Actuator endpoint

    4.6  Creating a custom Spring Boot Actuator endpoint

    Technique: Creating a custom Spring Boot actuator endpoint

    Spring Boot actuator metrics

    Creating custom metrics

    Gauge

    Metrics dashboard with Prometheus and Grafana

      5 Securing Spring Boot applications

    5.1  Introducing Spring Security

    5.2  Hello Spring Security with Spring Boot

    Technique: Enabling application security with Spring Security in a Spring Boot application

    Filter, FilterChain, and Spring Security

    Spring Security architecture

    Authenticating a user

    Spring Security autoconfiguration

    5.3  Using Spring Security

    Technique: Customizing the default Spring Security login page of a Spring Boot application

    Technique: Configuring in-memory authentication with custom users in Spring Security in a Spring Boot application

    Technique: Configuring JDBC authentication with Spring Security in a Spring Boot application

    Technique: Implementing JDBC authentication with custom UserDetailsService in a Spring Boot application

    Technique: Implementing LDAP authentication in a Spring Boot application

    Technique: Implementing HTTP basic authentication in a Spring Boot application

      6 Implementing additional security with Spring Security

    6.1  Enabling HTTPS in a Spring Boot application

    Technique: Enabling HTTPS in a Spring Boot application

    6.2  Securing secrets in Spring Cloud Vault

    Technique: Managing application secrets with HashiCorp Vault in a Spring Boot application

    6.3  Implementing user registration

    Technique: Implementing user registration with Spring Security in a Spring Boot application

    6.4  Implementing email verification at user registration

    Technique: Validating user email addresses in a Spring Boot application

    6.5  Controlling multiple incorrect login attempts

    Technique: Controlling multiple incorrect login attempts in a Spring Boot application

    6.6  Implementing a Remember Me feature

    Technique: Enabling a Remember Me feature in a Spring Boot application with Spring Security

    6.7  Implementing reCAPTCHA

    Technique: Enabling Google reCAPTCHA in a Spring Boot application with Spring Security

    6.8  Enabling two-factor authentication with Google Authenticator

    Technique: Enabling two-factor authentication in a Spring Boot application

    6.9   Authentication with OAuth2

    Technique: Enabling sign in with Google in a Spring Boot application

    6.10 Securing Actuator endpoints

    Technique: Securing Spring Boot Actuator endpoints

      7 Developing RESTful Web services with Spring Boot

    7.1  Developing a RESTful API with Spring Boot

    Technique: Developing a RESTful API using Spring Boot

    7.2  Managing exceptions in a Spring Boot RESTful API

    Technique: Handling exceptions in a RESTful API

    7.3  Testing a RESTful API

    Technique: Testing a RESTful API in a Spring Boot application

    7.4  Documenting a RESTful API

    Technique: Documenting a RESTful API with OpenAPI

    7.5  Implementing RESTful API versioning

    Technique: Implementing versioning in a RESTful API

    7.6  Securing a RESTful API

    Technique: Using JWT to authorize RESTful API requests

    Part 3.

      8 Reactive Spring Boot application development

    8.1  Introduction to reactive programming

    Backpressure

    Benefits of reactive programming

    8.2  Understanding Project Reactor

    8.3  Introducing Spring WebFlux

    Technique: Developing a reactive RESTful API with annotated controllers

    Technique: Developing a reactive RESTful API with functional endpoints

    8.4  Testing reactive applications

    Technique: Using WebClient to build an API client

    8.5  Introduction to RSocket

    Technique: Developing applications using RSocket and Spring Boot

    8.6  Introduction to WebSocket

    Technique: Developing an application using WebSocket and Spring Boot

    Part 4.

      9 Deploying Spring Boot applications

    9.1  Running Spring Boot applications as executable JAR files

    Technique: Packaging and executing a Spring Boot application as an executable JAR file

    9.2  Deploying Spring Boot applications as WAR in the WildFly application server

    Technique: Packaging and deploying a Spring Boot application as WAR in the WildFly application server

    9.3  Deploying Spring Boot applications in Cloud Foundry

    Technique: Deploying a Spring Boot application to Cloud Foundry

    9.4  Deploying Spring Boot applications in Heroku

    Technique: Deploying a Spring Boot application in Heroku

    9.5  Running Spring Boot applications as Docker containers

    Technique: Creating a container image and running a Spring Boot application as a container

    9.6  Deploying Spring Boot applications in a Kubernetes cluster

    Technique: Deploying a Spring Boot application in a Kubernetes cluster

    9.7  Deploying Spring Boot applications in Red Hat OpenShift

    Technique: Deploying a Spring Boot application in the Red Hat OpenShift platform

    Part 5.

    10 Spring Boot with Kotlin, Native Image, and GraphQL

    10.1  Spring Boot with Kotlin

    Technique: Developing a Spring Boot application with Kotlin

    Technique: Securing a Spring Boot Kotlin application with Spring Security

    10.2  Introducing Spring Native

    Introduction to GraalVM

    GraalVM native image

    Spring Boot native image

    Technique: Generating Spring Boot native image using buildpacks

    Technique: Generating Spring Boot native image using a Maven plugin

    Understanding Spring AOT Maven Plugin

    10.3  Spring Boot with GraphQL

    Issues with REST

    Introduction to GraphQL

    Using GraphQL with Spring Boot

    Technique: Developing a GraphQL API with a Spring Boot application

    Technique: Developing a GraphQL API over WebSocket with a Spring Boot application

    Appendix A. Generating and building Spring Boot projects

    Appendix B. Spring MVC and Thymeleaf Template Engine

    index

    front matter

    foreword

    We might be on to something

    I remember sitting with cloud luminaries and colleagues, James Watters and Andrew Clay Shafer, in a café in Santa Monica, California in 2015. We were at a crossroads. The Spring team had launched Spring Boot in 2013, and it was generally available in 2014. And in 2015, it was taking off. We knew people were excited about the possibilities, and we knew people were embracing it, but we also knew we hadn’t quite gotten there. It was too big to know when or where there was. I still don’t know if we know. It is early 2022 as I write this, and the project is growing day by day. I still don’t know if we know where there is.

    We might be on to something, we agreed. Indeed.

    I still don’t know if we’re there, of course. But I do know that to get there, we need people to be on the same page and familiar with the landscape. You can’t find your way around without proper orientation. This book, Spring Boot in Practice, gives me hope. It avoids the vertigo typical of most attempts to scale the rock face that is server-side application and service development by offering a steady hand.

    The book almost immediately gets right into the business of building an application straight out of the gate. First, there’s a quick primer on the fundamentals, and then boom, you’re building something! I think that’s the best way, too. With something this big, you just have to start exploring. It won’t matter how much, or in what detail, I try to describe the place or even depict it cartographically; it’s just not the same. You need to see it; you need to explore the space!

    After the primer, it feels like we’re working our way up the conceptual ladder, starting with the foundational stuff you will deal with when building any Spring Boot-based application. Then, we get into data access, the Spring Boot observability support through the Spring Boot Actuator support, securing your applications with Spring Security, and building HTTP services with Spring MVC and Spring Webflux. If you get this far, you won’t know every nook and cranny, but you’ll know where to go. You’ll be correctly oriented.

    Where you go next is anybody’s guess, but author Somnath Musib does a good job here, as well, charting out some newer neighborhoods in the wide and wonderful world of Springdom, including Kotlin, GraphQL, and GraalVM. Kotlin is an ever-changing and vibrant language that maps nicely to the Spring ecosystem. Spring GraphQL is a brand-new project that brings the GraphQL Java project to the Spring developer. And Spring Native is a fantastic way to turn Spring Boot 2.x and Spring Framework 5.x code into GraalVM native images. Both Spring GraphQL and Spring Native are relatively new projects, so I am delighted to see them covered here in this book, your reliable guide to Spring.

    Somnath Musib does a great job navigating the area, and his guidance no doubt makes it easier to focus on the journey that matters: the journey to production. When you enjoy success in production, when you’re there, I hope you too can look at your friends and colleagues and say, smiling, We might be on to something.

    —Josh Long, Spring Developer Advocate, Tanzu, a division of VMWare, @starbuxman

    preface

    As of the writing of this book, Spring Boot is the most popular Java framework, and it is way ahead in its usage and acceptance from its competitor frameworks, such as Dropwizard, Quarkus, and Micronaut. With the industry-wide adoption of microservice-based architecture, the popularity of Spring Boot is skyrocketing, and it has become the most preferred Java framework to learn amongst the developers.

    Despite its popularity, the biggest challenge newcomers come across is knowing where to start. Both Spring and Spring Boot reference documentation is humongous and not beginner friendly. Spring Boot provides several guides on how to do certain things with Spring Boot. These guides are good for a quick start but fail to provide practical examples and a comprehensive understanding of the capabilities of Spring Boot. There are numerous tutorials, articles, and blog posts available across the internet. But again, those are scattered, incomplete, and far from providing a complete picture of Spring Boot.

    Spring Boot in Practice attempts to address many of these issues. When we started working on the book, we had two major goals. The first was to provide our readers with a clear picture of Spring Boot and its many internal concepts, such as autoconfiguration, actuator, and security. The second was to enrich the readers’ learning journey with practical examples of Spring Boot, rather than traditional textbook-style, theory-oriented examples. We are confident that we have kept ourselves focused on these two goals.

    Spring Boot in Practice covers a wide variety of Spring Boot materials. Primarily, the book is focused on beginner- to intermediate-level readers. The book aims to take the readers on a journey starting with basic Spring Boot concepts and how to use various Spring Boot features effectively, supported by ample real-world use cases that lead to more advanced topics. Although the book is primarily focused on entry-level to intermediate-level developers, it has materials for seasoned developers as well. Concepts such as Spring Boot with Kotlin, Spring Native Image with GraalVM, Spring Boot with GraphQL, Hashicorp Vault, and Multi-Factor Authentication (MFA) will all be useful for senior developers.

    I sincerely hope that readers appreciate and benefit from the contents of this book and find it useful in their Spring Boot application development. Any remarks or suggestions for improving the content of the book are most welcome and eagerly awaited. You may reach the author on LinkedIn at https://www.linkedin.com/in/musibs/.

    acknowledgments

    While it is my name listed on the front cover, this book came about with the help of many people, and I would like to thank all of them for helping to make it one of the best Spring Boot books available.

    First, I would like to express my heartfelt gratitude to my wife, Jhinuk. You’ve patiently waited and allowed me to spend hours writing this book. Thank you for all your support and encouragement throughout this journey. I love you.

    Next, I would like to thank my newborn child, Abhirup, for giving me a new meaning and purpose in my life. My gratitude is also due to my parents and my brother, Sumanta, and sister, Supriya, who have always believed in me and motivated me to achieve new heights in my life.

    I’d like to thank my mentors, colleagues, and friends who taught me many invaluable lessons in my career. This list is large, but I must mention the following people: Amit Chitnis, Ashwani Singh, Midhuna Babu, Kiran N. S., Sandeep Salian, Priya Ponnekanti, Minal Barve, Shravan Kumar Singh, Suhasini C. H., Ramya S., and Parijat Pathak.

    I’d also like to acknowledge my development editor at Manning, Jennifer Stout, for working with me, making me believe I could write this book, and for making the journey easier. I’d also like to thank the book’s acquisition editor, Mike Stephens; review editor, Mihaela Batinić; production editor, Andy Marinkovich; copy editor, Christian Berk; and proofreader, Jason Everett. Thank you for providing me with the opportunity to write a Manning book. Thanks as well to all other people at Manning who worked with me on the production and promotion of the book. It was truly a team effort.

    Thank you to all the reviewers who took the time to read the manuscript at various stages during its development and provided their invaluable feedback. To Ajit Malleri, Al Pezewski, Alain Lompo, Alex Saez, Amrah Umudlu, Andres Sacco, Anindya Bandopadhyay, Ashley Eatly, Asif Iqbal, Becky Huett, Chad Johnston, Fernando Bernardino, Gabriele Bassi, Giampiero Granatella, Harinath Kuntamukkala, Ilya Sakayev, Javid Asgarov, Jean-François Morin, João Miguel Pires Dias, John Guthrie, Kent R. Spillner, Krzysztof Kamyczek, Lachman Dhalliwal, Maqbool Patel, Mladen Knežić, Mohamed Sanaulla, Najeeb Arif, Neil Croll, Rafał Gorzkowski, Raffaella Ventaglio, Raghunath Nedumpurath, Raymond Cheung, Richard Meinsen, Ruslan Vidzert, Sambaran Hazra, Satej Sahu, Sergio Britos Arevalo, Søren Dines Jensen, Tan Wee, Tiziano Bezzi, and William Fly, you all helped make this a better book.

    Special thanks to the technical reviewer of the book, Ubaldo Pescatore, for all the reviews and feedback. And a big thank you to Giampiero Granatella, the technical proofreader, for his careful review of the code one last time, shortly before the book went into production.

    Finally, thank you to the Spring and Spring Boot team. You’ve created something incredibly useful and made life easier for developers around the world.

    about this book

    Spring Boot in Practice is written for Java developers who would like to learn Spring Boot and how to use it in their application development. This book belongs with Manning’s In Practice series and is focused on the practical use of Spring Boot with lots of real-world examples. The book is written in the problem, solution, discussion pattern, where we first introduce a problem and then provide a solution for it. Lastly, we provide an in-depth discussion of each feature in the discussion section.

    Who should read this book?

    Spring Boot in Practice is written for beginner- to intermediate-level application developers and provides plenty of real-life examples for using Spring Boot. This book attempts to emphasize various Spring Boot internal concepts as well as emerging features, such as Spring Boot with GraalVM Native Image, GraphQL, and reactive application development. Thus, this book has enough material for senior Spring Boot application developers to add to their existing knowledge. Anyone who wishes to learn Spring Boot, or brush up on their Spring Boot knowledge, will find the book useful.

    How this book is organized: A roadmap

    Spring Boot in Practice has 10 chapters and two appendixes, which span five parts.

    Part 1 contains an introduction to Spring Boot and its various features:

    Chapter 1 provides a high-level discussion on Spring Boot, its characteristics, and the various features it offers.

    Part 2 contains several concepts and techniques for Spring Boot application development:

    Chapter 2 discusses how you can perform several commonly used application tasks with Spring Boot. This includes various ways of managing configuration, using logging, data validation, and more.

    Chapter 3 discusses several techniques for accessing a database from a Spring Boot application.

    Chapter 4 provides an in-depth discussion on Spring Boot autoconfiguration and actuators. In this chapter, we discuss how autoconfiguration is designed and its internals. We also cover the Spring Boot actuator, creating custom endpoints, and Prometheus monitoring in considerable depth.

    Chapter 5 introduces Spring Security and several techniques for securing a Spring Boot application. We introduce how Spring Security works, various important filters, and how to customize various security parameters in your Spring Boot application.

    Chapter 6 takes the concepts introduced in chapter 5 to the next level by discussing several advanced production-grade security features that can be implemented in a Spring Boot application.

    Chapter 7 introduces how to develop RESTful APIs with Spring Boot. We discuss handling exceptions in RESTful API development, document APIs, version APIs, and, lastly, securing RESTful APIs

    Part 3 discusses performing reactive application development with Spring Boot:

    Chapter 8 introduces how to develop reactive applications with Spring Boot. We also cover using WebSocket and RSocket with Spring Boot.

    Part 4 highlights various techniques for deploying Spring Boot applications into various platforms:

    Chapter 9 discusses how to deploy Spring Boot applications on various platforms. We start with basic JAR and WAR deployment of Spring Boot applications. We then discuss deploying Spring Boot applications in Cloud Foundry and Heroku. Lastly, we demonstrate how to run Spring Boot applications as containers and deploy in Kubernetes Cluster and Red Hat OpenShift.

    Part 5 discusses using Spring Boot with Kotlin, GraalVM, Native Image, and GraphQL:

    Chapter 10 talks about using Kotlin to develop Spring Boot applications. We also discuss generating native images of the Spring Boot application with Spring Native. Lastly, we introduce how you can use GraphQL in a Spring Boot application.

    About the code

    This book contains many examples of source code, both in numbered listings and in line with normal text. In both cases, source code is formatted in a fixed-width font like this to separate it from ordinary text. Sometimes code is also in bold to highlight code that has changed from previous steps in the chapter, such as when a new feature adds to an existing line of code.

    In many cases, the original source code has been reformatted; we’ve added line breaks and reworked indentation to accommodate the available page space in the book. In rare cases, even this was not enough, and listings include line-continuation markers (➥). Additionally, comments in the source code have often been removed from the listings when the code is described in the text. Code annotations accompany many of the listings, highlighting important concepts.

    You can get executable snippets of code from the liveBook (online) version of this book at https://livebook.manning.com/book/spring-boot-in-practice. The complete code for the examples in the book is available for download from the Manning website at www.manning.com/books/spring-boot-in-practice, and from GitHub at https://github.com/spring-boot-in-practice/repo.

    liveBook discussion forum

    Purchase of Spring Boot in Practice includes free access to liveBook, Manning’s online reading platform. Using liveBook’s exclusive discussion features, you can attach comments to the book globally or to specific sections or paragraphs. It’s a snap to make notes for yourself, ask and answer technical questions, and receive help from the author and other users. To access the forum, go to https://livebook.manning.com/book/spring-boot-in-practice/discussion. You can also learn more about Manning’s forums and the rules of conduct at https://livebook.manning.com/discussion.

    Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the author can take place. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the forum remains voluntary (and unpaid). We suggest you try asking the author some challenging questions lest his interest stray! The forum and the archives of previous discussions will be accessible from the publisher’s website for as long as the book is in print.

    about the author

    Somnath Musib

    is a polyglot developer with 10+ years of experience. He has been using Spring Boot since 2015 and is actively involved in Spring Boot application development. Somnath loves teaching and likes to explain complex topics to people in an easy-to-understand manner. In his spare time, he loves writing about technologies on his Medium blog at https://musibs.medium.com/.

    about the cover illustration

    The figure on the cover of Spring Boot in Practice is Femme de Navarre or Woman from Navarre, taken from a collection by Jacques Grasset de Saint-Sauveur, published in 1797. Each illustration is finely drawn and colored by hand.

    In those days, it was easy to identify where people lived and what their trade or station in life was just by their dress. Manning celebrates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional culture centuries ago, brought back to life by pictures from collections such as this one.

    Part 1.

    Part 1 of this book consists of chapter 1, which introduces you to Spring Boot and some of its important characteristics. Chapter 1 covers the overview of Spring Boot, its various components, and some of its important features, such as Spring Boot starter, autoconfiguration, actuator, and failure analyzers. We also explore the project structure and various elements of a Spring Boot application. Chapter 1 also discusses creating an executable JAR file from a Spring Boot application and explores the JAR file components.

    1 Booting Spring Boot

    This chapter covers

    Introducing Spring Boot

    Project structure and various elements of a generated project

    Creating an executable JAR file and the generated JAR structure

    An overview of Spring Boot starter, autoconfiguration, failure analyzer, and actuator

    Introducing Spring Boot developer tools to increase developer productivity

    Welcome to Spring Boot—the most popular Java framework out there! It has revolutionized the way Spring applications or, more specifically, Java applications are developed these days. Spring Boot is an open source extension of the Spring Framework designed to simplify the Spring application development. The popularity of Spring Boot is mostly attributed to its ability to create standalone, production-ready, Spring-based applications, in no time, that you can run without worrying much about the configuration hazards.

    This chapter provides an overview of Spring Boot, discussing what Spring Boot is, its purpose, its project structure, and several key Spring Boot features. Are you ready? Let’s boot our journey!

    1.1 Introducing Spring Boot

    In this section, we’ll introduce you to the Spring Boot framework and briefly answer a few common questions about Spring Boot. We’ll discuss why we need Spring Boot framework, introduce you to the framework, the various features it offers and various components of the framework.

    1.1.1 Why Spring Boot?

    As we venture out on this beautiful voyage of getting ourselves familiar with Spring Boot, the very first question that appears in mind is: why should we learn it in the first place? To find an answer to this question, let’s understand what problem Spring Boot promises to solve.

    The Spring Framework started its journey to simplify the Java Enterprise application development. It became immensely popular due to its simplified application development strategies and the heavy-lifting nature of the framework. Further, as the use of Spring as a framework increased, the need to further simplify the Spring application development process was also amplified.

    Although Spring provides a great deal of support to the developers in focusing only on solving their business problems, before Spring Boot there is still a significant amount of work that needs to be done by the developer to make things work. For instance, the following are a few challenges you’ll face once you start developing a Spring-based web application:

    Gain understanding of Servlet and the associated deployment descriptor web.xml concepts.

    Familiarize yourself with the WAR and EAR directory structures to package the application components.

    Understand application server-specific concepts, such as the domain, port, threads, and data sources while you deploy your application.

    Deal with complicated class loading strategies, application monitoring, management concepts, and logging facilities.

    There are too many technical buzzwords out there. What if, instead, you could write the business logic for your application, build an executable file, and just run it in a command line? You wouldn’t need to define complicated XML configurations or perform application server deployment or other technical juggleries. All these pieces of the puzzle would be mysteriously solved by some experienced magician, which would be impressive, right? Well, you’ll soon discover that Spring Boot is this magician.

    Spring Boot was introduced as a subproject under the Spring Framework to empower developers with a fast startup experience and exempt them from most of the configuration hazards. As you proceed with your Spring Boot journey, you’ll notice how seamlessly Spring Boot addresses several configuration and integration issues. For instance, in your Spring Boot project, you’ll not be forced to define a deployment descriptor web.xml file. You also won’t be forced to use an application server to run your application unless you specifically decide to run on an application server. Most of the time, Spring Boot’s default configuration can easily meet your needs.

    1.1.2 What is Spring Boot?

    Spring Boot was released in April 2014 to reduce some of the burdens of developing a Java web application. It allowed developers to focus more on the business logic rather than the boilerplate technical code and associated configurations. Spring Boot intends to create Spring-based, production-ready, standalone applications with little configuration changes on behalf of the application developer. It takes an opinionated view of the Spring Framework, so the application developers can quickly get started with what they need. It provides an additional layer between the Spring Framework for the user to simplify certain configuration aspects.

    Figure 1.1 Developer view of Spring Boot. It sandwiches itself between the developer and the Spring Framework. Several Spring Framework components are automatically configured by Spring Boot based on the Spring components a developer uses.

    Figure 1.1 shows how Spring Boot sandwiches itself between you, as the application developer, and the Spring Framework. As an intermediate layer, Spring Boot performs many configurations, which you’ll otherwise need to do yourself if you interact directly with the Spring Framework.

    1.1.3 Spring Boot core features

    Spring Boot has several notable features that make it stand out from the crowd of other frameworks:

    Fast bootstrapping—One of the primary goals of Spring Boot is to provide a fast startup experience in Spring application development. Let’s say you want to build a web application using Spring in a traditional approach. You’ll most likely follow the steps outlined below:

    Configure a Maven or Gradle project with Spring MVC dependencies.

    Configure the Spring MVC DispatcherServlet.

    Package the application components into a WAR file.

    Deploy the WAR file into a servlet container (e.g., Apache Tomcat).

    With Spring Boot, you can generate an application by specifying the dependencies you need in your application, and Spring Boot takes care of the rest.

    Autoconfiguration—Spring Boot automatically configures the bare minimum components of a Spring application. It does this based on the presence of the JAR files in the classpath or properties configured in the various property files. For instance, if Spring Boot detects the presence of a database driver JAR file (e.g., H2 in-memory database JAR) in the classpath, it automatically configures the corresponding data source to connect to the database.

    Opinionated—Spring Boot is opinionated. It automatically configures several components to start with a Spring application. Spring Boot does this with a set of starter dependencies. A starter dependency targets a specific area of application development and provides the related dependencies. For example, if you need to develop a web application, you can configure the spring-boot-starter-web dependency, which ensures that all related dependencies for developing a web application, such as spring-web and spring-webmvc, are available in the application classpath.

    Standalone—Spring Boot applications embed a web server, so they can run standalone and do not necessarily require an external web or application server. This enables Spring Boot applications to be packaged as an executable JAR file and run with the java -jar command. This also allows Spring Boot applications to be easily containerized and candidates for cloud-native application development.

    Production-ready—Spring Boot provides several useful production-ready features out of the box to monitor and manage the application once it is pushed to production, such as health checks, thread dumps, and other useful metrics.

    1.1.4 Spring Boot components

    Spring Boot consists of several components with each component focusing on a specific area of the application development. Some of these are core components, and you’ll use them often with almost every Spring Boot project. For example, the Spring Boot is the primary component you’ll use in almost every Spring Boot project. Figure 1.2 shows the Spring Boot components, and the following list briefly discusses these components:

    spring-boot—This is the primary Spring Boot component that provides support to other components. For example, it contains the SpringApplication class, which contains several static methods to create a standalone Spring Boot application. It also provides support for embedded web servers (e.g., Tomcat) and supports externalized application configurations (e.g., database details of your application), etc.

    spring-boot-autoconfigure—This component provides the necessary support for the automatic configuration of a Spring Boot application. Spring Boot autoconfiguration guesses and configures the spring beans based on the dependencies present in classpath and the properties configured. However, autoconfiguration backs away from the default configuration if it detects user-configured beans with custom configurations.

    Spring-boot-starters—Starters are a set of prepackaged dependency descriptors provided for developer convenience. A Spring Boot starter assists in providing a set of Spring and related technologies to the developer, which otherwise, the developer needs to manage themselves.

    spring-boot-CLI—This is a developer-friendly command-line utility that compiles and runs groovy codes. It can also watch files for changes, so you do not need to restart your application on modifications. This CLI tool exempts you from the need for dependency management tools, such as Maven or Gradle. Also, it lets you quickly prototype Spring applications without worrying much about dependency management and other builds-related issues. Refer to appendix A to learn how to use the Spring Boot CLI.

    spring-boot-actuator—This component provides the actuator endpoints to interact with, monitor, and audit a Spring Boot application. An actuator in Spring Boot can be managed through JMX or HTTP endpoints. Spring Boot provides a predefined list of actuator endpoints that cover a range of application aspects. If that does not satisfy your need, you can also create your custom actuator endpoints specific to your application. Spring Boot actuator also provides configurations to let you decide which actuator endpoints you want to enable and provides several means to secure them from unauthorized access.

    spring-boot-actuator-autoconfigure—This component provides support to autoconfigure the actuator endpoints based on the classpath. For instance, if the Micrometer (https://micrometer.io) dependency is present in the classpath, Spring Boot automatically configures the MetricsEndpoint.

    spring-boot-test—This module contains annotations and methods to write test cases for the Spring Boot application.

    spring-boot-test-autoconfigure—This component supports the autoconfiguration of the test cases of your application.

    spring-boot-loader—This component allows a Spring Boot application to be packaged as a single fat JAR file, including all dependencies and the embedded web servers that can be run standalone. You don’t use this module independently; instead, it is used along with Maven or Gradle plugins.

    spring-boot-devtools—This component contains an additional developer toolkit for a smooth development experience of Spring Boot applications. The toolkit includes features such as automatic detection of application code changes and LiveReload server to automatically refresh any HTML changes to the browser. Developer tools are intended to increase developer productivity.

    Figure 1.2 Spring Boot components

    1.2 Code examples

    In this section, we’ll discuss the code examples and the technologies we’ll use to develop the examples. We’ll talk about the build system, programming language, and the database that we’ll use in this book. We’ll also introduce you to Lombok, which helps us to simplify the POJO class definitions with simple annotations.

    1.2.1 Maven vs. Gradle

    Spring Boot lets you create a Spring Boot project with either Apache Maven (https://maven.apache.org/) or Gradle (https://gradle.org/) build tools. In the Spring Initializr (https://start.spring.io/) tool, you can choose the build system of your choice and generate the project. In this book, we’ll use Apache Maven as the preferred build system, as most readers are familiar with Apache Maven. However, if you are a Gradle user, you will find it is quite easy to port the code examples to Gradle seamlessly.

    1.2.2 Java vs. Kotlin

    You can use both Java and Kotlin (https://kotlinlang.org/) programming languages in your Spring Boot project. Spring Framework 5.0 has incorporated support for Kotlin, and since then there is a constant effort to provide better support for Kotlin in the Spring Framework. For instance, in Spring Security 5.3, the Spring team has introduced a Kotlin version of their domain-specific language (DSL) support to Spring Security. You can read more about Spring Framework’s Kotlin support at http://mng.bz/Bxw8.

    In this book, we’ll primarily use Java as our preferred language in most of the code examples. We’ll cover the major Kotlin features in Spring Framework (through Spring Boot) in chapter 10.

    1.2.3 Database support

    Several coding examples in this book require database access to demonstrate the concepts. Spring Boot extends support to an array of SQL and NoSQL databases. For the ease of testing of the coding examples, we’ll use an H2 in-memory SQL database in all our code examples (with a few exceptions).

    1.2.4 Lombok

    Lombok (https://projectlombok.org/) is a Java library that automatically generates the constructors, getter, setter, toString, and others based on the presence of a few annotations in the plain old Java object (POJO) class. All you need to do is use the appropriate annotation in the POJO class. For instance, to generate a getter method for all member variables in the POJO class, you can specify @Getter annotation in the class. We’ll use Lombok in this book in the code examples.

    If you are not interested in using Lombok, you can simply provide the getter, setter, and constructors, as applicable to the code. The code examples should work as expected.

    Record

    Java 14 has introduced the concept of records in the Java language. Records are immutable data classes that require you to specify only the type and name of the fields. The Java compiler can then generate the equals, hashCode, and toString methods. It also generates the private final fields, getter methods, and public constructor. If you do not wish to use a third-party library, such as Lombok, you may consider using Java records.

    A record can be defined as follows:

    Public record Course(int id, String name, String description, int rating) {}

    The compiler generates the public constructor with all the defined fields and provides getter methods with the same as the field names (e.g., id(), name() etc.) as well as equals and hashCode methods. You can find more information about Java records at http://mng.bz/donO.

    1.3 Getting started with Spring Boot

    You now have an overview of Spring Boot and know the purpose of the framework. In this section, you’ll learn to generate a Spring Boot project and the various parts of the generated project.

    1.3.1 Your first Spring Boot project

    Spring Boot provides a tool called Spring Initializr that lets you generate a skeleton Spring Boot project. You can access the Spring Initializr tool at https://start.spring.io. Further, Spring Boot also provides APIs that allows the mainstream IDE vendors to integrate Spring Initializr and provide built-in support to generate a Spring Boot project in the IDE itself. If you are new to Spring Initializr, refer to appendix A to learn various ways to create a Spring Boot project. We’ve generated a Spring Boot project for your reference in the book’s companion GitHub repository at http://mng.bz/razD.

    1.3.2 Spring Boot project structure

    A generated Spring Boot project structure is relatively simple and consists of only the components you need to proceed with Spring Boot application development. It contains the following components:

    A pom.xml file that contains the dependencies you’ve selected during project generation.

    A Maven wrapper file that lets you build the project without installing Maven in your local machine.

    A package structure that contains the source and tests Java files. The source package contains a Java class with the main method, and the test package has an empty test class.

    A resources folder to maintain additional project artifacts and an empty application.properties file.

    Let’s discuss the key components of the generated project in detail.

    The Maven pom.xml file

    The pom.xml file of the generated project is shown in the following listing.

    Listing 1.1 The pom.xml file of generated Spring Boot project

    1.0 encoding=UTF-8?> http:/ /maven.apache.org/POM/4.0.0 ➥ xmlns:xsi=http:/ /www.w3.org/2001/XMLSchema-instance         xsi:schemaLocation=http:/ /maven.apache.org/POM/4.0.0 ➥ https:/ /maven.apache.org/xsd/maven-4.0.0.xsd>     4.0.0                                                            ①         org.springframework.boot              ①         spring-boot-starter-parent      ①         2.6.3                                  ①             ①                                                         ①     com.manning.sbip.ch01                      ②     spring-boot-app-demo                ②     1.0.0                                      ②     spring-boot-app-demo     Spring Boot Demo Application             17                                                         ③                     org.springframework.boot             spring-boot-starter-web                                                     ④                     org.springframework.boot             spring-boot-starter-test             test                                                 org.junit.vintage                     junit-vintage-engine                                                                                                               ⑤                 org.springframework.boot                 spring-boot-maven-plugin                        

    ① Current project declares Spring Boot starter parent as its parent to indicate that this project is a child Spring Boot project. This ensures several features of the application, such as plugin and dependency management, can be managed by Spring Boot.

    ② Current project’s artifact details

    ③ List of declared Maven dependencies: Spring Boot starter web and Spring Boot starter test

    ④ Spring Boot starter test dependency provides necessary support to perform testing Spring Boot applications with popular testing libraries, such as Junit, Hamcrest, and Mockito. This dependency excludes junit-vintage-engine dependency to leverage Junit 5 features with junit-jupiter-engine.

    ⑤ Spring Boot Maven plugin is a Maven plugin that provides useful goals to perform several application management activities. For instance, you can quickly start the Spring Boot application with this plugin using mvn spring-boot:run command.

    There are three segments of the pom.xml you’ll explore in this section:

    The parent tag

    The dependencies section

    The Spring Boot Maven plugin

    The spring-boot-starter-parent is the parent dependency for all Spring Boot starter dependencies. It also indicates that the current Spring Boot project is a child Spring Boot project and extends a few details from the parent project.

    A spring-boot-starter-parent is a special type of starter dependency that provides several default configurations, such as the default java version and default configurations for several Maven plugins to a Spring Boot project. For example, the maven-war-plugin and maven-surefire-plugin are automatically included by the starter parent dependency.

    Further, spring-boot-starter-parent also assists in dependency management. Notice that there is no dependency version specified for any of the declared dependencies. The appropriate version of these libraries is specified in the spring-boot-starter-parent.

    Does your project already have a parent pom?

    It is possible that you already have an existing Maven project set up with a parent pom, and you are upgrading this project to the Spring Boot. In this scenario, how can your child Spring Boot project extend the parent pom, since it is already extending a custom parent pom?

    You can still leverage several benefits, such as the dependency management offered by Spring Boot parent pom, by adding the following dependency. You can specify spring-boot-dependencies in the dependencyManagement section of the pom.xml file:

                    org.springframework.boot         spring-boot-dependencies         2.6.3         pom         import        

    In the second section of the pom.xml file, Spring Boot starter dependencies are declared. Spring Boot starter dependencies are one of the key features of the Spring Boot framework. Refer to the Spring Boot starter dependency sidebar for a quick overview.

    Spring Boot starter dependency

    A Spring Boot starter dependency is intended to make the Spring Boot application development easy, rapid, and effective. If you have previous experience developing Java applications with a build tool such as Apache Maven or Gradle, you can recall that managing dependencies is one of the key challenges for an application developer.

    The first challenge is to identify the libraries (dependencies) you need to develop a specific component of your application. Once you identify them, you need to find the right versions of the libraries. Even if you find the right libraries and versions, in this fast-paced world of application development, it is relatively easy to become out of sync with the versions. To further increase your issues, the dependencies you choose have their own dependencies or, more precisely, transitive dependencies. In some cases, you even need to control those as well. Spring Boot starter dependency is a solution in Spring Boot to relieve you of all the above-mentioned issues.

    A starter dependency groups together a set of dependencies you might need to develop a part of your application. If you choose to develop a web application with Spring Boot, you’ll most likely choose the spring-boot-starter-web dependency. It ensures that all required dependencies to develop a web application are available in your application. Of course, this is opinionated, and you get the set of dependencies that the Spring team recommends you need to have to develop a web application. However, the key part here is that you are relieved from the dependency versioning, upgrades, and many other issues.

    A starter dependency can also depend on another starter dependency. For instance, the spring-boot-starter-web needs a few common starter dependencies, such as the spring-boot-starter, spring-boot-starter-tomcat, and spring-boot-starter-json dependencies. These starters pull another set of dependencies related to Spring Boot, Tomcat, and JSON, respectively. You can refer to the Spring Boot documentation for a list of Spring Boot starters available at http://mng.bz/VlJ0.

    The concept of starter dependency is extendable. Spring Boot lets you build starters that you can use in your application. This is useful for large applications to modularize and manage dependencies in terms of custom starters. You’ll learn how to create a custom starter later in the book.

    In the generated project, we’ve included two starter dependencies: spring-boot-starter-web and spring-boot-starter-test. The web starter dependency includes required JARs to build a web application, whereas the test dependency lets you write test cases for your application.

    In the final section of the pom.xml presented in listing 1.1, you can find the spring-boot-maven-plugin. This plugin is provided for developer convenience to simplify several application management activities. For instance, you’ll often notice it is quite straightforward to build an executable JAR or WAR file of a Spring Boot application. This is because the repackage goal of the spring-boot-maven-plugin ensures that it takes the Maven-generated original JAR or WAR file (which is not an executable) and repackages it to make it executable. Table 1.1 shows the list of available goals of spring-boot-maven-plugin with syntax and a brief description:

    Table 1.1 List of Spring Boot Maven plugin goals

    Enjoying the preview?
    Page 1 of 1