Spring Boot 3.0 Cookbook - Felip Miguel Puig - E-Book

Spring Boot 3.0 Cookbook E-Book

Felip Miguel Puig

0,0
28,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

In today's dynamic landscape, crafting robust and scalable Java web applications presents formidable challenges. Spring Boot emerges as the leading framework for web and microservices development, featuring a dynamic ecosystem and seamless integrations to address a spectrum of scenarios, from scaling apps on the cloud to deploying them to production. In this book, you’ll explore its streamlined, convention-over-configuration approach, simplifying application development.
You’ll start by covering recipes showcasing Spring Boot's features. As you progress, you’ll understand how it helps streamline application development while staying ahead of technology trends. The book helps you grasp concepts effectively, explores basic REST APIs, shows you how to escalate to advanced scenarios, and tackle common cloud application challenges like security, scalability, performance optimization, and automated deployments. Dedicated sections are designed to help you stay ahead of the curve with recipes that delve into the latest trends such as containers, observability, native images, DevOps, test automation, and microservices, ensuring your applications align with evolving industry standards.
By the end of this book, you’ll be able to build and automate the deployment of a scalable and high-performing distributed solution using Spring Boot 3.

Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:

EPUB
MOBI

Seitenzahl: 479

Veröffentlichungsjahr: 2024

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Spring Boot 3.0 Cookbook

Proven recipes for building modern and robust Java web applications with Spring Boot

Felip Miguel Puig

Spring Boot 3.0 Cookbook

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.

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(s), 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: Bhavya Rao

Book Project Manager: Shagun Saini

Senior Editor: Debolina Acharyya

Technical Editor: Reenish Kulshrestha

Copy Editor: Safis Editing

Indexer: Subalakshmi Govindhan

Production Designer: Jyoti Kadam

DevRel Marketing Coordinators: Anamika Singh and Nivedita Pandey

First published: July 2024

Production reference: 1130624

Published by Packt Publishing Ltd.

Grosvenor House

11 St Paul’s Square

Birmingham

B3 1RB, UK

ISBN 978-1-83508-949-1

www.packtpub.com

To my wife, Àgata Font; you and I make the best team imaginable. To Rita, Telma, and Liam; thank you for teaching me life’s true priorities. To my mother, Pepita, and the memory of my father, Gregorio; I am grateful for the values you instilled in me.

– Felip Miguel Puig

Contributors

About the author

Felip Miguel Puig has been working in the technology industry since 2000, particularly interested in software development and Java and C#. He is currently a principal software engineer at Dynatrace, a leading company in the monitoring and observability industry. Before joining Dynatrace, Felip worked at Microsoft for 17 years in various engineering and consulting roles, where he delivered noteworthy projects for significant clients in different industries. He is an expert in cloud technology and has been working in this field since 2012.

I want to thank my wife, Àgata, for her support and patience with my geek hobbies, such as writing this book.

About the reviewers

Romit Sutariya is a software engineer skilled in enhancing applications by identifying areas for improvement, providing recommendations, and implementing solutions. He has successfully managed multiple projects utilizing Java, Spring Boot, microservices, AWS, and Kubernetes and adhering to clean coding practices for optimal quality and performance. His educational background includes an MSc in computer and information technology. Additionally, Romit holds certifications for AWS Solutions Architect Associate and Kubernetes, showcasing his dedication to continuous learning and applying new technologies to solve real-world challenges.

Ibidapo Abdulazeez is currently a master’s student at York St John University with a focus on software engineering. Prior to embarking on his graduate journey, he accumulated two years of invaluable work experience in the field of software engineering. During this time, he had the opportunity to architect, design, and develop enterprise solutions. His other areas of expertise are Amazon Web Services (AWS), Azure, and databases, to mention a few.

Table of Contents

Preface

Part 1: Web Applications and Microservices

1

Building RESTful APIs

Technical requirements

Creating a RESTful API

Getting ready

How to do it...

How it works...

There’s more...

See also

Defining responses and the data model exposed by the API

Getting ready

How to do it...

How it works...

Managing errors in a RESTful API

Getting ready

How to do it...

How it works...

There’s more...

Testing a RESTful API

Getting ready

How to do it...

How it works...

There’s more...

See also

Using OpenAPI to document our RESTful API

Getting ready

How to do it...

How it works...

Consuming a RESTful API from another Spring Boot application using FeignClient

Getting ready

How to do it...

How it works...

There’s more...

Consuming a RESTful API from another Spring Boot application using RestClient

Getting ready

How to do it...

How it works...

Mocking a RESTful API

Getting ready

How to do it...

How it works...

See also

2

Securing Spring Boot Applications with OAuth2

Technical requirements

Setting up Spring Authorization Server

