Statistics
40
Views
0
Downloads
0
Donations
Support
Share
Uploader

高宏飞

Shared on 2026-01-27

AuthorMohamed Shazin Sadakath

Spring is one of the best tools available on the market for developing web, enterprise, and cloud-ready software. The goal of Spring Boot is to provide a set of tools for quickly building Spring applications that are easy to configure, and that make it easy to create and run production-grade Spring-based applications. Spring Boot 2.0 Projects will get you acquainted with important features of the latest version of this application-building tool and will cover basic, as well as advanced topics. The book starts off by teaching you how to create a web application using Spring Boot, followed by creating a Spring Boot-based simple blog management system that uses Elasticsearch as the data store. As you make your way through the chapters, you’ll build a RESTful web services application using Kotlin and the Spring WebFlux framework. Spring WebFlux is a new framework that helps in creating a reactive a

Tags
No tags
ISBN: 1789136156
Publisher: Packt Publishing
Publish Year: 2020
Language: 英文
Pages: 329
File Format: PDF
File Size: 5.6 MB
Support Statistics
¥.00 · 0times
Text Preview (First 20 pages)
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.

WOW! eBook www.wowebook.org
Spring Boot 2.0 Projects Build production-grade reactive applications and microservices with Spring Boot Mohamed Shazin Sadakath BIRMINGHAM - MUMBAI WOW! eBook www.wowebook.org
Spring Boot 2.0 Projects Copyright © 2018 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, 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. Commissioning Editor: Richa Tripathi Acquisition Editor: Sandeep Mishra Content Development Editor: Tiksha Sarang Technical Editor: Supriya Thabe Copy Editor: Safis Editing Project Coordinator: Prajakta Naik Proofreader: Safis Editing Indexer: Rekha Nair Graphics: Jisha Chirayil Production Coordinator: Aparna Bhagat First published: July 2018 Production reference: 1260718 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78913-615-9 www.packtpub.com WOW! eBook www.wowebook.org
To my parents, for going through tough times in order to give me a good education and manners, and to my wife, Nadhiya, for being my loving partner throughout our life journey together. WOW! eBook www.wowebook.org
mapt.io Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website. Why subscribe? Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals Improve your learning with Skill Plans built especially for you Get a free eBook or video every month Mapt is fully searchable Copy and paste, print, and bookmark content PacktPub.com Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com, and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at service@packtpub.com for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks. WOW! eBook www.wowebook.org
Contributors About the author Mohamed Shazin Sadakath is an experienced software engineer with over 9 years of software development experience in J2SE-, J2EE-, and Spring-based applications. He is a BSc (Hons) software engineering graduate, having achieved first class honors. He has worked in different domains, ranging from telecommunications to real estate. In his spare time, he contributes to open source projects, such as Spring Security, and writes technical articles for blogs. He is a Stack Overflow Moderator and loves answering Java-related questions. I would like to thank my loving wife, Nadhiya, for her help and encouragement while writing this book. I would like to thank Gunith Devasurendra for the technical reviewing of this book. I would also like to thank Sudharshan Selvenayagam and Manoj Senevirathne for their assistance while writing this book. WOW! eBook www.wowebook.org
About the reviewers Gunith Eranda Devasurendra is a senior software engineer with 10 years, professional development experience, specializing in Java. Born in Sri Lanka, he became interested in programming as he considers elegant programming and design to be an art form. Gunith has a master's in computer science awarded by the University of Colombo. He is a speaker and a trainer on technical topics including Spring, and Git. He is also an advocate of FOSS. Gunith also helps out in the Stack Overflow community. To Lord Buddha. To my parents for raising me and giving me an education so that I could contribute to this book. To my wife, Vimanga, for her love and helping me on so many levels so that I can contribute. To my son Sasen for his love. To Shazin, the author, for nominating me and trusting me. To all my teachers and friends who taught me things. Biharck Araújo has been working as a principal software architect and lead programmer for the past 15 years. He is passionate about technology and academic research. He has been working with JavaEE technology for web projects that demand high-security standards in terms of information transmission for companies across different sectors. He has extensive experience in activities regarding software architecture. He works in bioinformatics using technology in life's favor. Packt is searching for authors like you If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea. WOW! eBook www.wowebook.org
Table of Contents Preface 1 Chapter 1: Introduction 6 Technical requirements 6 Generating Spring Boot Projects 7 Opening the generated project with IntelliJ 8 Opening the generated project with STS 10 Getting started with Spring Boot 12 Learning about Spring Boot 12 Anatomy of a Spring Boot application 13 Supporting the Spring Framework ecosystem in Spring Boot 15 Changes since Spring Boot 1.x 16 Registering a Spring Bean using ApplicationContextInitializer 17 Configuration property binding 18 New property binding API 19 Property origin 20 Tightened rules for governing relaxed property binding 20 Environment variables with indices 21 Direct binding of property type java.time.Duration in the ISO-8601 form 21 Custom endpoints for Spring Boot Actuator using annotations 21 Exposing a custom Spring Boot Actuator endpoint 22 Extending a custom endpoint with a specialized implementation for the web 23 Connecting to a custom endpoint using monitoring and management tools 23 Custom metrics using Micrometer 25 Custom health indicator 26 Using the HTTP/2 protocol 27 Securing applications with Spring Security 30 The next milestone 31 Migration 32 Using the correct JDK and JVM 32 Running on Java 9 32 Tackling JAXBException 32 Using the correct AspectJ version 33 Being aware of limitations on Apache Cassandra drivers 33 Being aware of issues with the Maven Surefire Plugin 33 Using the upgraded Spring Framework 5.0 33 Modified CORS support behavior 34 Removed packages, classes, and methods 34 Dropped support for frameworks 34 Using the updated configuration properties 35 Using the changed servlet-specific server properties 35 Using the modified template engine extension handling 35 WOW! eBook www.wowebook.org
Table of Contents [ ii ] Using the changed actuator configuration properties 36 Using the changed actuator base path 36 Using the renamed actuator endpoints 36 Using the changed Embedded Container Configuration 37 Using the changed default behavior for path mapping 37 Using the changed default dispatcher types for the servlet filter 38 Using the modified transitive dependency to spring-boot-web-starter 38 Using the changed default proxying strategy 39 Using the modified configuration location strategy 39 Using the changed Jackson/JSON support 39 Using the changed Spring Boot Actuator security 39 Using the changed HikariCP default connection pool for JPA 40 Using the changed default database initialization strategy 40 Using the changed database schema creation strategy 40 Using the changed testing support 41 Using the revised Spring Security 41 Using the changed default security auto-configuration strategy 41 Spring Security OAuth2 is migrated to Spring Security core 41 Using the AuthenticationManager bean 41 Understanding removed features 42 Summary 42 Questions 43 Further reading 43 Chapter 2: Building a Basic Web Application 44 Technical requirements 44 Getting started 45 Web application architecture 45 Workflow of Spring Web MVC 46 Requirements for our web application 48 The use case diagram 48 Using Spring Data JPA for persistence 49 Understanding the Java Persistence API (JPA) 49 Understanding Spring Data JPA 50 Class diagram for the domain model 50 Implementation of the domain model using JPA annotations 51 Setting up dependencies and configuration 51 Implementing the domain model 53 Implementation of Spring Data JPA repositories 55 Testing Spring Data JPA repositories 55 Using Spring Boot Devtools for database visualization 58 Using Services to encapsulate business logic 60 Testing Services 61 Using Spring Thymeleaf for the view 64 Understanding template engines 64 Spring Thymeleaf 65 WOW! eBook www.wowebook.org
Table of Contents [ iii ] UI design for the Retro Board 65 UI implementation for the Retro Board using Spring Thymeleaf 66 Using Spring Web MVC with servlet 3.x for the controller 68 Implementation of Controllers annotations 69 Testing controllers 70 Using Spring Security for authentication and authorization 73 Demonstrating the Retro Board 76 Summary 78 Questions 78 Further reading 79 Chapter 3: Building a Simple Blog Management System 80 Technical requirements 80 Getting started 81 Web application architecture 81 Workflow of Spring WebFlux 82 Requirements of the Bloggest system 82 The use case diagram 83 Using Spring Data Elasticsearch for persistence 84 Understanding Elasticsearch 84 Understanding Spring Data Elasticsearch 85 Class diagram for the domain model 85 Implementation of the domain model using Spring Data Elasticsearch annotations 86 Setting up dependencies and configuration classes 86 Implementing the domain model 87 Implementation of Spring Data Elasticsearch repositories 88 Using Apache FreeMarker for the view 89 Understanding template engines 89 Apache FreeMarker 90 UI design for Bloggest 91 UI implementation for Bloggest using Apache FreeMarker 93 Implementing a common layout using Apache FreeMarker 94 Implementing a List Articles page 97 Implementing a Create Article page 100 Implementing a Show Article page 102 Implementing an error page 104 Using Spring WebFlux for controller 105 Implementation of controllers 105 Implementation of ControllerAdvice 109 Using Spring Security for authentication and authorization 110 Demonstrating Bloggest 113 Summary 121 Questions 122 Further reading 122 WOW! eBook www.wowebook.org
Table of Contents [ iv ] Chapter 4: Introduction to Kotlin 123 Technical requirements 123 Getting started with Kotlin 124 Default imports 124 Basic data types 125 Numeric data types 125 Learning numeric literals 125 Numeric representation 126 Numeric operations 126 String literals 127 The syntax for Kotlin code 127 The Kotlin packages 127 String interpolation 128 Functions in Kotlin 128 Variables in Kotlin 129 Conditional statements 129 The if statement 129 The when statement 130 Type checking and automatic casting 130 Nullable values and compile-time null safety 130 The for loop 131 The for loop with an array 131 The for loop with a collection 131 The for loop with a value range 132 The while loop 132 Object-oriented programming with Kotlin 133 Learning about visibility modifiers 133 Classes in Kotlin 134 Abstract classes 134 Concrete classes 135 The concept of interfaces in Kotlin 135 Learning about extensions 136 Generic types in Kotlin 137 Enums in Kotlin 137 Objects in Kotlin 138 Object expressions 138 Object declarations 138 Companion objects 139 Advanced programming with Kotlin 139 Functions 140 Infix notation in functions 140 Local functions in Kotlin 140 Default arguments in functions 141 Named arguments in functions 141 Generics in functions 142 Variable number of arguments (vararg) in functions 142 Summary 142 Questions 143 WOW! eBook www.wowebook.org
Table of Contents [ v ] Further reading 143 Chapter 5: Building a Reactive Movie Rating API Using Kotlin 144 Technical requirements 144 Getting started 145 REST architecture 145 Requirements of REST architecture 146 The use case diagram 147 Using Spring Data MongoDB for persistence 147 Understanding MongoDB 148 Understanding Spring Data MongoDB 148 Class diagram for the domain model 149 Implementation of the domain model using Spring Data MongoDB annotations 150 Setting up dependencies and configuration 150 Implementing the domain model 150 Implementing of Spring Data MongoDB repositories 152 Using a service to encapsulate business logic 152 Testing Services 154 Using Spring WebFlux for controllers 158 Implementation of controllers 159 Testing controllers 160 Using Spring Security for basic authorization 163 Demonstrating Moviee 165 Integration testing 165 Demonstrating the use of Postman 168 Accessing the List Movies endpoint 168 Accessing the Get Movie endpoint 169 Accessing the Get Movie endpoint with an invalid Movie ID 170 Accessing the Rate Movie endpoint 171 Summary 172 Questions 172 Further reading 173 Chapter 6: Building an API with Reactive Microservices 174 Technical requirements 175 Getting started 175 Microservices architecture 175 The requirements of microservices architecture 177 The use case diagram 178 The project structure to develop microservices 179 Using Spring Data Redis for persistence 180 Understanding Redis 180 Understanding Spring Data Redis 180 Class diagram for the domain model 181 Implementation of domain model using Spring Data Redis annotations 182 WOW! eBook www.wowebook.org
Table of Contents [ vi ] Setting up dependencies and configuration 182 Implementing the domain model 182 Implementation of Spring Data Redis repositories 184 Using a Service to encapsulate business logic 184 Using Spring WebFlux for a controller 190 Implementation of controllers 191 Using asynchronous data transfer for cross-microservice communication 194 Asynchronous data transfer using Redis 194 Using Docker to support microservices 196 Understanding Docker 196 Using Maven to build Docker images 197 Building a system of microservices with Docker 199 Deploying microservices with Docker 203 Demonstrating Saber 204 Submitting to the Register Taxi endpoint 204 Submitting location to update Taxi Location endpoint 206 Submitting to Update Taxi Status endpoint 207 Accessing the Get Taxi Status endpoint 208 Accessing the GET available Taxis endpoint 209 Submitting to Book Taxi endpoint 210 Submitting to Accept Taxi Booking endpoint 211 Submitting to cancel Taxi Booking endpoint 212 Accessing Taxi Bookings endpoint 213 Summary 214 Questions 214 Further reading 215 Chapter 7: Building a Twitter Clone with Spring Boot 216 Technical requirements 216 Getting started 217 Beginning with the Tweety architecture 217 Tweety requirements 218 The use case diagram 218 Using Spring Data JPA for persistence 219 Class diagram for the domain model 219 Implementation of the domain model using Spring Data JPA annotations 220 Setting up dependencies and configuration 220 Implementing the domain model 221 Implementing Spring Data JPA repositories 223 Caveat for going reactive with blocking JDBC 223 Using Service to encapsulate business logic 224 Using Angular 5 for the frontend 226 Getting started with Angular 5 application development 226 Generating Angular services 227 Generating the users service 228 WOW! eBook www.wowebook.org
Table of Contents [ vii ] Generating Angular page components 230 Generating the Tweets Add page 232 Generating the User Profile page 234 Using Spring Web Flux for the REST controller 235 Implementing controllers 236 Enabling Angular frontend access to controllers 238 Using Spring Security for authentication and authorization 239 Understanding OAuth2 239 Setting up dependencies and configuration 240 Configuring the Resource Server 241 Configuring the Authorization Server 241 Configuring web security 242 Using an Angular service for OAuth2 authentication and authorization 243 Demonstrating Tweety 246 Accessing the login page 247 Accessing the List Tweets page 248 Accessing the Send Tweet page 248 Accessing the User Profile page 249 Summary 250 Questions 251 Further reading 251 Chapter 8: Introducing Spring Boot 2.0 Asynchronous 252 Technical requirements 252 Getting started 253 Synchronous applications 253 Asynchronous applications 254 The requirement of asynchronous applications 254 The use case diagram 255 The architecture of an image resizing application 256 Using Spring Kafka for communication 256 Understanding Apache Kafka 257 Setting up dependencies and configuration 258 Configuration for the Image Resize Request Producer 258 Configuration for Image Resize Request Consumer 261 Starting Spring Boot applications in a non-web mode 262 Using Quartz for scheduling 263 Understanding Quartz 263 Setting up dependencies and configuration 263 Configuration for Quartz scheduling 263 Demonstrating Image Resizer 265 Building all dependencies 265 Running Apache Kafka 265 Running Apache ZooKeeper on Windows 265 Running Apache Kafka on Linux/Unix 266 Running Apache Kafka on Windows 266 WOW! eBook www.wowebook.org
Table of Contents [ viii ] Running Image Resize Request Consumer 266 Running Image Resize Request Producer 266 Summary 269 Questions 269 Further reading 270 Chapter 9: Building an Asynchronous Email Formatter 271 Technical requirements 271 Getting started 272 Why Email Formatter is useful 272 The use case diagram 273 The architecture of the Email Formatter application 274 Using Spring Data JPA for persistence 274 Class diagram for the domain model 275 Implementation of the domain model using JPA annotations 275 Setting up dependencies and the configuration class 275 Implementing the domain model 276 Implementation of Spring Data JPA repositories 277 Using Services to encapsulate business logic 277 Using Apache FreeMarker for templates 279 Using Spring Kafka for communication 281 Setting up dependencies and the configuration class 282 Configuration for User Registration 282 Configuration for the Email Formatter consumer 284 Configuring Java Mail 286 Using Spring Web MVC for the REST controller 287 Implementation of controller annotations 287 Using Spring Security for authentication and authorization 288 Demonstrating Email Formatter 289 Building all dependencies 289 Running Apache Kafka 290 Running Apache ZooKeeper on Windows 290 Running Apache Kafka on Linux/Unix 290 Running Apache Kafka on Windows 290 Running SMTP server 291 Running the Email Formatter consumer 292 Running the User Registration microservice 292 Summary 296 Questions 297 Further reading 297 Assessments 298 Other Books You May Enjoy 305 Index 308 WOW! eBook www.wowebook.org
Preface This book is about Spring Boot 2.0 hands-on development for beginners, intermediate, and expert-level software developers. The purpose of this book is to increase the practical knowledge of the readers by going through the practical uses of the features introduced in Spring Boot 2.0. This book covers vast topics with example applications so that it is much easier to grasp and use in real-life projects. Who this book is for This book is for anyone interested in developing applications using the Spring Framework, and specifically, Spring Boot 2. The readers may have prior experience of Spring Boot, but it is not compulsory, as even beginners can benefit from the content of this book. This book expects the readers to have some level of understanding of software development using Java. What this book covers Chapter 1, Introduction, outlines the Spring Boot 2.0 application development framework and compares its features with the previous version of Spring Boot. It also talks about configuration property changes, API changes, platform changes, and more in Spring Boot 2.0. Furthermore, it explains how to migrate from the previous version of Spring Boot application to Spring Boot 2.0 application. Chapter 2, Building a Basic Web Application, begins with the practical side of developing a basic web application using the Spring Boot 2.0 Framework. It also talks about Spring Data JPA persistence, Spring Thymeleaf view, and Spring WebFlux controllers. Chapter 3, Building a Simple Blog Management System, presents the practical side of developing a simple blog management system using the Spring Boot 2.0 framework. It also talks about Spring Data Elasticsearch for persistence, Apache FreeMarker view, and Spring WebFlux controllers. WOW! eBook www.wowebook.org
Preface [ 2 ] Chapter 4, Introduction to Kotlin, introduces the programming language Kotlin by comparing it with Java programming language side by side. It will help to get started with Kotlin programming, subsequently moving into advanced topics in Kotlin such as OOP and other features. Chapter 5, Building a Reactive Movie Rating API Using Kotlin, discusses reactive movie rating API development using Kotlin programming language with Spring Boot 2.0. It talks about Spring Data MongoDB persistence, Spring WebFlux controllers, and Spring Security authentication and authorization. Chapter 6, Building an API with Reactive Microservices, explains reactive microservices development using Spring Boot 2.0. It also talks about Spring Data Redis persistence, Spring Web Flux controllers, Asynchronous data transfer among microservices, and Docker deployment of microservices. Chapter 7, Building a Twitter Clone with Spring Boot, covers Angular application acting as a client for Spring Boot 2.0 REST API. It also talks about Spring Data JPA persistence, Angular 5 frontend, Spring Web Flux controllers, and Spring Security OAuth2 authentication and authorization. Chapter 8, Introducing Spring Boot 2.0 Asynchronous, Quartz Scheduler introduces asynchronous application development using Spring Boot 2.0. It also talks about Apache Kafka as a message broker that enables decoupled, asynchronous communication between applications. Chapter 9, Building an Asynchronous Email Formatter, explains details of how to build an Asynchronous Email Formatter, using Spring Boot 2 as the backend development framework and Apache Kafka as a message queue. It will also explain how to use JPA as the persistence layer, which is a widely used data source. It will use Apache FreeMarker to create the email templates and show how to use placeholders to provide dynamic data to email templates. To get the most out of this book You need knowledge of the following: The Java programming language1. Spring Framework2. Web application concepts3. WOW! eBook www.wowebook.org
Preface [ 3 ] The following tools will be used throughout chapters: Java Development Kit 8+1. Maven 32. IntelliJ IDEA or Spring Tool Suite3. Download the example code files You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you. You can download the code files by following these steps: Log in or register at www.packtpub.com.1. Select the SUPPORT tab.2. Click on Code Downloads & Errata.3. Enter the name of the book in the Search box and follow the onscreen4. instructions. Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of: WinRAR/7-Zip for Windows Zipeg/iZip/UnRarX for Mac 7-Zip/PeaZip for Linux The code bundle for the book is also hosted on GitHub at https:/​/​github.​com/ PacktPublishing/​Spring-​Boot-​2.​0-​Projects-​Fundamentals-​of-​Spring-​Boot-​2.​0. In case there's an update to the code, it will be updated on the existing 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! WOW! eBook www.wowebook.org
Preface [ 4 ] Conventions used There are a number of text conventions used throughout this book. CodeInText: 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: "An ApplicationStartedEvent will be sent right after the application context is refreshed but before any command-line runners run. " A block of code is set as follows: public class Address { private String number; private String street; private String city; private String country; private String zipCode; // Getters, Setters, Equals, Hashcode } Any command-line input or output is written as follows: $ jconsole Bold: Indicates a new term, an important word, or words that you see onscreen. For example, words in menus or dialog boxes appear in the text like this. Here is an example: "Select File | Open from the menu bar." Warnings or important notes appear like this. Tips and tricks appear like this. WOW! eBook www.wowebook.org
Preface [ 5 ] Get in touch Feedback from our readers is always welcome. General feedback: Email feedback@packtpub.com and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at questions@packtpub.com. 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/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering 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 copyright@packtpub.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. Reviews Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you! For more information about Packt, please visit packtpub.com. WOW! eBook www.wowebook.org