Registered users can read the full content for free
Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.
Page
1
(This page has no text content)
Page
2
Mastering Spring Boot 3.0 A comprehensive guide to building scalable and efficient backend systems with Java and Spring Ahmet Meric
Page
3
Mastering Spring Boot 3.0 Copyright © 2024 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. The author acknowledges the use of cutting-edge AI, such as ChatGPT, with the sole aim of enhancing the language and clarity within the book, thereby ensuring a smooth reading experience for readers. It’s important to note that the content itself has been crafted by the author and edited by a professional publishing team. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. Group Product Manager: Kaustubh Manglurkar Publishing Product Manager: Urvi Shah Book Project Manager: Sonam Pandey Senior Editor: Rashi Dubey Technical Editor: K Bimala Singha Copy Editor: Safis Editing Proofreader: Rashi Dubey Indexer: Tejal Daruwale Soni Production Designer: Prafulla Nikalje DevRel Marketing Coordinators: Nivedita Pandey and Anamika Singh First published: July 2024 Production reference: 1070624 Published by Packt Publishing Ltd. Grosvenor House 11 St Paul’s Square Birmingham B3 1RB, UK ISBN 978-1-80323-078-8 www.packtpub.com
Page
4
This book is the culmination of years of effort, and it owes much to the endless patience and understanding of my dear wife and beloved children. I must also extend my deepest gratitude to my father, whose profound support and academic spirit have inspired me every step of the way. Your belief in my abilities has been a guiding light. – Ahmet Meric
Page
5
Contributors About the author Ahmet Meric, with over 20 years of Java development expertise, has excelled in various roles, including Senior Engineer, Tech Lead, and Head of Engineering. He has led software development and architecture, streamlining transitions to microservices in diverse domains such as aviation, fintech, and energy. His career has spanned multiple countries, including Italy, Turkey, the KSA, the USA, and the UK, enriching his approach with global insights. Known for his strategic prowess in modernizing legacy systems, Ahmet is a mentor and thought leader, constantly engaged with the latest industry trends. He resides in the UK with his family. I want to thank my father, who has always supported and inspired me, as well as my wife for her patience.
Page
6
About the reviewers Anand Saurabh, a seasoned software developer with over 6 years of experience in full-stack development, holds a BE in Computer Science from Rajiv Gandhi Proudyogiki Vishwavidyalaya, Bhopal. With stints at Accenture and Publicis Sapient, and a current role at a product-based company, Anand has demonstrated his prowess in the field. He’s deeply interested in AI/ML and has earned recognition for his innovative ideas, including the Most Innovative Idea Award from Yahoo and Accenture. Anand’s achievements have been widely acknowledged; he’s appeared in over 16 newspapers, articles, and news channels, showcasing his contributions to the tech industry. Deepak Vohra is an Oracle Certified Java Programmer and an Oracle Certified Web Component Developer. Deepak is the author of Packt’s Amazon Fargate Quick Start Guide, Processing XML documents with Oracle JDeveloper 11g, JDBC 4.0 and Oracle JDeveloper for J2EE Development, and EJB 3.0 Database Persistence with Oracle Fusion Middleware 11g.
Page
7
(This page has no text content)
Page
8
Preface xiii Part 1: Architectural Foundations 1 Introduction to Advanced Spring Boot Concepts 3 Technical requirements 4 Why use Spring Boot for advanced projects? 4 The complexity of modern software development 4 The advantages of Spring Boot 4 Embracing the new era – the innovations of Spring Boot 3.0 11 Wrapping up – why Spring Boot 3.0 is your advanced project ally 14 A brief overview of what’s to come 14 Chapter 2, Key Architectural Patterns in Microservices – DDD, CQRS, and Event Sourcing 15 Chapter 3, Reactive REST Development and Asynchronous Systems 15 Chapter 4, Spring Data: SQL, NoSQL, Cache Abstraction, and Batch Processing 16 Chapter 5, Securing Your Spring Boot Applications 17 Chapter 6, Advanced Testing Strategies 17 Chapter 7, Spring Boot 3.0 Features for Containerization and Orchestration 18 Chapter 8, Exploring Event-Driven Systems with Kafka 19 Chapter 9, Enhancing Productivity and Development Simplification 19 Summary 20 Table of Contents
Page
9
Table of Contentsviii Part 2: Architectural Patterns and Reactive Programming 2 Key Architectural Patterns in Microservices – DDD, CQRS, and Event Sourcing 23 Technical requirements 24 Introduction to architectural patterns in microservices 24 Why do we need an architectural design in the first place? 24 What are design patterns? 25 What are microservices? 25 What are the principles behind microservices? 26 Microservices design patterns 26 Exploring DDD 28 What is a domain exactly? 29 What is DDD? 29 How to define DDD structure? 30 Learning about CQRS 32 What is the context of CQRS? 33 What are best practices and common pitfalls? 33 What are the benefits of the CQRS design pattern? 34 Understanding Event Sourcing 35 Event-Driven Architecture 35 What is Event Sourcing? 36 Differences between Event-Driven Architecture and Event Sourcing 38 A real-world example of the Event Sourcing pattern 39 The relation of Event Sourcing with CQRS 41 A real-world example of CQRS with Event Sourcing 45 Brief overview of other architectural patterns 46 Service Oriented Architecture (SOA) design pattern 46 The Circuit Breaker pattern 47 The Layered design pattern 48 The MVC design pattern 49 The Saga design pattern 50 Summary 52 3 Reactive REST Development and Asynchronous Systems 53 Technical requirements 53 Introduction to reactive programming 54 Introducing reactive programming basics 54 Contrasting paradigms – reactive versus traditional programming 55 Exploring the dictionary of reactive programming 56
Page
10
Table of Contents ix Identifying opportunities for reactive programming 57 Learning from the field – reactive programming in action 58 Leveraging Spring Boot 3.0 for reactive solutions 59 Wrapping up and looking forward 60 Building a reactive REST API 61 Setting up the development environment 61 Implementing the repository layer 64 Building the reactive REST controller 66 Adding advanced Mono operations 68 Running the Spring Boot application with Gradle and Java 17 69 Conclusion 71 Asynchronous systems and backpressure 72 Diving into backpressure 72 Implementing backpressure in the project 74 Observations and conclusions 77 Summary 77 Part 3: Data Management, Testing, and Security 4 Spring Data: SQL, NoSQL, Cache Abstraction, and Batch Processing 81 Technical requirements 82 Introduction to Spring Data 82 Understanding the fundamentals and benefits of Spring Data 83 Setting up your Spring Boot project 84 Using Spring Data with SQL databases 86 Integrating PostgreSQL with Spring Boot using Docker 86 Developing complex relationships between entities 88 Implementing practical CRUD operations in the online bookstore 89 NoSQL databases in Spring Boot 92 Exploring the integration of NoSQL databases in Spring Boot 92 Setting up and configuring MongoDB 93 Building the Review object and its repository 94 Implementing a hybrid data model in the online bookstore 95 Spring Boot cache abstraction 96 Understanding cache abstraction 97 Configuring and using cache abstraction in the application 97 In conclusion 99 Spring Boot batch processing 100 Understanding the role of batch processing in Spring Boot 100 Implementing Spring Batch 101 Executing the batch job 104 Data migration and consistency 105 Exploring data migration strategies and tools like Liquibase 105 Practical steps for implementing data migration using Liquibase 106 Implementing migration strategies in the online bookstore 107 Summary 109
Page
11
Table of Contentsx 5 Securing Your Spring Boot Applications 111 Technical requirements 112 Introducing security in Spring Boot 3.0 112 Exploring Spring Boot 3.0’s security features 112 Setting up a basic security configuration 114 Implementing OAuth2 and JWT 116 Configuring OAuth2 with Keycloak 116 Testing our endpoints with an access token 127 Implementing RBAC in Spring Boot 129 Defining roles and permissions in Keycloak 130 Tailoring the book store application for role-based access 132 Summary 139 6 Advanced Testing Strategies 141 Technical requirements 142 TDD in Spring Boot 142 Implementing TDD 143 Discussing terminology for unit tests 146 Unit testing of controllers with a security layer 147 Key annotations for Spring MVC controller testing 148 Crafting controller tests with Spring annotations 149 Integration testing – bridging components together 152 Setting up the testing environment 153 Configuring application properties for integration testing 154 Initializing the database with Testcontainers 155 Mocking external services with WireMock 157 Writing integration tests for Author Controller 158 Testing reactive components 159 Setting up the testing environment 159 Preparing mock components 160 Writing test cases 161 Summary 162
Page
12
Table of Contents xi Part 4: Deployment, Scalability, and Productivity 7 Spring Boot 3.0 Features for Containerization and Orchestration 165 Technical requirements 166 Containerization and orchestration in Spring Boot 166 Understanding containerization – your app in a box 166 Reaping the benefits – lighter loads, quicker starts 167 Getting Spring Boot in the game – container- friendly from the start 167 Unleashing Spring Boot superpowers – portability, efficiency, and control 168 Spring Boot and Docker 168 Crafting efficient Docker images with layered jars 169 Simplifying Dockerization with Cloud Native Buildpacks 170 Enhancing graceful shutdown capabilities 171 Optimizing Spring Boot apps for Kubernetes 172 Integrating Kubernetes probes for application health 173 Managing configurations and Secrets with Kubernetes 177 Utilizing profile-specific configurations in Kubernetes 179 Spring Boot Actuator with Prometheus and Grafana 181 Integrating Prometheus for metrics collection 181 Visualizing metrics with Grafana 184 Summary 187 8 Exploring Event-Driven Systems with Kafka 189 Technical requirements 190 Introduction to event-driven architecture 190 Setting up Kafka and ZooKeeper for local development 191 Understanding Kafka brokers and their role in event-driven systems 192 Running Kafka and ZooKeeper with Docker 193 Building an event-driven application with Spring Boot messaging 195 Creating a Spring Boot project for Kafka integration 196 Building the producer application 198 Building the consumer application 199 Testing the whole stack – bringing your event-driven architecture to life 201 Monitoring event-driven systems 202 Monitoring your Kafka infrastructure 203 Using CMAK to monitor the Kafka server 204 Summary 207
Page
13
Table of Contentsxii 9 Enhancing Productivity and Development Simplification 209 Technical requirements 210 Introducing AOP in Spring Boot 210 Exploring the basics of AOP – join points, pointcuts, advice declarations, and weaving 211 Crafting a logging aspect – a step-by-step example 211 Simplifying HTTP API with the Feign Client 214 What is the Feign Client? 214 Implementing the Feign Client in Spring Boot 214 Advanced Spring Boot auto-configuration 217 What is advanced auto-configuration? 217 Understanding conditional configuration 218 Common pitfalls and best practices 219 Embracing best practices in Spring Boot – AOP, the Feign Client, and advanced auto-configuration 219 Navigating common pitfalls in Spring Boot – AOP, the Feign Client, and advanced auto-configuration 221 Real-world example – incorrectly scoped proxies in AOP 222 Summary 222 Index 225 Other Books You May Enjoy 234
Page
14
Preface Mastering Spring Boot 3.0 provides an in-depth exploration of Spring Boot 3.0, focusing on its advanced features. The technology is positioned as essential for Java developers who are eager to build complex and scalable backend systems. The introduction sets the stage for a comprehensive guide through the capabilities of Spring Boot 3.0, emphasizing its utility in modern software development. Who this book is for If you're a Java developer eager to elevate your skills, then Mastering Spring Boot 3.0 is for you. Microservices architects, DevOps engineers, and technical leads who want to enhance their skills in building powerful backend systems with advanced Spring Boot features will also find this book useful. A foundational understanding of microservices architecture and some experience with RESTful APIs will help you get the most out of this book. What this book covers Chapter 1, Introduction to Advanced Spring Boot Concepts, introduces advanced features of Spring Boot 3.0, providing a foundation for the subsequent chapters. Chapter 2, Key Architectural Patterns in Microservices – DDD, CQRS, and Event Sourcing, explores essential architectural patterns such as DDD, CQRS, and Event Sourcing, providing both theoretical knowledge and practical examples. Chapter 3, Reactive REST Development and Asynchronous Systems, covers reactive programming within Spring Boot and asynchronous systems’ implementation details. Chapter 4, Spring Data: SQL, NoSQL, Cache Abstraction, and Batch Processing, discusses managing data using Spring Data, including SQL and NoSQL databases, and introduces cache abstraction and batch processing. Chapter 5, Securing Your Spring Boot Applications, provides a comprehensive look at securing Spring Boot applications using OAuth2, JWT, and Spring Security filters. Chapter 6, Advanced Testing Strategies, delves into testing strategies in Spring Boot applications, focusing on unit, integration, and security testing techniques. Chapter 7, Spring Boot 3.0 Features for Containerization and Orchestration, focuses on containerization and orchestration features of Spring Boot 3.0, including Docker and Kubernetes integration.
Page
15
Prefacexiv Chapter 8, Exploring Event-Driven Systems with Kafka, explores the integration of Kafka with Spring Boot for building event-driven systems and includes monitoring and troubleshooting tips. Chapter 9, Enhancing Productivity and Development Simplification, focuses on simplifying development processes through tools and techniques such as aspect-oriented programming and custom Spring Boot starters. To get the most out of this book You will need to have essential knowledge of Java 17 before reading this book. The Java Development Kit (JDK 17) should be installed on your computer. All the code examples have been tested using JDK 17 on macOS. However, they should work on other operating systems. Software/hardware covered in the book Operating system requirements JDK 17 Windows, macOS, or Linux Gradle 8.7 Docker Desktop IDE IntelliJ Community Edition, Eclipse If you are using the digital version of this book, we advise you to type the code yourself or access the code from the book’s GitHub repository (a link is available in the next section). Doing so will help you avoid any potential errors related to the copying and pasting of code. Download the example code files You can download the example code files for this book from GitHub at https://github.com/ PacktPublishing/Mastering-Spring-Boot-3.0. If there’s an update to the code, it will be updated in the GitHub repository. We also have other code bundles from our rich catalog of books and videos available at https:// github.com/PacktPublishing/. Check them out! Conventions used There are a number of text conventions used throughout this book. Code in text: Indicates code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles. Here is an example: “However, in the reactive world, we use ReactiveCrudRepository or R2dbcRepository.”
Page
16
Preface xv A block of code is set as follows: # Enable H2 Console spring.h2.console.enabled=true # Database Configuration for H2 spring.r2dbc.url=r2dbc:h2:mem:///testdb spring.r2dbc.username=sa spring.r2dbc.password= # Schema Generation spring.sql.init.mode=always spring.sql.init.platform=h2 Any command-line input or output is written as follows: ./gradlew bootRun Bold: Indicates a new term, an important word, or words that you see onscreen. For instance, words in menus or dialog boxes appear in bold. Here is an example: “Once you’ve made all the selections, click on the Generate button to get the ready-to-build project.” Tips or important notes Appear like this. Get in touch Feedback from our readers is always welcome. General feedback: If you have questions about any aspect of this book, email us at customercare@ packtpub.com and mention the book title in the subject of your message. Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/support/errata and fill in the form. Piracy: If you come across any illegal copies of our works in any form on the internet, we would be grateful if you would provide us with the location address or website name. Please contact us at copyright@packt.com with a link to the material. If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com
Page
17
Prefacexvi Share Your Thoughts Once you’ve read Mastering Spring Boot 3.0 we’d love to hear your thoughts! Please click here to go straight to the Amazon review page for this book and share your feedback. Your review is important to us and the tech community and will help us make sure we’re delivering excellent quality content.
Page
18
Preface xvii Download a free PDF copy of this book Thanks for purchasing this book! Do you like to read on the go but are unable to carry your print books everywhere? Is your e-book purchase not compatible with the device of your choice? Don’t worry!, Now with every Packt book, you get a DRM-free PDF version of that book at no cost. Read anywhere, any place, on any device. Search, copy, and paste code from your favorite technical books directly into your application. The perks don’t stop there, you can get exclusive access to discounts, newsletters, and great free content in your inbox daily Follow these simple steps to get the benefits: 1. Scan the QR code or visit the following link: https://packt.link/free-ebook/9781803230788 2. Submit your proof of purchase. 3. That’s it! We’ll send your free PDF and other benefits to your email directly.
Page
19
(This page has no text content)
Page
20
Part 1: Architectural Foundations In this part, we will dive into the sophisticated world of advanced spring boot concepts. This part sets the stage for a deeper understanding of how Spring Boot can be utilized to build robust and scalable applications. This part has the following chapter: • Chapter 1, Introduction to Advanced Spring Boot Concepts
The above is a preview of the first 20 pages. Register to read the complete e-book.
AI Reading Assistant
Whole-book reading guide from stratified index samples; jump to passages in the text
Brief outline
【One-Line Pitch】
Mastering Spring Boot 3.0 A comprehensive guide to building scalable and efficient backend systems with Java and Spring (Ahmet Meric) (z-library.sk, 1lib.sk, z-lib.sk) (Ahmet Meric): a quick map of the book's arc and key takeaways for busy readers.
【Book Arc】
- **Opening (~0%–12%)**: He resides in the UK with his family.; The Circuit Breaker pattern 47 What is the context of CQRS?
- **Early (~12%–35%)**: In the previous XML configuration, you saw that it was hard to see and manage data source properties.; othing less than a leap forward in our development journey.
- **Middle (~35%–65%)**: there are some best practices to follow up and some common mistakes we need to consider while we are implementing this architecture design.; on day 3, someone else grabbed another product.
- **Late (~65%–88%)**: list or read the data from the application: @GetMapping public Flux User getAllUsers() { return userRepository.findAll();; By these manual tests, we ensure that the app is working and acting as expected in various scenarios.
- **Ending (~88%–100%)**: As we conclude this section, our journey through the data landscape of Spring Boot continues.; ractically in our online bookstore.
【Key Takeaways】
- **He resides in the UK w…** (Opening): He resides in the UK with his family.
- **The Circuit Breaker pa…** (Opening): The Circuit Breaker pattern 47 What is the context of CQRS?
- **the complex world of m…** (Opening): the complex world of modern Java development.
- **In the previous XML co…** (Early): In the previous XML configuration, you saw that it was hard to see and manage data source properties.
- **othing less than a lea…** (Early): othing less than a leap forward in our development journey.
- **We kick off with an in…** (Early): We kick off with an introduction to Spring Data.
【Reading Tips】
- Use Passage locations below to jump into the text and set reading anchors
- Chinese and English guides are each generated once, then served from local cache without calling the model again
【Coverage Limits】
Compressed outline without the model (~32 index chunks). Full structured guide needs AI available.
Passage locations
Excerpt 1
The Circuit Breaker pattern 47 What is the context of CQRS? 33 The Layered design pattern 48 What are best practices and common pitfalls? 33 The MVC design p...
View in text
Excerpt 2
3.0 is an important feature, particularly for cloud-native solutions. When we have a task to develop a serverless project, Java is usually not the first opti...
View in text
Excerpt 3
o make things easier to manage. For example, within a food company, there may be separate contexts for the sales team and delivery team, each with its own ex...
View in text
Excerpt 4
everything. You could do operations such as inserting data and then get it right back out of the same place, and that works fine if you’re just doing basic c...
View in text
Recommended for You
{{#thumbnailUrl}}
{{/thumbnailUrl}}
{{^thumbnailUrl}}
{{/thumbnailUrl}}
Loading recommended books...
Failed to load, please try again later
Tip the Site
Scan the WeChat Pay or Alipay code to tip. No login required.
WeChat Pay
Alipay