Getting ready

How to do it…

How it works…

There’s more…

See also

Protecting a RESTful API using OAuth2

Getting ready

How to do it…

How it works…

Protecting a RESTful API using OAuth2 with different scopes

Getting ready

How to do it…

How it works…

There’s more…

See also

Configuring an MVC application with OpenID authentication

Getting ready

How to do it…

How it works…

See also

Logging in with Google Accounts

Getting ready

How to do it…

How it works…

See also

Integrating a RESTful API with a cloud IdP

Getting ready

How to do it…

How it works…

There’s more…

3

Observability, Monitoring, and Application Management

Technical requirements

Adding Actuator to your application

Getting ready

How to do it…

How it works…

There’s more…

See also

Creating a custom Actuator endpoint

Getting ready

How to do it…

How it works…

Using probes and creating a custom health check

Getting ready

How to do it…

How it works…

See also

Implementing distributed tracing

Getting ready

How to do it…

How it works…

There’s more…

Accessing standard metrics

Getting ready

How to do it…

How it works…

See also

Creating your own metrics

Getting ready

How to do it…

How it works…

There’s more…

Integrating your application with Prometheus and Grafana

Getting ready

How to do it…

How it works…

Changing the settings of a running application

Getting ready

How to do it…

How it works…

There’s more…

4

Spring Cloud

Technical requirements

Setting up Eureka Server

Getting ready

How to do it...

How it works...

Integrating an application in Eureka Server

Getting ready

How to do it...

How it works...

There’s more...

Scaling out the RESTful API

Getting ready

How to do it...

How it works...

Setting up Spring Cloud Gateway

Getting ready

How to do it...

How it works...

See also

Testing Spring Cloud Gateway

Getting ready

How to do it...

How it works...

Setting up Spring Cloud Config

Getting ready

How to do it...

How it works...

There’s more...

See also

Integrating distributed tracing with Spring Cloud

Getting ready

How to do it...

How it works...

Deploying Spring Boot Admin

Getting ready

How to do it...

How it works...

Protecting Spring Cloud Gateway

Getting ready

How to do it...

How it works...

Part 2: Database Technologies

5

Data Persistence and Relational Database Integration with Spring Data

Technical requirements

Connecting your application to PostgreSQL

Getting ready

How to do it...

How it works...

There’s more...

Using JdbcClient to access the database

Getting ready

How to do it...

How it works...

Using an ORM to access the database

Getting ready

How to do it...

How it works...

There’s more...

See also

Creating the database schema from our code

Getting ready

How to do it...

How it works...

There’s more...

See also

PostgreSQL integration tests with Testcontainers

Getting ready

How to do it...

How it works...

Versioning and upgrading database schema

Getting ready

How to do it...

How it works...

There’s more...

See also

Using JPQL

Getting ready

How to do it...

How it works...

There’s more...

Using Native Queries

Getting ready

How to do it...

How it works...

There’s more...

See also

Updating Operations

Getting ready

How to do it...

How it works...

See also

Using Dynamic Queries

Getting ready

How to do it...

How it works...

There’s more...

See also

Using Transactions

Getting ready

How to do it...

How it works...

There’s more...

See also

6

Data Persistence and NoSQL Database Integration with Spring Data

Technical requirements

Connecting your application to MongoDB

Getting ready

How to do it...

How it works...

There’s more...

Using Testcontainers with MongoDB

Getting ready

How to do it...

How it works...

Data indexing and sharding in MongoDB

Getting ready

How to do it...

How it works...

There’s more...

Using transactions in MongoDB

Getting ready

How to do it...

How it works...

See also

Deploying a MongoDB cluster in Testcontainers

Getting ready

How to do it...

How it works...

Managing concurrency with MongoDB

Getting ready

How to do it...

How it works...

Connecting your application to Apache Cassandra

Getting ready

How to do it...

How it works...

See also

Using Testcontainers with Cassandra

Getting ready

How to do it...

How it works...

Using Apache Cassandra templates

Getting ready

How to do it...

How it works...

There’s more...

Managing concurrency with Apache Cassandra

Getting ready

How to do it...

How it works...

Part 3: Application Optimization

7

Finding Bottlenecks and Optimizing Your Application

Technical requirements

Tuning the database connection pool

Getting ready

How to do it…

How it works…

There’s more…

Caching dependencies

Getting ready

How to do it…

How it works…

There’s more…

Using shared cache

Getting ready

How to do it…

How it works…

Using Testcontainers with Redis cache

Getting ready

How to do it…

How it works…

Creating a native image using Spring Boot

Getting ready

How to do it…

How it works…

Using GraalVM Tracing Agent to configure the native application

Getting ready

How to do it…

How it works…

There’s more…

