Explore 1.5M+ audiobooks & ebooks free for days

Only $12.99 CAD/month after trial. Cancel anytime.

Mastering Spring Boot 3.0: A comprehensive guide to building scalable and efficient backend systems with Java and Spring
Mastering Spring Boot 3.0: A comprehensive guide to building scalable and efficient backend systems with Java and Spring
Mastering Spring Boot 3.0: A comprehensive guide to building scalable and efficient backend systems with Java and Spring
Ebook614 pages4 hours

Mastering Spring Boot 3.0: A comprehensive guide to building scalable and efficient backend systems with Java and Spring

Rating: 0 out of 5 stars

()

Read preview
LanguageEnglish
PublisherPackt Publishing
Release dateJun 28, 2024
ISBN9781803245027
Mastering Spring Boot 3.0: A comprehensive guide to building scalable and efficient backend systems with Java and Spring

Related to Mastering Spring Boot 3.0

Related ebooks

Programming For You

View More

Reviews for Mastering Spring Boot 3.0

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

    Mastering Spring Boot 3.0 - Ahmet Meric

    Cover.png

    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

    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

    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.

    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.

    Table of Contents

    Preface

    Part 1: Architectural Foundations

    1

    Introduction to Advanced Spring Boot Concepts

    Technical requirements

    Why use Spring Boot for advanced projects?

    The complexity of modern software development

    The advantages of Spring Boot

    Embracing the new era – the innovations of Spring Boot 3.0

    Wrapping up – why Spring Boot 3.0 is your advanced project ally

    A brief overview of what’s to come

    Chapter 2, Key Architectural Patterns in Microservices – DDD, CQRS, and Event Sourcing

    Chapter 3, Reactive REST Development and Asynchronous Systems

    Chapter 4, Spring Data: SQL, NoSQL, Cache Abstraction, and Batch Processing

    Chapter 5, Securing Your Spring Boot Applications

    Chapter 6, Advanced Testing Strategies

    Chapter 7, Spring Boot 3.0 Features for Containerization and Orchestration

    Chapter 8, Exploring Event-Driven Systems with Kafka

    Chapter 9, Enhancing Productivity and Development Simplification

    Summary

    Part 2: Architectural Patterns and Reactive Programming

    2

    Key Architectural Patterns in Microservices – DDD, CQRS, and Event Sourcing

    Technical requirements

    Introduction to architectural patterns in microservices

    Why do we need an architectural design in the first place?

    What are design patterns?

    What are microservices?

    What are the principles behind microservices?

    Microservices design patterns

    Exploring DDD

    What is a domain exactly?

    What is DDD?

    How to define DDD structure?

    Learning about CQRS

    What is the context of CQRS?

    What are best practices and common pitfalls?

    What are the benefits of the CQRS design pattern?

    Understanding Event Sourcing

    Event-Driven Architecture

    What is Event Sourcing?

    Differences between Event-Driven Architecture and Event Sourcing

    A real-world example of the Event Sourcing pattern

    The relation of Event Sourcing with CQRS

    A real-world example of CQRS with Event Sourcing

    Brief overview of other architectural patterns

    Service Oriented Architecture (SOA) design pattern

    The Circuit Breaker pattern

    The Layered design pattern

    The MVC design pattern

    The Saga design pattern

    Summary

    3

    Reactive REST Development and Asynchronous Systems

    Technical requirements

    Introduction to reactive programming

    Introducing reactive programming basics

    Contrasting paradigms – reactive versus traditional programming

    Exploring the dictionary of reactive programming

    Identifying opportunities for reactive programming

    Learning from the field – reactive programming in action

    Leveraging Spring Boot 3.0 for reactive solutions

    Wrapping up and looking forward

    Building a reactive REST API

    Setting up the development environment

    Implementing the repository layer

    Building the reactive REST controller

    Adding advanced Mono operations

    Running the Spring Boot application with Gradle and Java 17

    Conclusion

    Asynchronous systems and backpressure

    Diving into backpressure

    Implementing backpressure in the project

    Observations and conclusions

    Summary

    Part 3: Data Management, Testing, and Security

    4

    Spring Data: SQL, NoSQL, Cache Abstraction, and Batch Processing

    Technical requirements

    Introduction to Spring Data

    Understanding the fundamentals and benefits of Spring Data

    Setting up your Spring Boot project

    Using Spring Data with SQL databases

    Integrating PostgreSQL with Spring Boot using Docker

    Developing complex relationships between entities

    Implementing practical CRUD operations in the online bookstore

    NoSQL databases in Spring Boot

    Exploring the integration of NoSQL databases in Spring Boot

    Setting up and configuring MongoDB

    Building the Review object and its repository

    Implementing a hybrid data model in the online bookstore

    Spring Boot cache abstraction

    Understanding cache abstraction

    Configuring and using cache abstraction in the application

    In conclusion

    Spring Boot batch processing

    Understanding the role of batch processing in Spring Boot

    Implementing Spring Batch

    Executing the batch job

    Data migration and consistency

    Exploring data migration strategies and tools like Liquibase

    Practical steps for implementing data migration using Liquibase

    Implementing migration strategies in the online bookstore

    Summary

    5

    Securing Your Spring Boot Applications

    Technical requirements

    Introducing security in Spring Boot 3.0

    Exploring Spring Boot 3.0’s security features

    Setting up a basic security configuration

    Implementing OAuth2 and JWT

    Configuring OAuth2 with Keycloak

    Testing our endpoints with an access token

    Implementing RBAC in Spring Boot

    Defining roles and permissions in Keycloak

    Tailoring the book store application for role-based access

    Summary

    6

    Advanced Testing Strategies

    Technical requirements

    TDD in Spring Boot

    Implementing TDD

    Discussing terminology for unit tests

    Unit testing of controllers with a security layer

    Key annotations for Spring MVC controller testing

    Crafting controller tests with Spring annotations

    Integration testing – bridging components together

    Setting up the testing environment

    Configuring application properties for integration testing

    Initializing the database with Testcontainers

    Mocking external services with WireMock

    Writing integration tests for Author Controller

    Testing reactive components

    Setting up the testing environment

    Preparing mock components

    Writing test cases

    Summary

    Part 4: Deployment, Scalability, and Productivity

    7

    Spring Boot 3.0 Features for Containerization and Orchestration

    Technical requirements

    Containerization and orchestration in Spring Boot

    Understanding containerization – your app in a box

    Reaping the benefits – lighter loads, quicker starts

    Getting Spring Boot in the game – container-friendly from the start

    Unleashing Spring Boot superpowers – portability, efficiency, and control

    Spring Boot and Docker

    Crafting efficient Docker images with layered jars

    Simplifying Dockerization with Cloud Native Buildpacks

    Enhancing graceful shutdown capabilities

    Optimizing Spring Boot apps for Kubernetes

    Integrating Kubernetes probes for application health

    Managing configurations and Secrets with Kubernetes

    Utilizing profile-specific configurations in Kubernetes

    Spring Boot Actuator with Prometheus and Grafana

    Integrating Prometheus for metrics collection

    Visualizing metrics with Grafana

    Summary

    8

    Exploring Event-Driven Systems with Kafka

    Technical requirements

    Introduction to event-driven architecture

    Setting up Kafka and ZooKeeper for local development

    Understanding Kafka brokers and their role in event-driven systems

    Running Kafka and ZooKeeper with Docker

    Building an event-driven application with Spring Boot messaging

    Creating a Spring Boot project for Kafka integration

    Building the producer application

    Building the consumer application

    Testing the whole stack – bringing your event-driven architecture to life

    Monitoring event-driven systems

    Monitoring your Kafka infrastructure

    Using CMAK to monitor the Kafka server

    Summary

    9

    Enhancing Productivity and Development Simplification

    Technical requirements

    Introducing AOP in Spring Boot

    Exploring the basics of AOP – join points, pointcuts, advice declarations, and weaving

    Crafting a logging aspect – a step-by-step example

    Simplifying HTTP API with the Feign Client

    What is the Feign Client?

    Implementing the Feign Client in Spring Boot

    Advanced Spring Boot auto-configuration

    What is advanced auto-configuration?

    Understanding conditional configuration

    Common pitfalls and best practices

    Embracing best practices in Spring Boot – AOP, the Feign Client, and advanced auto-configuration

    Navigating common pitfalls in Spring Boot – AOP, the Feign Client, and advanced auto-configuration

    Real-world example – incorrectly scoped proxies in AOP

    Summary

    Index

    Other Books You May Enjoy

    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.

    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.

    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.

    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 [email protected]

    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 [email protected]

    with a link to the material.

    If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com

    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.

    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:

    Scan the QR code or visit the following link:

    https://packt.link/free-ebook/9781803230788

    Submit your proof of purchase.

    That’s it! We’ll send your free PDF and other benefits to your email directly.

    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

    1

    Introduction to Advanced Spring Boot Concepts

    Welcome to this guide to mastering projects with Spring Boot 3.0. This book isn’t a manual; instead, it serves as your roadmap to navigate the complex world of modern Java development. Spring Boot is not a newcomer but a mature framework that has been simplifying Java development for years. But in the 3.0 release, Spring Boot has made the development process even more seamless and more convenient to use. Java 17 is the minimum version of Java required with Spring Boot 3.0, and Java 19 is also among the versions supported, which ensures that developers will be able to utilize the latest features or improvements of Java. Spring Boot 3.0 presents AppStartup – a feature to register callbacks in different stages of application startup, aiding with tasks such as resource initialization and configuration error checking. In addition to that, there is a new algorithm in Spring Boot 3.0 for dependency resolution to help increase the start speed and lower the memory footprint, so more complex projects are handled more efficiently.

    By the time you finish reading this book, you will not just be familiar but proficient, efficient, and, most importantly, capable of implementing Spring Boot effectively in real-world scenarios.

    So, what can you expect in this chapter? We will delve into why Spring Boot stands out as the preferred framework for projects. We’ll explore its advantages and the new features of Spring Boot 3.0. This chapter lays the foundation for using Spring Boot 3.0 more effectively, ensuring you can tackle complex projects confidently and skillfully. Let’s dive in!

    In this chapter, we’re going to cover the following main topics:

    Why use Spring Boot for advanced projects?

    A brief overview of what’s to come

    Technical requirements

    There are no technical requirements for this chapter. The code blocks included in this chapter are used to explain certain concepts and are not meant to be executed.

    Why use Spring Boot for advanced projects?

    Welcome to the beginning of your journey into the world of Spring Boot 3.0! In this section, we are going to talk about the potential that Spring Boot has for creating the most sophisticated software projects. We are going to elaborate on why Spring Boot is more than a framework but less simple. It will be your best friend in dealing with the complicated challenges of software development.

    The complexity of modern software development

    First, let’s clarify the complexity of modern software development. As you will know, there are lots of different challenges that arise in software projects. When we have a task or a project, we need to consider scalability, data security, orchestrating services in a cloud environment, and much more. In the old days, a developer was responsible for the code quality and performance. But now, we need to think about and cover the whole stack.

    Look at modern applications. They have to adjust to the evolving dynamics of user needs, they have to leverage cloud-native capabilities and cutting-edge technologies, and they have to stay secure all the time. Doing all this, while ensuring a responsive and reliable experience for users, is not easy.

    I can sense apprehension in your eyes. Don’t be afraid; we have a perfect tool to beat all these difficulties. It is a tool to help us navigate through this complicated landscape. It is a framework that simplifies development and enables developers to make strides in meeting the mentioned challenges. That tool is Spring Boot – its benefits make it a strong candidate for future projects.

    Let’s now delve into why Spring Boot stands out as the framework of choice for handling advanced software projects.

    The advantages of Spring Boot

    This section consists of the various advantages of Spring Boot. We are going to go through these advantages and discuss how they make our lives easier and how we can use them.

    Advantage 1 – rapid development

    In the world of software development, time is the most crucial resource. We should get our product ready for market as soon as possible because the market is so competitive. Spring Boot offers a streamlined development experience, making it an outstanding choice for many developers. It eliminates the need for boilerplate configuration, enabling you to concentrate on writing business logic. With Spring Boot’s auto-configuration and starter dependencies, you can set up a project in minutes rather than hours. This feature alone saves a lot of time and effort, allowing developers to focus on what they do best – writing code. As you can see in Figure 1.1, just one click in Spring Initializr is enough to start developing.

    Figure 1.1: Spring Initializr page

    Figure 1.1: Spring Initializr page

    Imagine the benefits of rapid development. It means you deliver faster,

    Enjoying the preview?
    Page 1 of 1