📄 Page
1
M A N N I N G Somnath Musib Foreword by Josh Long IN PRACTICE
📄 Page
2
Spring Boot in Practice SOMNATH MUSIB Foreword by JOSH LONG MANN I NG SHELTER ISLAND
📄 Page
3
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book 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. The author and publisher have made every effort to ensure that the information in this book was correct at press time. The author and publisher do not assume and hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from negligence, accident, or any other cause, or from any usage of the information herein. Manning Publications Co. Development editor: Jennifer Stout 20 Baldwin Road Technical development editor: Ubaldo Pescatore PO Box 761 Review editor: Mihaela Batinić Shelter Island, NY 11964 Production editor: Andy Marinkovich Copy editor: Christian Berk Proofreader: Jason Everett Technical proofreader: Giampiero Granatella Typesetter: Dennis Dalinnik Cover designer: Marija Tudor ISBN: 9781617298813 Printed in the United States of America
📄 Page
4
To my parents—for sacrificing everything to raise us and To my son, Abhirup—for adding new meaning and purpose to my life
📄 Page
5
iv brief contents PART 1 ................................................................................... 1 1 ■ Booting Spring Boot 3 PART 2 ................................................................................. 29 2 ■ Common Spring Boot tasks 31 3 ■ Database access with Spring Data 70 4 ■ Spring Boot: Autoconfiguration and Actuator 131 5 ■ Securing Spring Boot applications 184 6 ■ Implementing additional security with Spring Security 233 7 ■ Developing RESTful Web services with Spring Boot 297 PART 3 . .............................................................................. 347 8 ■ Reactive Spring Boot application development 349 PART 4 . .............................................................................. 397 9 ■ Deploying Spring Boot applications 399 PART 5 . .............................................................................. 439 10 ■ Spring Boot with Kotlin, Native Image, and GraphQL 441
📄 Page
6
contents foreword xiii preface xv acknowledgments xvii about this book xix about the author xxii about the cover illustration xxiii PART 1 ........................................................................ 1 1 Booting Spring Boot 3 1.1 Introducing Spring Boot 4 Why Spring Boot? 4 ■ What is Spring Boot? 5 ■ Spring Boot core features 6 ■ Spring Boot components 7 1.2 Code examples 9 Maven vs. Gradle 9 ■ Java vs. Kotlin 9 ■ Database support 9 Lombok 9 1.3 Getting started with Spring Boot 10 Your first Spring Boot project 10 ■ Spring Boot project structure 10 ■ Creating an executable JAR file 20 ■ Exploring the JAR file 20 ■ Shutting down a Spring Boot application 21v
📄 Page
7
CONTENTSvi1.4 Spring Boot additional concepts 22 Spring Boot startup events 22 ■ Listening events in a Spring Boot application 23 ■ Custom Spring Boot starters 25 ■ Custom autoconfiguration 26 ■ Failure analyzers 26 ■ Spring Boot actuator 26 ■ Spring Boot developer tool 27 PART 2 ...................................................................... 29 2 Common Spring Boot tasks 31 2.1 Managing configurations 32 Using the SpringApplication class 32 ■ Using @PropertySource 33 Config data file 35 ■ OS environment variable 38 2.2 Creating custom properties with @ConfigurationProperties 40 Technique: Defining custom properties with @ConfigurationProperties in a Spring Boot application 41 2.3 Executing code on Spring Boot application startup 46 Technique: Using CommandLineRunner to execute code at Spring Boot application startup 46 2.4 Customizing logging in a Spring Boot application 51 Technique: Understanding and customizing default Spring Boot logging in a Spring Boot application 52 ■ Technique: Using Log4j2 to configure logging in a Spring Boot application 56 2.5 Validate user data using Bean Validation 60 Technique: Using built-in Bean Validation annotations to validate business entity in a Spring Boot application 60 ■ Technique: Defining and using custom Bean Validation annotation to validate a POJO in a Spring Boot application 63 3 Database access with Spring Data 70 3.1 Introducing Spring Data 71 Why Spring Data? 72 ■ Spring Data modules 72 3.2 Configuring a database in a Spring Boot application 74 Technique: Configuring a relational database in a Spring Boot application 74 ■ Technique: Configuring MongoDB database in a Spring Boot application 79 ■ Technique: Initializing a relational database schema with a Spring Boot application 82
📄 Page
8
CONTENTS vii3.3 Understanding the CrudRepository interface 86 Technique: Managing domain objects in a relational database with Spring Data JPA 88 ■ Technique: Creating a custom Spring Data repository with Spring Data JPA to manage domain objects in a relational database 94 3.4 Retrieve data from a database using Spring Data 97 Defining query methods 97 ■ Technique: Defining custom query methods to retrieve domain objects from a relational database with Spring Data JPA 98 ■ Implementing pagination with PagingAndSortingRepository 101 ■ Technique: Using PagingAndSortingRepository interface to paginate and sort the data 101 ■ Specifying query using @NamedQuery 104 Technique: Using a named query to manage domain objects in a relational database with Spring Data JPA 105 3.5 Specifying query using @Query 107 Technique: Using @Query annotation to define queries and retrieve domain objects in a relational database with Spring Data JPA 107 3.6 Using Criteria API with Spring Data JPA 111 Technique: Using Criteria API to manage domain objects in a relational database with Spring Data JPA 111 3.7 Using QueryDSL with Spring Data JPA 114 Technique: Using QueryDSL to manage domain objects in a relational database with Spring Data JPA 114 3.8 Managing domain object relationships 119 Technique: Managing domain objects with many-to-many relationships in a relational database with Spring Data JPA 121 4 Spring Boot: Autoconfiguration and Actuator 131 4.1 Understanding Spring Boot autoconfiguration 132 Understanding @Conditional annotation 134 ■ Deep dive into autoconfiguration 136 4.2 Using Spring Boot DevTools 139 Property defaults 139 ■ Automatic restart 140 ■ Live reload 140 4.3 Creating a custom failure analyzer 140 Technique: Creating a custom Spring Boot FailureAnalyzer 141 4.4 Spring Boot Actuator 144 Technique: Configuring Spring Boot Actuator in a Spring Boot application 145 ■ Understanding Spring Boot Actuator
📄 Page
9
CONTENTSviiiendpoints 146 ■ Managing Spring Boot Actuator endpoints 149 ■ Health endpoint deep dive 150 Creating a custom Spring Boot HealthIndicator 154 Technique: Defining a custom Spring Boot actuator HealthIndicator 155 4.5 Info endpoint deep dive 158 Technique: Configuring info Spring Boot Actuator endpoint 158 Technique: Configuring a custom info contributor to provide custom application info in the Spring Boot Actuator endpoint 162 4.6 Creating a custom Spring Boot Actuator endpoint 164 Technique: Creating a custom Spring Boot actuator endpoint 164 Spring Boot actuator metrics 170 ■ Creating custom metrics 174 Gauge 176 ■ Metrics dashboard with Prometheus and Grafana 179 5 Securing Spring Boot applications 184 5.1 Introducing Spring Security 185 5.2 Hello Spring Security with Spring Boot 187 Technique: Enabling application security with Spring Security in a Spring Boot application 187 ■ Filter, FilterChain, and Spring Security 192 ■ Spring Security architecture 195 Authenticating a user 197 ■ Spring Security autoconfiguration 200 5.3 Using Spring Security 202 Technique: Customizing the default Spring Security login page of a Spring Boot application 202 ■ Technique: Configuring in- memory authentication with custom users in Spring Security in a Spring Boot application 207 ■ Technique: Configuring JDBC authentication with Spring Security in a Spring Boot application 215 ■ Technique: Implementing JDBC authentication with custom UserDetailsService in a Spring Boot application 219 Technique: Implementing LDAP authentication in a Spring Boot application 224 ■ Technique: Implementing HTTP basic authentication in a Spring Boot application 229 6 Implementing additional security with Spring Security 233 6.1 Enabling HTTPS in a Spring Boot application 235 Technique: Enabling HTTPS in a Spring Boot application 235 6.2 Securing secrets in Spring Cloud Vault 238 Technique: Managing application secrets with HashiCorp Vault in a Spring Boot application 239
📄 Page
10
CONTENTS ix6.3 Implementing user registration 242 Technique: Implementing user registration with Spring Security in a Spring Boot application 242 6.4 Implementing email verification at user registration 251 Technique: Validating user email addresses in a Spring Boot application 251 6.5 Controlling multiple incorrect login attempts 261 Technique: Controlling multiple incorrect login attempts in a Spring Boot application 261 6.6 Implementing a Remember Me feature 267 Technique: Enabling a Remember Me feature in a Spring Boot application with Spring Security 268 6.7 Implementing reCAPTCHA 270 Technique: Enabling Google reCAPTCHA in a Spring Boot application with Spring Security 271 6.8 Enabling two-factor authentication with Google Authenticator 276 Technique: Enabling two-factor authentication in a Spring Boot application 276 6.9 Authentication with OAuth2 287 Technique: Enabling sign in with Google in a Spring Boot application 288 6.10 Securing Actuator endpoints 292 Technique: Securing Spring Boot Actuator endpoints 294 7 Developing RESTful Web services with Spring Boot 297 7.1 Developing a RESTful API with Spring Boot 298 Technique: Developing a RESTful API using Spring Boot 298 7.2 Managing exceptions in a Spring Boot RESTful API 306 Technique: Handling exceptions in a RESTful API 306 7.3 Testing a RESTful API 311 Technique: Testing a RESTful API in a Spring Boot application 311 7.4 Documenting a RESTful API 317 Technique: Documenting a RESTful API with OpenAPI 317
📄 Page
11
CONTENTSx7.5 Implementing RESTful API versioning 323 Technique: Implementing versioning in a RESTful API 324 7.6 Securing a RESTful API 334 Technique: Using JWT to authorize RESTful API requests 335 PART 3 .................................................................... 347 8 Reactive Spring Boot application development 349 8.1 Introduction to reactive programming 350 Backpressure 353 ■ Benefits of reactive programming 354 8.2 Understanding Project Reactor 355 8.3 Introducing Spring WebFlux 358 Technique: Developing a reactive RESTful API with annotated controllers 359 ■ Technique: Developing a reactive RESTful API with functional endpoints 367 8.4 Testing reactive applications 372 Technique: Using WebClient to build an API client 373 8.5 Introduction to RSocket 378 Technique: Developing applications using RSocket and Spring Boot 379 8.6 Introduction to WebSocket 388 Technique: Developing an application using WebSocket and Spring Boot 389 PART 4 .................................................................... 397 9 Deploying Spring Boot applications 399 9.1 Running Spring Boot applications as executable JAR files 401 Technique: Packaging and executing a Spring Boot application as an executable JAR file 401 9.2 Deploying Spring Boot applications as WAR in the WildFly application server 406 Technique: Packaging and deploying a Spring Boot application as WAR in the WildFly application server 407
📄 Page
12
CONTENTS xi9.3 Deploying Spring Boot applications in Cloud Foundry 416 Technique: Deploying a Spring Boot application to Cloud Foundry 417 9.4 Deploying Spring Boot applications in Heroku 420 Technique: Deploying a Spring Boot application in Heroku 420 9.5 Running Spring Boot applications as Docker containers 423 Technique: Creating a container image and running a Spring Boot application as a container 424 9.6 Deploying Spring Boot applications in a Kubernetes cluster 429 Technique: Deploying a Spring Boot application in a Kubernetes cluster 429 9.7 Deploying Spring Boot applications in Red Hat OpenShift 434 Technique: Deploying a Spring Boot application in the Red Hat OpenShift platform 434 PART 5 .................................................................... 439 10 Spring Boot with Kotlin, Native Image, and GraphQL 441 10.1 Spring Boot with Kotlin 442 Technique: Developing a Spring Boot application with Kotlin 443 Technique: Securing a Spring Boot Kotlin application with Spring Security 449 10.2 Introducing Spring Native 453 Introduction to GraalVM 453 ■ GraalVM native image 454 Spring Boot native image 455 ■ Technique: Generating Spring Boot native image using buildpacks 455 ■ Technique: Generating Spring Boot native image using a Maven plugin 460 Understanding Spring AOT Maven Plugin 463 10.3 Spring Boot with GraphQL 464 Issues with REST 464 ■ Introduction to GraphQL 466 Using GraphQL with Spring Boot 467 ■ Technique: Developing a GraphQL API with a Spring Boot application 467 ■ Technique:
📄 Page
13
CONTENTSxiiDeveloping a GraphQL API over WebSocket with a Spring Boot application 483 appendix A Generating and building Spring Boot projects 486 appendix B Spring MVC and Thymeleaf Template Engine 522 index 549
📄 Page
14
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 possibili- ties, 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 applica- tion 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!xiii
📄 Page
15
FOREWORDxiv After the primer, it feels like we’re working our way up the conceptual ladder, start- ing 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 rela- tively new projects, so I am delighted to see them covered here in this book, your reli- able 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
📄 Page
16
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 inter- net. 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 auto- configuration, 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 thexv
📄 Page
17
PREFACExvireaders 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. Con- cepts 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 sug- gestions 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/.
📄 Page
18
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 mean- ing 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.xvii
📄 Page
19
ACKNOWLEDGMENTSxviii 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.
📄 Page
20
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 pro- vide 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 develop- ers 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 fea- tures, such as Spring Boot with GraalVM Native Image, GraphQL, and reactive appli- cation 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.xix