Creating a native executable using Spring Boot

Getting ready

How to do it…

How it works…

There’s more…

Creating a native executable from a JAR

Getting ready

How to do it…

How it works…

8

Spring Reactive and Spring Cloud Stream

Technical requirements

Creating a reactive RESTful API

Getting ready

How to do it...

How it works...

There’s more...

Using a reactive API client

Getting ready

How to do it...

How it works...

Testing reactive applications

Getting ready

How to do it...

How it works...

Connecting to PostgreSQL using Spring Data R2DBC

Getting ready

How to do it...

How it works...

There’s more...

Event-driven applications with Spring Cloud Stream and RabbitMQ

Getting ready

How to do it...

How it works...

There’s more...

See also

Routing messages with Spring Cloud Stream and RabbitMQ

Getting ready

How to do it...

How it works...

See also

Error handling with Spring Cloud Stream

Getting ready

How to do it...

How it works...

See also

Part 4: Upgrading to Spring Boot 3 from Previous Versions

9

Upgrading from Spring Boot 2.x to Spring Boot 3.0

Technical requirements

Preparing the application

Getting ready

How to do it...

How it works...

See also

Preparing Spring Security

Getting ready

How to do it...

How it works...

See also

Detecting property changes

Getting ready

How to do it...

How it works...

Upgrade the project to Spring Boot 3

Getting ready

How to do it...

How it works...

Upgrading Spring Data

Getting ready

How to do it...

How it works...

There’s more...

See also

Managing Actuator changes

Getting ready

How to do it...

How it works...

See also

Managing web application changes

Getting ready

How to do it...

How it works...

There’s more...

See also

Using OpenRewrite for migration automation

Getting ready

How to do it...

How it works...

There’s more...

See also

Index

Other Books You May Enjoy

Preface

Spring Boot is Java’s most popular framework for web and microservices development. It allows you to create production-grade applications with minimal configuration, following its “convention over configuration approach.”

Spring Boot is always evolving and adapting to the latest technology trends. Its ecosystem allows you to integrate with any technology, from databases to AI, and use traversal features such as observability and security. You can use it for virtually any type of application.

In this book, we’ll cover the most common scenarios in a hands-on way, and you’ll learn the foundations to use the vast features available.

Who this book is for

This book is for Java developers who want to gain expertise in modern web development, architects designing complex systems, experienced Spring Boot developers and technology enthusiasts looking to stay up to date with the latest trends, and software engineers in need of practical solutions for everyday challenges. Hands-on experience with Java is required. Prior development experience on the cloud will be useful, but not necessary.

What this book covers

Chapter 1, Building RESTful APIs, teaches you how to write, consume, and test RESTful API with Spring Boot 3.

Chapter 2, Securing Spring Boot Applications with OAuth2, shows you how to deploy an authorization server and use it to protect a RESTful API and a website. You will learn how to authenticate users with Google accounts. You will also learn how to protect applications with Azure AD B2C.

Chapter 3, Observability, Monitoring, and Application Management, explores how to leverage the observability features available in Spring Boot with Actuator. This chapter uses Open Zipkin, Prometheus, and Grafana, consuming the observability data exposed by a Spring Boot application for monitoring.

Chapter 4, Spring Cloud, covers how to use Spring Cloud to develop a distributed system composed of several microservices. We’ll use Eureka Server, Spring Cloud Gateway, Spring Config, and Spring Boot Admin.

Chapter 5, Data Persistence and Relational Database Integration with Spring Data, delves into how to integrate an application with PostgreSQL using Spring Data JPA. You will define repositories and use Java Persistance Query Language (JPQL) and Native SQL. You will learn to use transactions, database versioning, and migrations with Flyway, and Testcontainers for integration tests.

Chapter 6, Data Persistence and NoSQL Database Integration with Spring Data, explains the benefits and trade-offs of using NoSQL databases such as MongoDB and Cassandra, teaching you how to tackle some common challenges of NoSQL databases, such as data partitioning or concurrency management. You will use Testcontainers for integration tests with MongoDB and Cassandra.

Chapter 7, Finding Bottlenecks and Optimizing Your Application, describes how to run a load test using JMeter against a Spring Boot application, apply different optimizations, such as caching or building a native application, and compare the improvements with the original results. You will also learn some useful techniques to prepare a Native application, such as using the GraalVM Tracing Agent.

Chapter 8, Spring Reactive and Spring Cloud Stream, explores how to use Spring Reactive for high concurrency scenarios, creating a reactive RESTful API, a reactive API client, and the R2DBC driver for PostgreSQL. You will learn how to create an event-driven application, using Spring Cloud Stream connected to a RabbitMQ server.

