M A N N I N G Craig Walls SIXTH EDITION
From the fifth edition of Spring in Action by Craig Walls “A great tool for understanding such a complex framework.” —Arnaldo Gabriel Ayala Meyer, Consultores Informáticos S.R.L. “Excellent coverage of the latest Spring release with complete practical examples.” —Bill Fly, Brookhaven College “The go-to book for learning the Spring Framework and an excellent reference guide.” —Colin Joyce, Cisco “This has always been my go-to book for Spring. The new edition is a comprehensive update that strikes the balance between practical instruction and comprehensive theory. It helps you to get started quickly and follows up with in-depth explanations.” —Daniel Vaughan, European Bioinfomatics Institute “The definitive guide to building cloud native applications using Spring.” —David Witherspoon, Parsons Corporation “The source of truth for the Spring ecosystem.” —Eddú Meléndez Gonzales, Scotiabank “I would highly recommend this book, either for newcomers to the Spring Framework or a seasoned Spring developer who wishes to deep-dive into the latest features available in the Spring 5 ecosystem.” —Iain Campbell, Tango Telecom “Even as a Spring veteran I got lots of practical tips from this book.” —Jettro Coenradie, Luminis
(This page has no text content)
Spring in Action, Sixth Edition
(This page has no text content)
Spring in Action, Sixth Edition CRAIG WALLS MANN I NG SHELTER ISLAND
For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2022 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. The author and publisher have made every effort to ensure that the information in this book was correct at press time. The author and publisher do not assume and hereby disclaim any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from negligence, accident, or any other cause, or from any usage of the information herein. Manning Publications Co. Development editor: Jennifer Stout 20 Baldwin Road Technical development editor: Joshua White PO Box 761 Review editor: Mihaela Batinić Shelter Island, NY 11964 Production editor: Deirdre S. Hiam Copy editor: Pamela Hunt Proofreader: Katie Tennant Technical proofreaders: Doug Warren and German Gonzalez-Morris Typesetter: Dennis Dalinnik Cover designer: Marija Tudor ISBN: 9781617297571 Printed in the United States of America
brief contents PART 1 FOUNDATIONAL SPRING ................................................1 1 ■ Getting started with Spring 3 2 ■ Developing web applications 29 3 ■ Working with data 61 4 ■ Working with nonrelational data 94 5 ■ Securing Spring 113 6 ■ Working with configuration properties 140 PART 2 INTEGRATED SPRING .................................................161 7 ■ Creating REST services 163 8 ■ Securing REST 186 9 ■ Sending messages asynchronously 210 10 ■ Integrating Spring 243 PART 3 REACTIVE SPRING . ....................................................277 11 ■ Introducing Reactor 279 12 ■ Developing reactive APIs 308vii
BRIEF CONTENTSviii13 ■ Persisting data reactively 337 14 ■ Working with RSocket 369 PART 4 DEPLOYED SPRING ....................................................385 15 ■ Working with Spring Boot Actuator 387 16 ■ Administering Spring 423 17 ■ Monitoring Spring with JMX 435 18 ■ Deploying Spring 443
contents preface xvii acknowledgments xix about this book xxi about the author xxv about the cover illustration xxvi PART 1 FOUNDATIONAL SPRING ......................................1 1 Getting started with Spring 3 1.1 What is Spring? 4 1.2 Initializing a Spring application 6 Initializing a Spring project with Spring Tool Suite 7 Examining the Spring project structure 11 1.3 Writing a Spring application 17 Handling web requests 18 ■ Defining the view 19 Testing the controller 20 ■ Building and running the application 21 ■ Getting to know Spring Boot DevTools 23 Let’s review 25 1.4 Surveying the Spring landscape 26 The core Spring Framework 26 ■ Spring Boot 26 ■ Spring Data 27 ■ Spring Security 27 ■ Spring Integration and Spring Batch 27 ■ Spring Cloud 28 ■ Spring Native 28ix
CONTENTSx2 Developing web applications 29 2.1 Displaying information 30 Establishing the domain 31 ■ Creating a controller class 34 Designing the view 38 2.2 Processing form submission 41 2.3 Validating form input 49 Declaring validation rules 50 ■ Performing validation at form binding 52 ■ Displaying validation errors 54 2.4 Working with view controllers 54 2.5 Choosing a view template library 57 Caching templates 59 3 Working with data 61 3.1 Reading and writing data with JDBC 62 Adapting the domain for persistence 64 ■ Working with JdbcTemplate 65 ■ Defining a schema and preloading data 70 ■ Inserting data 73 3.2 Working with Spring Data JDBC 78 Adding Spring Data JDBC to the build 78 ■ Defining repository interfaces 79 ■ Annotating the domain for persistence 81 Preloading data with CommandLineRunner 83 3.3 Persisting data with Spring Data JPA 85 Adding Spring Data JPA to the project 85 ■ Annotating the domain as entities 86 ■ Declaring JPA repositories 89 Customizing repositories 90 4 Working with nonrelational data 94 4.1 Working with Cassandra repositories 95 Enabling Spring Data Cassandra 95 ■ Understanding Cassandra data modeling 98 ■ Mapping domain types for Cassandra persistence 99 ■ Writing Cassandra repositories 105 4.2 Writing MongoDB repositories 106 Enabling Spring Data MongoDB 106 ■ Mapping domain types to documents 107 ■ Writing MongoDB repository interfaces 111
CONTENTS xi5 Securing Spring 113 5.1 Enabling Spring Security 114 5.2 Configuring authentication 116 In-memory user details service 118 ■ Customizing user authentication 119 5.3 Securing web requests 125 Securing requests 125 ■ Creating a custom login page 128 Enabling third-party authentication 131 ■ Preventing cross-site request forgery 133 5.4 Applying method-level security 134 5.5 Knowing your user 136 6 Working with configuration properties 140 6.1 Fine-tuning autoconfiguration 141 Understanding Spring’s environment abstraction 142 Configuring a data source 143 ■ Configuring the embedded server 145 ■ Configuring logging 146 ■ Using special property values 148 6.2 Creating your own configuration properties 148 Defining configuration property holders 151 ■ Declaring configuration property metadata 153 6.3 Configuring with profiles 155 Defining profile-specific properties 156 ■ Activating profiles 158 Conditionally creating beans with profiles 159 PART 2 INTEGRATED SPRING .......................................161 7 Creating REST services 163 7.1 Writing RESTful controllers 164 Retrieving data from the server 164 ■ Sending data to the server 170 ■ Updating data on the server 171 ■ Deleting data from the server 173 7.2 Enabling data-backed services 174 Adjusting resource paths and relation names 177 ■ Paging and sorting 179 7.3 Consuming REST services 180 GETting resources 182 ■ PUTting resources 183 DELETEing resources 184 ■ POSTing resource data 184
CONTENTSxii8 Securing REST 186 8.1 Introducing OAuth 2 187 8.2 Creating an authorization server 192 8.3 Securing an API with a resource server 201 8.4 Developing the client 204 9 Sending messages asynchronously 210 9.1 Sending messages with JMS 211 Setting up JMS 211 ■ Sending messages with JmsTemplate 214 Receiving JMS messages 222 9.2 Working with RabbitMQ and AMQP 226 Adding RabbitMQ to Spring 227 ■ Sending messages with RabbitTemplate 228 ■ Receiving messages from RabbitMQ 232 9.3 Messaging with Kafka 236 Setting up Spring for Kafka messaging 237 ■ Sending messages with KafkaTemplate 238 ■ Writing Kafka listeners 241 10 Integrating Spring 243 10.1 Declaring a simple integration flow 244 Defining integration flows with XML 246 ■ Configuring integration flows in Java 247 ■ Using Spring Integration’s DSL configuration 249 10.2 Surveying the Spring Integration landscape 251 Message channels 252 ■ Filters 253 ■ Transformers 254 Routers 256 ■ Splitters 257 ■ Service activators 260 Gateways 262 ■ Channel adapters 263 ■ Endpoint modules 265 10.3 Creating an email integration flow 267 PART 3 REACTIVE SPRING ...........................................277 11 Introducing Reactor 279 11.1 Understanding reactive programming 280 Defining Reactive Streams 281 11.2 Getting started with Reactor 283 Diagramming reactive flows 285 ■ Adding Reactor dependencies 286
CONTENTS xiii11.3 Applying common reactive operations 287 Creating reactive types 287 ■ Combining reactive types 291 Transforming and filtering reactive streams 295 ■ Performing logic operations on reactive types 305 12 Developing reactive APIs 308 12.1 Working with Spring WebFlux 309 Introducing Spring WebFlux 310 ■ Writing reactive controllers 312 12.2 Defining functional request handlers 316 12.3 Testing reactive controllers 320 Testing GET requests 320 ■ Testing POST requests 323 Testing with a live server 324 12.4 Consuming REST APIs reactively 325 GETting resources 326 ■ Sending resources 328 ■ Deleting resources 329 ■ Handling errors 329 ■ Exchanging requests 331 12.5 Securing reactive web APIs 333 Configuring reactive web security 333 ■ Configuring a reactive user details service 335 13 Persisting data reactively 337 13.1 Working with R2DBC 338 Defining domain entities for R2DBC 339 ■ Defining reactive repositories 343 ■ Testing R2DBC repositories 345 ■ Defining an OrderRepository aggregate root service 347 13.2 Persisting document data reactively with MongoDB 353 Defining domain document types 354 ■ Defining reactive MongoDB repositories 356 ■ Testing reactive MongoDB repositories 357 13.3 Reactively persisting data in Cassandra 361 Defining domain classes for Cassandra persistence 362 Creating reactive Cassandra repositories 365 ■ Testing reactive Cassandra repositories 366 14 Working with RSocket 369 14.1 Introducing RSocket 370 14.2 Creating a simple RSocket server and client 372 Working with request-response 372 ■ Handling request-stream messaging 376 ■ Sending fire-and-forget messages 378 Sending messages bidirectionally 379 14.3 Transporting RSocket over WebSocket 382
CONTENTSxivPART 4 DEPLOYED SPRING ..........................................385 15 Working with Spring Boot Actuator 387 15.1 Introducing Actuator 388 Configuring Actuator’s base path 389 ■ Enabling and disabling Actuator endpoints 390 15.2 Consuming Actuator endpoints 391 Fetching essential application information 392 ■ Viewing configuration details 395 ■ Viewing application activity 403 Tapping runtime metrics 405 15.3 Customizing Actuator 408 Contributing information to the /info endpoint 408 ■ Defining custom health indicators 414 ■ Registering custom metrics 415 Creating custom endpoints 417 15.4 Securing Actuator 420 16 Administering Spring 423 16.1 Using Spring Boot Admin 424 Creating an Admin server 424 ■ Registering Admin clients 426 16.2 Exploring the Admin server 427 Viewing general application health and information 428 Watching key metrics 428 ■ Examining environment properties 429 ■ Viewing and setting logging levels 431 16.3 Securing the Admin server 431 Enabling login in the Admin server 432 ■ Authenticating with the Actuator 433 17 Monitoring Spring with JMX 435 17.1 Working with Actuator MBeans 435 17.2 Creating your own MBeans 437 17.3 Sending notifications 440 18 Deploying Spring 443 18.1 Weighing deployment options 444 18.2 Building executable JAR files 445
CONTENTS xv18.3 Building container images 446 Deploying to Kubernetes 449 ■ Enabling graceful shutdown 451 Working with application liveness and readiness 452 18.4 Building and deploying WAR files 455 18.5 The end is where we begin 457 appendix Bootstrapping Spring applications 459 index 479
(This page has no text content)
preface Spring entered the development world more than 18 years ago with the fundamental mission of making Java application development easier. Originally, that meant offering a lightweight alternative to EJB 2.x. But Spring was just getting started. Over the years, Spring expanded its mission of simplicity to address common development challenges, including persistence, security, integration, cloud computing, and others. Although Spring is closing in on two decades of enabling and simplifying enterprise Java development, it shows no signs of slowing down. Spring continues to address Java development challenges, whether it be creating an application deployed to a conventional application server or a containerized application deployed to a Kuberne- tes cluster in the cloud. And with Spring Boot providing autoconfiguration, build dependency help, and runtime monitoring, there has never been a better time to be a Spring developer! This edition of Spring in Action is your guide to Spring and Spring Boot and has been updated to reflect the best of what both have to offer. Even if you’re new to Spring, you’ll have your first Spring application up and running before the end of the first chap- ter. As the book progresses, you’ll learn how to create web applications, work with data, secure your application, and manage application configuration. Next, you’ll explore options for integrating your Spring applications with other applications and how to ben- efit from reactive programming in your Spring applications, including the new RSocket communication protocol. As the book draws to a close, you’ll see how to prepare your application for production and learn options for deploying.xvii
PREFACExviii Whether you’re new to Spring or have many years of Spring development to your credit, this is your next step in your journey. I’m excited for you and happy to bring this guide to you. I look forward to seeing what you create with Spring!
acknowledgments One of the most amazing things that Spring and Spring Boot do is automatically pro- vide all of the foundational plumbing for an application, leaving you as a developer to focus primarily on the logic that’s unique to your application. Unfortunately, no such magic exists for writing a book. Or does it? At Manning, several people worked their magic to make sure that this book is the best it can possibly be. Many thanks in particular to my development editor, Jenny Stout, and to production editor, Deirdre Hiam, copy editor, Pamela Hunt, graphics editor, Jennifer Houle, and the entire production team for their wonderful work in making this book a reality. As the book was forming, we had several peer reviewers take an early look, give us feedback, and help make sure that the book stayed on target and covered the right stuff. For this, my thanks go to Al Pezewski, Alessandro Campeis, Becky Huett, Chris- tian Kreutzer-Beck, Conor Redmond, David Paccoud, David Torrubia Iñigo, David Witherspoon German Gonzalez-Morris, Iain Campbell, Jon Guenther, Kevin Liao, Mark Dechamps, Michael Bright, Philippe Vialatte, Pierre-Michel Ansel, Tony Sweets, William Fly, and Zorodzayi Mukuya. I absolutely must give a shout out to everyone on the Spring engineering team. You consistently produce some of the most incredible stuff I’ve ever worked with, and I am proud to consider you my colleagues. Many thanks go to my fellow speakers on the No Fluff/Just Stuff tour. I continue to learn so much from every one of you. And many thanks to those of you who havexix
Comments 0
Loading comments...
Reply to Comment
Edit Comment