P IN RACTICE Somnath Musib Foreword by Josh Long M A N N I N G Spring Boot in Practice SOMNATH MUSIB Foreword by JOSH LONG MANNING SHELTER ISLAND 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: [email protected] ©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 Batinic´ 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 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 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 iivv 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 21 v vi CONTENTS 1.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 CONTENTS vii 3.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 viii CONTENTS endpoints 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 CONTENTS ix 6.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