Chapter 9, Upgrading from Spring Boot 2.x to Spring Boot 3.0, explains how to manually upgrade a Spring Boot 2.6 application to the latest version of Spring Boot 3. You will prepare the application before upgrading to Spring Boot 3 and fix all the issues, step by step, after the upgrade. You will also learn how to use OpenRewrite to automate part of the migration process.

To get the most out of this book

You will need the JDK 21 for all the chapters of this book. In Chapter 9, you will also need JDK 11 and JDK 17. I recommend using a tool such as SDKMAN! to install and configure the SDK on your computer. If you use Windows, you can use the JDK installer.

I used Maven as a dependency and build system for all samples. You can optionally install it on your computer, but all projects created in this book use the Maven Wrapper, which downloads all dependencies if needed.

If you are a Windows user, I recommend using Windows Subsystem for Linux (WSL), as some of the complementary tools used in this book are available in Linux, and the scripts available in the book’s GitHub repository are tested in Linux only. Indeed, I’m a Windows user and used WSL for all the samples prepared for this book.

I also recommend installing Docker, as it’s the simplest way to run some of the services integrated with this book, such as PostgreSQL. Docker is the best option to run a distributed system, composed of different applications talking to each other on your computer. In addition, most of the integration tests use Testcontainers, which requires Docker.

I tried to explain all samples without specific IDE requirements in this book. I used Visual Studio Code, primarily for its excellent integration with WSL, but you can use any other IDE of your preference, such as IntelliJ or Eclipse.

Software/hardware covered in the book

OS requirements

OpenJDK 21

Windows, macOS, or Linux

OpenJDK 11 and 17

Windows, macOS, or Linux

Docker

Windows (recommended with WSL integration), macOS, or Linux

Prometheus

On Docker (recommended) or natively on Windows, macOS, or Linux

Grafana

On Docker (recommended) or natively on Windows, macOS, or Linux

OpenZipkin

On Docker (recommended) or natively running Java on Windows, macOS, or Linux

PostgreSQL

On Docker (recommended) or natively on Windows, macOS, or Linux.

MongoDB

On Docker (recommended) or natively on Windows, macOS, or Linux

Apache Cassandra

On Docker (recommended) or natively on Linux

RabbitMQ

On Docker (recommended) or natively on Windows, macOS, or Linux

JMeter

Windows, macOS, or Linux

An IDE such as Visual Studio Code/IntelliJ

Windows, macOS, or Linux

If you are using the digital version of this book, we advise you to type the code yourself or access the code via the GitHub repository (link 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/Spring-Boot-3.0-Cookbook. If there’s an update to the code, it will be updated on the existing GitHub repository. Some recipes use the previous recipes as the starting point. In those cases, I provide a working version in the start subfolder of each recipe and the complete version in the end folder.

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: “This behavior can be configured using the propagation attribute of the @Transactional annotation.”

A block of code is set as follows:

em.getTransaction().begin(); // do your changes em.getTransaction().commit();

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

public int getTeamCount() {     return jdbcTemplate.queryForObject("SELECT COUNT(*) FROM teams", Integer.class); }

Any command-line input or output is written as follows:

docker-compose -f docker-compose-redis.yml up

Bold: Indicates a new term, an important word, or words that you see on screen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: “If you run the application now, you’ll see a new queue named match-events-topic.score.dlq.”

Tips or important notes

Appear like this.

Sections

In this book, you will find several headings that appear frequently (Getting ready, How to do it..., How it works..., There’s more..., and See also).

To give clear instructions on how to complete a recipe, use these sections as follows.

Getting ready

This section tells you what to expect in the recipe and describes how to set up any software or any preliminary settings required for the recipe.

How to do it…

This section contains the steps required to follow the recipe.

How it works…

This section usually consists of a detailed explanation of what happened in the previous section.

There’s more…

This section consists of additional information about the recipe in order to make you more knowledgeable about the recipe.

See also

This section provides helpful links to other useful information for the recipe.

Get in touch

Feedback from our readers is always welcome.

General feedback: If you have questions about any aspect of this book, mention the book title in the subject of your message and email us at [email protected].

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, select your book, click on the Errata Submission Form link, and enter the details.

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 Spring Boot 3.0 Cookbook, 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 eBook 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 link below

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

Submit your proof of purchaseThat’s it! We’ll send your free PDF and other benefits to your email directly

Part 1:Web Applications and Microservices

In this part, we cover the basics of RESTful APIs, distributed applications, and microservices with Spring Cloud, as well as cross-functional features such as security and observability.

This part has the following chapters:

Chapter 1, Building RESTful APIsChapter 2, Securing Spring Boot Applications with Oauth2Chapter 3, Observability, Monitoring, and Application ManagementChapter 4, Spring Cloud