Spring Boot 3.0 Crash Course: Mastering Spring Boot, from Application Development to Advanced Security, Data Access, Integration and Deployment
5/5
()
About this ebook
This Spring Boot 3.0 Crash Course will teach you all you need to know to create powerful Spring applications with the latest version of the framework. You will be able to create any feature that an application may require because this book covers everything from the fundamentals to advanced features.
First things first: ge
Related to Spring Boot 3.0 Crash Course
Related ebooks
Real-World Web Development with .NET 9: Build websites and services using mature and proven ASP.NET Core MVC, Web API, and Umbraco CMS Rating: 0 out of 5 stars0 ratingsMastering Java Spring Boot: Advanced Techniques and Best Practices Rating: 0 out of 5 stars0 ratingsJava Spring Boot: From Basics to Expert Proficiency Rating: 0 out of 5 stars0 ratingsSpring Boot 3.0 Cookbook: Proven recipes for building modern and robust Java web applications with Spring Boot Rating: 0 out of 5 stars0 ratingsMastering Spring Boot 3.0: A comprehensive guide to building scalable and efficient backend systems with Java and Spring Rating: 0 out of 5 stars0 ratingsMastering Spring 5.0 Rating: 5 out of 5 stars5/5Java Spring Framework: From Basics to Expert Proficiency Rating: 0 out of 5 stars0 ratingsSpring Boot 2: How To Get Started and Build a Microservice - Third Edition Rating: 5 out of 5 stars5/5Java 17 Backend Development: Design backend systems using Spring Boot, Docker, Kafka, Eureka, Redis, and Tomcat Rating: 0 out of 5 stars0 ratingsFastAPI Cookbook: Develop high-performance APIs and web applications with Python Rating: 0 out of 5 stars0 ratingsReact and React Native: Build cross-platform JavaScript and TypeScript apps for the web, desktop, and mobile Rating: 0 out of 5 stars0 ratingsSpring Boot 3.0 Crash Course Rating: 0 out of 5 stars0 ratingsLaravel 5.x Cookbook Rating: 0 out of 5 stars0 ratingsMicroservices Deployment Cookbook Rating: 0 out of 5 stars0 ratingsPuzzles in Java: Shaping Beginners Rating: 1 out of 5 stars1/5Angular Services Rating: 0 out of 5 stars0 ratingsJava 8 to 21: Explore and work with the cutting-edge features of Java 21 (English Edition) Rating: 0 out of 5 stars0 ratingsSpring Security 3.x Cookbook Rating: 0 out of 5 stars0 ratingsHeroku Cloud Application Development Rating: 0 out of 5 stars0 ratingsUltimate Selenium WebDriver for Test Automation Rating: 0 out of 5 stars0 ratings
Programming For You
SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Microsoft Azure For Dummies Rating: 0 out of 5 stars0 ratingsPython: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5PYTHON PROGRAMMING Rating: 4 out of 5 stars4/5Beginning Programming with C++ For Dummies Rating: 4 out of 5 stars4/5Linux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Beginning Programming with Python For Dummies Rating: 3 out of 5 stars3/5The Recursive Book of Recursion: Ace the Coding Interview with Python and JavaScript Rating: 0 out of 5 stars0 ratingsPython for Data Science For Dummies Rating: 0 out of 5 stars0 ratingsProblem Solving in C and Python: Programming Exercises and Solutions, Part 1 Rating: 5 out of 5 stars5/5Algorithms For Dummies Rating: 4 out of 5 stars4/5PYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5
Reviews for Spring Boot 3.0 Crash Course
1 rating0 reviews
Book preview
Spring Boot 3.0 Crash Course - Kit Harrington
Spring Boot 3.0 Crash Course
Mastering Spring Boot, from Application Development to Advanced Security, Data Access, Integration and Deployment
Kit Harrington
Preface
This Spring Boot 3.0 Crash Course will teach you all you need to know to create powerful Spring applications with the latest version of the framework. You will be able to create any feature that an application may require because this book covers everything from the fundamentals to advanced features.
First things first: get your development environment ready and build your very first Spring Boot App. Data access, security, configuration, and testing are some of the more advanced subjects you'll cover as you go along. This crash course will teach you how to create RESTful services, use Spring Data JPA to integrate different types of data, and work with properties and YAML files to oversee configurations. You practice to manage application properties, get into the application of annotations, and master the Spring MVC architecture. It will teach you to manage form submissions, validate user input, and construct dynamic web pages using Thymeleaf templates. The book also covers topics like integrating front-end frameworks, handling errors, and deploying applications to cloud platforms and Kubernetes.
Issues with configuring URL authorization, implementing JWT authentication, and integrating with OAuth2 and OpenID Connect are some of the critical problems that are being solved in this book. Methods for troubleshooting auto-configuration issues, managing environment variables in Docker, and making use of performance testing tools such as JMeter are all topics that will be covered. Additionally, the book delves into the topic of how to integrate with Active Directory and LDAP for centralized user management and authentication.
By the time you finish this book, you will know everything there is to know about Spring Boot application development, security, and deployment, so you can confidently take on real-world projects.
In this book you will learn how to:
Discover the ins and outs of efficiently configuring a Spring Boot 3.0 development environment.
Integrate various data sources and construct strong RESTful services with the help of Spring Data JPA.
Get to know Spring Boot's properties and YAML files to set up customizable apps.
Use Spring Security and JWT tokens to implement secure authorization and authentication.
Use Thymeleaf templates to build interactive websites and easily handle form submissions.
Use Kubernetes and cloud platforms to effortlessly deploy Spring Boot applications.
Make your apps more up-to-date and responsive by incorporating front-end frameworks such as Angular and React.
Put thorough error handling strategies into your applications and handle errors gracefully.
Use Docker to manage environment variables and JMeter to optimize application performance.
Prologue
Thank you for choosing our Spring Boot 3.0 Crash Course. Hi, I'm Kit Harrington, and I'm really excited to show you how to use Spring Boot 3.0. Allow me to begin by relating a tale that exemplifies why this book is so important.
A fast-growing tech startup had me as their project manager a few years back. The success of the business hinged on creating a safe, scalable, and reliable app that could manage thousands of users with ease. These lofty expectations were squarely on my shoulders as lead developer. The complexity of integrating different technologies, guaranteeing security, and optimizing performance was a challenge for me, even though I have a lot of experience in this area. I started using Spring Boot as my primary tool at that point. An easier way to build apps using the Spring framework was made available by Spring Boot. I was able to focus on creating effective code because it made setting everything up and running much easier. Thanks to Spring Boot's robust capabilities, we were able to build and deploy features at an incredible pace. Mastering Spring Boot, though, necessitated familiarity with its foundational concepts, recommended practices, and more complex features.
That experience is the foundation of this book. I hope that by sharing what I've learned and the solutions I've found, you'll be able to build your Spring Boot applications with ease and confidence. In this book, I'll show you how to build an app using Spring Boot from the ground up, including all the necessary features and making sure it's secure, scalable, and fast. You may find at times repetition of steps while demonstrating practical examples, so apology in advance but the intention is to ensure you dont get stuck in the middle of coding the application.
In this first step, you will build your first Spring Boot app and configure your development environment. The course will teach you the ins and outs of dependency management, application configuration via properties and YAML files, and more. Annotations, data source integration with Spring Data JPA, and RESTful service construction are some of the more advanced topics that we will cover as we go along. I will demonstrate how to incorporate Spring Security authentication and authorization, two essential components of any application. In this lesson, you will find out how to secure your application from intruders by configuring basic authentication, URL authorization, and JWT authentication.
Also covered will be the basics of working with Thymeleaf templates to build dynamic web pages, accept and process form submissions, and check user input. Learn the ins and outs of integrating popular front-end frameworks such as Angular and React to create cutting-edge, mobile-friendly apps. I will show you how to package your app, make Docker images, and deploy them to cloud platforms and Kubernetes—all of which are essential steps in the development process. Managing environment variables and achieving zero downtime during deployments are topics you'll cover in this course. Using JMeter for performance testing, I will demonstrate how to optimize performance, which is essential for deliver
ing an excellent user experience. You will gain knowledge on how to locate performance issues and enhance your application to its full potential.
With the knowledge and skills, you gain from this book, you will be able to confidently construct applications that are strong, secure, and perform well. So that you can put what you learn into practice right away, I want to equip you with practical knowledge and real-world examples.
Come on, let's start making awesome Spring Boot apps!
Copyright © 2024 by GitforGits
All rights reserved. This book is protected under copyright laws and no part of it may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage and retrieval system, without the prior written permission of the publisher. Any unauthorized reproduction, distribution, or transmission of this work may result in civil and criminal penalties and will be dealt with in the respective jurisdiction at anywhere in India, in accordance with the applicable copyright laws.
Published by: GitforGits
Publisher: Sonal Dhandre
www.gitforgits.com
Printed in India
First Printing: July 2024
Cover Design by: Kitten Publishing
For permission to use material from this book, please contact GitforGits at [email protected].
Content
Preface
GitforGits
Acknowledgement
Chapter 1: Up and Running with Spring Boot
Chapter Overview
What is Spring Boot?
Emergence of Spring Boot
Relation to Spring Framework
Recent Version
Applications, Programs, and APIs
Key Features of Spring Boot
Auto-configuration
Spring Boot Starters
Embedded Servers
Production-Ready Features
Externalized Configuration
Spring Boot CLI
DevTools
Spring Initializr
Actuator
Spring Boot DevTools
Simplified Dependency Management
Simplified Testing
Application Metrics and Health Checks
Security Integration
Integration with Other Spring Projects
Reactive Programming Support
GraalVM Native Image Support
Setting up Development Environment
Installing JDK
Installing IDE
Installing Apache Maven
Installing Spring Boot CLI
Creating Spring Boot Project
Configuring IDE
Running first Spring Boot App
Exploring Project Structure
Adding Dependencies
Configuring Application Properties
Spring Boot DevTools
Spring Boot CLI
Creating First Spring Boot Application
Setting up the Project
Creating Main Application Class
Creating a REST Controller
Running the Application
Understanding Auto-configuration
Adding Dependency Injection
Exploring Application Properties
Understanding Spring Boot Dependencies
Spring Boot Starters
Maven
Dependency Management
Adding Custom Dependencies
Using Spring Boot DevTools
Dependency Exclusions
Resolving Dependency Conflicts
Using Bill of Materials (BOM)
Upgrading Dependencies
Annotations Overview
Core Annotations
Stereotype Annotations
Configuration and Bean Annotations
Dependency Injection Annotations
Spring MVC Annotations
Data Access Annotations
Testing Annotations
Actuator Annotations
Overview of Spring Boot CLI
Installing Spring Boot CLI
Creating Simple Web App with CLI
Using Spring Boot CLI for Dependency Management
Packaging Applications with Spring Boot CLI
Spring Boot CLI for Existing Projects
Prototyping
Spring Boot CLI Configuration
Spring Boot CLI with Spring Initializr
Spring Boot CLI with Groovy Templates
Summary
Chapter 2: Building First Spring Boot App
Chapter Overview
Creating a Basic RESTful Service
Main Application Class
Creating a REST Controller
Running the Application
Expanding the REST Controller
Handling GET and POST Requests
Implementing GET Requests
Implementing POST Requests
Handling PUT and DELETE Requests
Implementing PUT Requests
Implementing DELETE Requests
Using Path Variables and Request Parameters
Using Path Variables
Using Request Parameters
Using Message Converters
Built-in Message Converters
Sample Program: Working of Message Converters
Spring MVC Architecture Overview
Understanding Spring MVC
Spring MVC Core Components
Sample Program: Inner Workings of MVC Components
Error Handling in Spring Boot
Built-in Error Handling
Customizing Error Responses
Handling Validation Errors
Summary
Chapter 3: Configuration and Properties
Chapter Overview
Spring Boot Configuration Overview
Application Properties
YAML for Structured Configuration
Profiles for Environment-Specific Configurations
Externalizing and Securing Configuration
Using Application Properties
Basic Configuration
Grouping Related Properties
Configuring Logging
Profiles in Application Properties
External Configuration
Using Application Properties
Configuration with YAML Files
Setting up YAML Configuration
Advantages of YAML
Profiles with YAML
Accessing YAML Properties
Profiles and Environment Specific Configurations
Defining Profiles
Activating Profiles
Using Profile-Specific Beans
Combining Profiles
Profile-Specific Configuration Properties
Accessing Profile Information
Externalizing Configuration
Using Environment Variables
Centralized Configuration with Spring Cloud Config
@Value and @ConfigurationProperties
Using @Value
Using @ConfigurationProperties
Binding Complex Nested Properties
Validation with @ConfigurationProperties
Type-Safe Configuration Properties
Setting up Type-Safe Configuration Properties
Advanced Type-Safe Configuration
Reloading Configuration Properties at Runtime
Using Spring Cloud Context
Using Spring Cloud Bus
Handling Configuration Reloads
Monitoring Configuration Changes
Summary
Chapter 4: Spring Boot Packaging and Deployment
Chapter Overview
Packaging a Spring Boot Application
Understanding Executable JAR Files
Understanding Executable WAR Files
Process of Packaging
Automating Packaging Process
Integrating Packaging with CI/CD Pipelines
Creating Executable JAR and WAR Files
Creating an Executable JAR File
Creating an Executable WAR File
Deploying to Tomcat
Install Tomcat and Copy WAR File
Start the Tomcat Server
Verifying Deployment
Hot Deployment and Redeployment
Managing Tomcat Deployments
Automating Deployment with CI/CD
Deploying to Jetty and Undertow
Why Jetty?
Jetty Deployment
Undertow Overview
Undertow Deployment
Deploying to Docker
Deploying Spring Boot Application
Deploying to AWS
Setup EC2 Instance
Install Java on EC2 Instance
Transfer Application JAR/WAR File to EC2
Run Application
Using AWS Elastic Beanstalk
Using AWS Elastic Container Service
Running Apps in Kubernetes
Setting up Kubernetes
Deploying Application to Kubernetes
Creating Spring Boot Docker Images
Workflow for Docker Images
Sample Program: Creation of Docker Images
Summary
Chapter 5: Spring Boot Auto-configuration
Chapter Overview
Understanding Auto-configuration
Auto-configuration Overview
Key Components of Auto-configuration
Sample Program: Auto-configuration using JPA and H2
Customizing Auto-configuration
Overriding Default Beans
Conditional Beans and Customization
Customizing Configuration with @ConfigurationProperties
Customizing Auto-configuration with Custom Annotations
Exploring Spring Boot Starter POMs
Using Conditional Beans
Common Conditional Annotations
Sample Program: Using Conditional Annotations
Writing Custom Auto-configuration
Custom Auto-configuration Workflow
Sample Program: Writing Custom Auto-configuration
Exploring Starter POMs
Common Spring Boot Starter POMs
Sample Program: Using Starter POMs
Summary
Chapter 6: Data Access with Spring Data JPA
Chapter Overview
Introduction to Spring Data JPA
Key Features of Spring Data JPA
Up and Running with Spring Data JPA
Configuring Data Source
Adding Dependencies
Defining Data Source Properties
Creating JPA Entities
Creating Repository Interfaces
Implementing Service Layer
Creating Controller Layer
JPA Entities and Relationships
Defining JPA Entities
One-to-One Relationship
One-to-Many and Many-to-One Relationships
Many-to-Many Relationship
Query Methods and Custom Queries
Defining Query Methods
Writing Custom Queries with @Query
Using JPA Criteria API
Why Criteria API?
Sample Program: Using JPA Criteria API
Paging and Sorting with Spring Data JPA
Brief Overview
Setting up Paging and Sorting
Handling Transactions in Spring Boot
Enabling Transaction Management
Using @Transactional Annotation
Transaction Scenarios
Additional Transaction Management
Integrating with Liquibase and Flyway for Database Migrations
Configuring Liquibase
Configuring Flyway
Performing Database Migrations
Sample Program: Combining Liquibase and Flyway
Summary
Chapter 7: Building Web Applications
Chapter Overview
Introduction to Spring MVC
Model-View-Controller Architecture
Spring MVC Components
Sample Program: Creating a User Management System using Spring MVC
Creating Controllers and Views
Creating Controllers
Creating Views
Using Thymeleaf Templates
Setting up Thymeleaf
Basic Syntax and Expressions
Creating a User Form with Validation
Implementing User Details View
Adding a CSS File for Styling
Updating the Application to Serve Static Content
Handling Form Submissions
Form Binding with Thymeleaf
Controller Method for Handling Form Submissions
Adding Validation Constraints
Handling Form Submission and Validation Errors
Validating User Input
Adding Validation Constraints to the Entity
Updating Controller to Handle Validation
Updating Form to Display Validation Errors
Utilizing WebSockets
Brief Overview
Configuring WebSockets
File Upload and Download Handling
Configuring File Uploads
Creating a File Upload Controller
Handling File Downloads
Integrating Front-End Frameworks
Integrating React with Spring Boot
Integrating Angular with Spring Boot
Summary
Chapter 8: Testing Spring Boot Applications
Chapter Overview
Getting Started with Testing
Background
Types of Testing
Unit Testing with JUnit and Mockito
Setting up JUnit and Mockito
Example 1: Unit Testing a Service Layer
Example 2: Unit Testing a Controller Layer
Conduct Slice Testing for Layer-Specific Tests
Understanding Layer-Specific Tests
Slice Testing for the Data Layer
Slice Testing for the Web Layer
MockMVC for Web Layer Testing
Introduction to MockMVC
Setting up MockMVC
Sample Program: Using MockMVC
Testing Data Repositories
Types of Data Repositories
Sample Program: Testing Data Repositories
Sample Program: Testing a Custom Repository Method
Testing with TestContainers
Setting up TestContainers
Writing Integration Tests with TestContainers
Performance Testing with JMeter
Introduction to JMeter
Setting up JMeter
Sample Test Plan
Summary
Chapter 9: Security in Spring Boot
Chapter Overview
Explore Spring Security
Introduction to Spring Security
Core Components of Spring Security
Configuring Basic Authentication
Setting up Spring Security
Customizing Basic Authentication
Configuring URL Authorization
Setting up URL Authorization
Customizing Access Denied Handling
Testing the Custom Access Denied Handler
JWT, OAuth and OpenID Connect
Setting up JWT Authentication
Setting up OAuth and OpenID Connect
Integrating with LDAP and Active Directory
Setting up LDAP Integration
Integrating with Active Directory
Summary
Index
Epilogue
GitforGits
Prerequisites
Whether you're a seasoned developer or just getting started, this book introduces you to geete comfortable with Spring Boot and take the most benefits of its tools to create high-quality apps quickly. All you need is to be just a basic programming experience with any of the languages to get started with.
Codes Usage
Are you in need of some helpful code examples to assist you in your programming and documentation? Look no further! Our book offers a wealth of supplemental material, including code examples and exercises.
Not only is this book here to aid you in getting your job done, but you have our permission to use the example code in your programs and documentation. However, please note that if you are reproducing a significant portion of the code, we do require you to contact us for permission.
But don't worry, using several chunks of code from this book in your program or answering a question by citing our book and quoting example code does not require permission. But if you do choose to give credit, an attribution typically includes the title, author, publisher, and ISBN. For example, Spring Boot 3.0 Crash Course by Kit Harrington
.
If you are unsure whether your intended use of the code examples falls under fair use or the permissions outlined above, please do not hesitate to reach out to us at [email protected].
We are happy to assist and clarify any concerns.
Chapter 1: Up and Running with Spring Boot
Chapter Overview
Let us start with our first chapter, Up and Running with Spring Boot,
which will serve as the foundation for your skill-building transition into Spring Boot. This chapter will walk you through the core concepts and essential features that make Spring Boot a powerful framework for developing robust applications. You'll start by learning about Spring Boot and how it evolved from the Spring Framework, which will help you understand why it's so popular among developers today.
As you progress, you'll discover the key features that set Spring Boot apart from other frameworks. Some of its features include an opinionated approach to configuration, the ability to build standalone apps, and the ability to integrate with different technologies seamlessly. Understanding these features will help you appreciate the efficiency and simplicity that Spring Boot adds to application development. You will then proceed to set up your development environment, ensuring that all required tools are installed and configured. This includes configuring your IDE, JDK, and other essential components. Following that, you will create your first Spring Boot application, giving you hands-on experience with the framework's capabilities. This practical approach will be supplemented by exploring Spring Boot dependencies and starter projects, which make dependency management and project setup easier.
Finally, the chapter will go over Spring Boot annotations and the Spring Boot CLI. By the end of this chapter, you will have a solid understanding of Spring Boot, allowing you to delve deeper into its advanced features and capabilities in the following chapters.
What is Spring Boot?
Spring Boot has gained significant traction among developers for its ability to simplify the creation of stand-alone, production-grade Spring-based applications. It has become synonymous with rapid application development, offering a set of tools and features that streamline the entire development process. The modern developer community appreciates Spring Boot for its minimal setup, reduced boilerplate code, and the seamless integration it provides with other technologies.
Emergence of Spring Boot
Spring Boot emerged as an enhancement to the Spring Framework, addressing some of the complexities and configuration challenges developers faced with traditional Spring applications. The Spring Framework, introduced in 2003, brought a revolutionary approach to Java development by promoting loose coupling through dependency injection and aspect-oriented programming. However, as the Spring ecosystem grew, configuring and deploying Spring applications became increasingly intricate. This is where Spring Boot comes into play.
Spring Boot was introduced to tackle these challenges by providing a convention-over-configuration approach. It simplifies the development process by offering default configurations and sensible defaults, which can be customized as needed. This allows developers to focus more on writing business logic rather than dealing with complex configurations.
Relation to Spring Framework
Spring Boot is essentially built on top of the Spring Framework, leveraging its core principles and components while abstracting much of the boilerplate configuration. This relationship ensures that Spring Boot applications inherit the robust and flexible nature of the Spring Framework but with added ease of use and productivity enhancements.
At its core, Spring Boot provides:
● Pre-configured dependencies for various functionalities, reducing the need for manual