Table of Contents

Open all
Close all
Preface
25
What Is Spring Boot?
25
Prior Knowledge and Target Group
25
Date4u Demo Application, Tasks, and Solutions
25
Chapter Organization
26
The * Sections
27
Which Java Version Is Used in the Book?
27
Required Software
27
Development Environment
28
Conventions
28
Program Listings
29
Download and Online Information
30
About the Author
31
Feedback
32
1 Introduction
33
1.1 History of Spring Framework and Your First Spring Project
33
1.1.1 Tasks of Java Platform, Standard Edition
33
1.1.2 Enterprise Requirements
33
1.1.3 Development of Java Enterprise Frameworks
34
1.1.4 Rod Johnson Develops a Framework
34
1.1.5 Spring Framework: Many Configurations Are Required
36
1.2 Spring Boot
37
1.2.1 Spring Boot Versions
38
1.2.2 Support Period
39
1.2.3 Alternatives to Spring
40
1.2.4 Setting Up a Spring Boot Project
43
1.2.5 Building Spring Projects in Development Environments
48
1.3 Spring Boot Project: Dependencies and Starter
53
1.3.1 Project Object Model with Parent Project Object Model
54
1.3.2 Dependencies as Imports
57
1.3.3 Milestones and the Snapshots Repository
58
1.3.4 Configuring Annotation Processors
58
1.3.5 Starter: Dependencies of the Spring Initializr
59
1.4 Getting Started with Configurations and Logging
61
1.4.1 Turning Off the Banner
62
1.4.2 Logging API and Simple Logging Facade for Java
62
1.5 Summary
65
2 Containers for Spring-Managed Beans
67
2.1 Spring Container
67
2.1.1 Start Container
67
2.1.2 Instantiate SpringApplication
68
2.1.3 SpringApplicationBuilder *
69
2.1.4 What main(…) Does and Doesn’t Do
70
2.1.5 The run(…) Method Returns ConfigurableApplicationContext
70
2.1.6 Context Methods
71
2.2 Package Structure of the Date4u Application
74
2.3 Pick Up Spring-Managed Beans through Classpath Scanning
76
2.3.1 Fill Container with Beans
76
2.3.2 @Component
77
2.3.3 @Repository, @Service, @Controller
80
2.3.4 Control Classpath Scanning More Precisely with @ComponentScan *
82
2.4 Interactive Applications with the Spring Shell
89
2.4.1 Include a Spring Shell Dependency
89
2.4.2 First Interactive Application
91
2.4.3 Write Shell Component: @ShellComponent, @ShellMethod
91
2.5 Injecting Dependencies
95
2.5.1 Build Object Graphs
95
2.5.2 Inversion of Control and Dependency Injection
97
2.5.3 Injection Types
97
2.5.4 PhotoService and PhotoCommands
102
2.5.5 Multiple Dependencies
105
2.5.6 Behavior in Case of a Missing Component
106
2.5.7 Optional Dependency
107
2.5.8 Cyclic Dependencies *
109
2.5.9 Inject Other Things
110
2.6 Configuration Classes and Factory Methods
111
2.6.1 What @Component Can’t Do
111
2.6.2 @Configuration and @Bean
111
2.6.3 Parameter Injection of an @Bean Method
119
2.6.4 @Configuration Bean and Lite Bean
119
2.6.5 InjectionPoint *
121
2.6.6 Static @Bean Methods *
124
2.6.7 @Import and @ImportSelector *
125
2.7 Abstraction and Qualifications
127
2.7.1 Bean Name and Alias
127
2.7.2 AwtBicubicThumbnail for Thumbnails
128
2.7.3 Basic Types
131
2.7.4 ObjectProvider
140
2.7.5 @Order and @AutoConfigurationOrder *
142
2.7.6 Behavior in Selected Inheritance Relationships *
144
2.8 Beans Lifecycle
146
2.8.1 @DependsOn
146
2.8.2 Delayed Initialization (Lazy Initialization)
147
2.8.3 Bean Initialization Traditional
149
2.8.4 InitializingBean and DisposableBean *
155
2.8.5 Inheritance of the Lifecycle Methods
155
2.8.6 *Aware Interfaces *
156
2.8.7 BeanPostProcessor *
159
2.8.8 Register Spring-Managed Beans Somewhere Else
163
2.8.9 Hierarchical Contexts *
165
2.8.10 Singleton and Prototype Stateless or Stateful
168
2.9 Annotations from JSR 330, Dependency Injection for Java *
169
2.9.1 Dependency for the JSR 330 Standard Annotation
169
2.9.2 Map JSR 330 Annotations to Spring
170
2.10 Auto-Configuration
170
2.10.1 @Conditional and Condition
171
2.10.2 If, Then: @ConditionalOn*
173
2.10.3 Turn on Spring Debug Logging
180
2.10.4 Controlling Auto-Configurations Individually *
182
2.11 Spring Expression Language
185
2.11.1 ExpressionParser
185
2.11.2 SpEL in the Spring (Boot) API
186
2.12 Summary
190
3 Selected Modules of the Spring Framework
191
3.1 Helper Classes in Spring Framework
191
3.1.1 Components of org.springframework
191
3.2 External Configuration and the Environment
193
3.2.1 Code and External Configuration
193
3.2.2 Environment
194
3.2.3 Inject Values with @Value
195
3.2.4 Get Environment Assignments via @Value and ${…}
197
3.2.5 @Value and Default Values
198
3.2.6 Access to Configurations
200
3.2.7 Nested/Hierarchical Properties
205
3.2.8 Map Special Data Types
211
3.2.9 Relaxed Bindings
216
3.2.10 Property Sources
218
3.2.11 Define Spring Profiles
231
3.2.12 Activate Profiles
235
3.2.13 Spring-Managed Beans Depending on Profile
236
3.3 At the Beginning and End
238
3.3.1 CommandLineRunner and ApplicationRunner
238
3.3.2 At the End of the Application
241
3.3.3 Exit Java Programs with Exit Code *
242
3.4 Event Handling
247
3.4.1 Participating Objects
247
3.4.2 Context Events
248
3.4.3 ApplicationListener
249
3.4.4 @EventListener
250
3.4.5 Methods of the Event Classes
251
3.4.6 Write Event Classes and React to the Events
251
3.4.7 An Event Bus of Type ApplicationEventPublisher
252
3.4.8 Generic Events Using the PayloadApplicationEvent Example
253
3.4.9 Event Transformations
256
3.4.10 Sequences by @Order
256
3.4.11 Filter Events by Conditions
256
3.4.12 Synchronous and Asynchronous Events
257
3.4.13 ApplicationEventMulticaster *
258
3.4.14 Send Events via ApplicationContext
259
3.4.15 Attach Listener to SpringApplication *
259
3.4.16 Listener in spring.factories *
260
3.5 Resource Abstraction with Resource
261
3.5.1 InputStreamSource and Resource
261
3.5.2 Load Resources
263
3.5.3 Inject Resources via @Value
264
3.6 Type Conversion with ConversionService
265
3.6.1 ConversionService
266
3.6.2 DefaultConversionService and ApplicationConversionService
267
3.6.3 ConversionService as Spring-Managed Bean
269
3.6.4 Register Your Own Converters with the ConverterRegistry
270
3.6.5 Printer and Parser
275
3.6.6 FormatterRegistry
277
3.6.7 DataBinder
279
3.7 Internationalization *
283
3.7.1 Possibilities for Internationalization with Java SE
283
3.7.2 MessageSource under Subtypes
284
3.8 Test-Driven Development with Spring Boot
289
3.8.1 Test Related Entries from Spring Initializr
289
3.8.2 Annotation @Test
290
3.8.3 Test Case for the FileSystem Class
290
3.8.4 Test Multitier Applications, Exchange Objects
294
3.8.5 Mocking Framework Mockito
298
3.8.6 @InjectMocks
301
3.8.7 Verify Behavior
302
3.8.8 Testing with ReflectionTestUtils
303
3.8.9 With or Without Spring Support
305
3.8.10 Test Properties
308
3.8.11 @TestPropertySource
309
3.8.12 @ActiveProfiles
310
3.8.13 Appoint Deputy
311
3.8.14 @DirtiesContext
313
3.9 Testing Slices Using a JSON Example *
314
3.9.1 JSON
314
3.9.2 Jackson
315
3.9.3 Write a Java Object in JSON
315
3.9.4 Testing JSON Mappings: @JsonTest
318
3.9.5 Mapping with @JsonComponent
321
3.10 Scheduling *
324
3.10.1 Scheduling Annotations and @EnableScheduling
325
3.10.2 @Scheduled
325
3.10.3 Disadvantages of @Scheduled and Alternatives
328
3.11 Types from org.springframework.*.[lang|util]
328
3.11.1 org.springframework.lang.*Null* Annotations
329
3.11.2 Package org.springframework.util
330
3.11.3 Package org.springframework.data.util
331
3.12 Summary
335
4 Selected Proxies
337
4.1 Proxy Pattern
337
4.1.1 Proxy Deployment in Spring
339
4.1.2 Dynamically Generate Proxies
340
4.2 Caching
343
4.2.1 Optimization through Caching
343
4.2.2 Caching in Spring
344
4.2.3 Component with the @Cacheable Method
345
4.2.4 Use @Cacheable Proxy
346
4.2.5 @Cacheable + Condition
348
4.2.6 @Cacheable + Unless
349
4.2.7 @CachePut
350
4.2.8 @CacheEvict
351
4.2.9 Specify Your Own Key Generators
352
4.2.10 @CacheConfig
358
4.2.11 Cache Implementations
358
4.2.12 Caching with Caffeine
359
4.2.13 Disable the Caching in the Test
360
4.3 Asynchronous Calls
361
4.3.1 @EnableAsync and @Async Methods
362
4.3.2 Example with @Async
362
4.3.3 The CompletableFuture Return Type
365
4.4 TaskExecutor *
369
4.4.1 TaskExecutor Implementations
370
4.4.2 Set Executor and Handle Exceptions
372
4.5 Spring and Bean Validation
374
4.5.1 Parameter Checks
374
4.5.2 Jakarta Bean Validation (JSR 303)
375
4.5.3 Dependency on Spring Boot Starter Validation
375
4.5.4 Photo with Jakarta Bean Validation Annotations
376
4.5.5 Inject and Test a Validator
378
4.5.6 Spring and the Bean Validation Annotations
380
4.5.7 Bean Validation Annotations to Methods
382
4.5.8 Validation Everywhere Using a Configuration Example
382
4.5.9 Test Validation *
383
4.6 Spring Retry *
387
4.6.1 Spring Retry Project
387
4.6.2 @Retryable
389
4.6.3 Fallback with @Recover
392
4.6.4 RetryTemplate
394
4.7 Summary
395
5 Connecting to Relational Databases
397
5.1 Set Up an H2 Database
397
5.1.1 Brief Introduction to the H2 Database
397
5.1.2 Install and Launch H2
398
5.1.3 Connect to the Database via the H2 Console
402
5.1.4 Date4u Database Schema
404
5.2 Realize Database Accesses with Spring
407
5.2.1 Spring Helper
407
5.3 Spring Boot Starter JDBC
408
5.3.1 Include the JDBC Starter in the Project Object Model
408
5.3.2 Provide JDBC Connection Data
410
5.3.3 Inject DataSource or JdbcTemplate
410
5.3.4 Connection Pooling
413
5.3.5 Log JDBC Accesses
414
5.3.6 JDBC org.springframework.jdbc Package and Its Subpackages
415
5.3.7 DataAccessException
415
5.3.8 Auto-Configuration for DataSource *
418
5.3.9 Addressing Multiple Databases
419
5.3.10 DataSourceUtils *
421
5.4 JdbcTemplate
422
5.4.1 Execute Any SQL: execute(…)
422
5.4.2 SQL Updates: update(…)
423
5.4.3 Query Individual Values: queryForObject(…)
423
5.4.4 Define a Placeholder for a PreparedStatement
424
5.4.5 Query Whole Row: queryForMap(…)
425
5.4.6 Query Multiple Rows with One Element: queryForList(…)
426
5.4.7 Read Multiple Rows and Columns: queryForList(…)
426
5.5 Data Types for Mapping to Results
427
5.5.1 RowMapper
428
5.5.2 RowCallbackHandler
433
5.5.3 ResultSetExtractor
434
5.6 NamedParameterJdbcTemplate
437
5.6.1 Type Relationships of *JdbcTemplate
438
5.6.2 Methods of the NamedParameterJdbcTemplate
439
5.6.3 Pass Values of NamedParameterJdbcTemplate through a Map
439
5.6.4 SqlParameterSource
439
5.6.5 Access to Underlying Objects *
442
5.7 Batch Operations *
443
5.7.1 Batch Methods for JdbcTemplate
443
5.7.2 BatchPreparedStatementSetter
444
5.7.3 Batch Methods at NamedParameterJdbcTemplate
449
5.7.4 SqlParameterSourceUtils
450
5.7.5 Configuration Properties
450
5.8 BLOBs and CLOBs *
451
5.8.1 SqlLobValue
452
5.8.2 LobHandler and DefaultLobHandler
453
5.8.3 Read LOBs via AbstractLobStreamingResultSetExtractor
454
5.9 Subpackage org.springframework.jdbc.core.simple *
455
5.9.1 SimpleJdbcInsert
456
5.10 Package org.springframework.jdbc.object *
458
5.10.1 MappingSqlQuery
458
5.11 Transactions
460
5.11.1 ACID Principle
460
5.11.2 Local or Global/Distributed Transactions
461
5.11.3 JDBC Transactions: Auto-Commit
461
5.11.4 PlatformTransactionManager
462
5.11.5 TransactionTemplate
466
5.11.6 @Transactional
470
5.12 Summary
472
6 Jakarta Persistence with Spring
473
6.1 World of Objects and Databases
473
6.1.1 Transient and Persistent
474
6.1.2 Mapping Objects to Tables
474
6.1.3 Java Libraries for O/R Mapping
478
6.2 Jakarta Persistence
479
6.2.1 Persistence Provider
480
6.2.2 Jakarta Persistence Provider and JDBC
481
6.2.3 Jakarta Persistence Coverage
481
6.3 Spring Data JPA
482
6.3.1 Include Spring Boot Starter Data JPA
482
6.3.2 Configurations
483
6.4 Jakarta Persistence Entity Bean
485
6.4.1 Develop an Entity Bean Class
486
6.5 Jakarta Persistence API
492
6.5.1 Getting the EntityManager from Spring
492
6.5.2 Search an Entity Bean by Its Key: find(…)
494
6.5.3 find(…) and getReference(…)
496
6.5.4 Query Options with the EntityManager
497
6.6 Jakarta Persistence Query Language (JPQL)
498
6.6.1 JPQL Example with SELECT and FROM
498
6.6.2 Build and Submit JPQL Queries with createQuery(…)
500
6.6.3 Conditions in WHERE
502
6.6.4 Parameterize JPQL Calls
503
6.6.5 JPQL Operators and Functions
506
6.6.6 Order Returns with ORDER BY
510
6.6.7 Projection on Scalar Values
511
6.6.8 Aggregate Functions
512
6.6.9 Projection on Multiple Values
513
6.6.10 Named Declarative Queries (Named Queries)
517
6.7 Call Database Functions and Send Native SQL Queries
519
6.7.1 Call Database Functions: FUNCTION(…)
519
6.7.2 Use createNativeQuery(…) via EntityManager
520
6.7.3 @NamedNativeQuery
521
6.7.4 @NamedNativeQuery with resultSetMapping
522
6.8 Write Access with the EntityManager in Transactions
525
6.8.1 Transactional Operations
525
6.8.2 persist(…)
525
6.8.3 EntityTransaction
526
6.8.4 PlatformTransactionManager with JpaTransactionManager
527
6.8.5 @Transactional
528
6.8.6 Save versus Update
529
6.8.7 remove(…)
530
6.8.8 Synchronization or Flush
530
6.8.9 Query with UPDATE and DELETE
531
6.9 Persistence Context and Other Transaction Controls
531
6.9.1 Jakarta Persistence API and Database Operations
531
6.9.2 States of an Entity Bean
532
6.10 Advanced ORM Metadata
535
6.10.1 Database-First and Code-First Approaches
535
6.10.2 Set the Table Name via @Table
536
6.10.3 Change the @Entity Name
537
6.10.4 Persistent Attributes
537
6.10.5 @Basic and @Transient
539
6.10.6 Column Description and @Column
539
6.10.7 Entity Bean Data Types
542
6.10.8 Map Data Types with AttributeConverter
544
6.10.9 Key Identification
547
6.10.10 Embedded Types
551
6.10.11 Entity Bean Inherits Properties from a Superclass
553
6.11 Relationships between Entities
555
6.11.1 Supported Associations and Relationship Types
555
6.11.2 1:1 Relationship
555
6.11.3 Bidirectional Relationships
559
6.11.4 1:n Relationship
560
6.11.5 n:m Relationships *
566
6.12 FetchType: Lazy and Eager Loading
567
6.12.1 Enumeration with FetchType
568
6.12.2 Hibernate Type: PersistentBag
568
6.12.3 1 + N Query Problem: Performance Anti-Pattern
570
6.13 Cascading
573
6.13.1 CascadeType Enumeration Type
574
6.13.2 Set CascadeType
576
6.13.3 cascade=REMOVE versus orphanRemoval=true
577
6.14 Repositories
577
6.14.1 Data Access Layer
578
6.14.2 Methods in the Repository
580
6.14.3 SimpleJpaRepository
582
6.15 Summary
585
7 Spring Data JPA
587
7.1 What Tasks Does Spring Data Perform?
587
7.1.1 For Which Systems Is Spring Data Available?
588
7.2 Spring Data Commons: CrudRepository
589
7.2.1 CrudRepository Type
589
7.2.2 Java Persistence API–Based Repositories
591
7.3 Subtypes of CrudRepository
594
7.3.1 ListCrudRepository
594
7.3.2 Technology-Specific [List]CrudRepository Subtypes
595
7.3.3 Selected Methods via Repository
597
7.4 Paging and Sorting with [List]PagingAndSortingRepository
598
7.4.1 JpaRepository: Subttype of ListPagingAndSortingRepository and ListCrudRepository
599
7.4.2 Sort Type
600
7.4.3 Sort.TypedSort<T>
601
7.4.4 Pageable and PageRequest
602
7.4.5 Sort Paginated Pages
607
7.5 QueryByExampleExecutor *
608
7.5.1 Sample
608
7.5.2 QueryByExampleExecutor
609
7.5.3 Sample into the Example
610
7.5.4 Build ExampleMatcher
611
7.5.5 Ignore Properties
611
7.5.6 Set String Comparison Techniques
612
7.5.7 Set Individual Rules with GenericPropertyMatcher
613
7.5.8 PropertyValueTransformer
613
7.6 Formulate Your Own Queries with @Query
615
7.6.1 @Query Annotation
615
7.6.2 Modifying @Query Operations with @Modifying
617
7.6.3 Fill IN Parameter by Array/Varg/Collection
617
7.6.4 @Query with JPQL Projection
618
7.6.5 Sort and Pageable Parameters
619
7.6.6 Add New Query Methods
620
7.6.7 Queries with Spring Expression Language Expressions
621
7.6.8 Using the @NamedQuery of an Entity Bean
622
7.6.9 @Query Annotation with Native SQL
622
7.7 Stored Procedures *
624
7.7.1 Define a Stored Procedure in H2
625
7.7.2 Calling a Stored Procedure via a Native Query
627
7.7.3 Call a Stored Procedure with @Procedure
627
7.8 Derived Query Methods
628
7.8.1 Individual CRUD Operations via Method Names
628
7.8.2 Structure of the Derived Query Methods
629
7.8.3 Returns from Derived Query Methods
633
7.8.4 Asynchronous Query Methods
633
7.8.5 Streaming Query Methods
634
7.8.6 Advantages and Disadvantages of Derived Query Methods
634
7.9 Criteria API and JpaSpecificationExecutor
635
7.9.1 Criteria API
636
7.9.2 Functional Interface Specification
637
7.9.3 JpaSpecificationExecutor
638
7.9.4 Methods in JpaSpecificationExecutor
639
7.9.5 Specification Implementations
639
7.9.6 Assemble Specification Instances
641
7.9.7 Internals *
642
7.9.8 Metamodel Classes
643
7.9.9 Cons of Using the Criteria API
646
7.10 Alternatives to JDBC Jakarta Persistence
647
7.10.1 Querydsl
648
7.10.2 Spring Data JDBC
655
7.11 Good Design with Repositories
660
7.11.1 Abstractions through the Onion Architecture
660
7.11.2 Think of the Interface Segregation Principle and the Onion!
661
7.11.3 Fragment Interface
662
7.12 Projections
664
7.12.1 Perform Projections Yourself
665
7.12.2 Projections in Spring Data
665
7.12.3 Interface-Based Projection
665
7.12.4 Projections with SpEL Expressions
667
7.12.5 Projections with Default Methods
668
7.12.6 Class-Based Projections
668
7.12.7 Dynamic Projections
669
7.13 [Fetchable]FluentQuery *
670
7.14 Auditing *
672
7.14.1 Auditing with Spring Data
672
7.14.2 Auditing with Spring Data JPA
672
7.14.3 AuditorAware for User Information
673
7.14.4 Outlook: Spring Data Envers
674
7.15 Incremental Data Migration
675
7.15.1 Long Live the Data
676
7.15.2 Evolutionary Database Design
676
7.15.3 Incremental Data Migration with Flyway
677
7.15.4 Flyway in Spring Boot: Migration Scripts
677
7.15.5 Migrations in Java Code
680
7.15.6 Flyway Migrations outside Spring
681
7.16 Test the Data Access Layer
682
7.16.1 What Do We Want to Test?
682
7.16.2 Test Slices
683
7.16.3 Deploy an In-Memory Test Database
684
7.16.4 Assign Connection to the Test Database
684
7.16.5 Build Tables with Initialization Scripts
686
7.16.6 Testcontainers Project
687
7.16.7 Demo Data
689
7.16.8 @Sql and @SqlGroup
690
7.16.9 TestEntityManager
691
7.17 Summary
691
8 Spring Data for NoSQL Databases
693
8.1 Not Only SQL
693
8.2 MongoDB
694
8.2.1 MongoDB: Documents and Collections
694
8.2.2 About MongoDB
695
8.2.3 Install and Start the MongoDB Community Server
696
8.2.4 GUI Tools for MongoDB
697
8.2.5 Spring Data MongoDB
698
8.2.6 MongoDB Application Programming Interfaces
699
8.2.7 MongoDB Documents
700
8.2.8 MongoTemplate Class
701
8.2.9 MongoDB Repositories
704
8.2.10 Test MongoDB Programs
706
8.3 Elasticsearch
707
8.3.1 Text Search Is Different
707
8.3.2 Apache Lucene
708
8.3.3 Documents and Fields
708
8.3.4 Index
708
8.3.5 Weaknesses of Apache Lucene
709
8.3.6 Lucene Attachments: Elasticsearch and Apache Solr
710
8.3.7 Install and Launch Elasticsearch
711
8.3.8 Spring Data Elasticsearch
712
8.3.9 Documents
713
8.3.10 ElasticsearchRepository
715
8.3.11 @DataElasticsearchTest
718
8.4 Summary
719
9 Spring Web
721
9.1 Web Server
721
9.1.1 Java Web Server
722
9.1.2 Spring Boot Starter Web
723
9.1.3 Use Other Web Servers *
724
9.1.4 Adjust Port via server.port
724
9.1.5 Serve Static Resources
725
9.1.6 WebJars
726
9.1.7 Transport Layer Security Encryption
726
9.2 Generate Dynamic Content
728
9.2.1 Stone Age: The Common Gateway Interface
728
9.2.2 Servlet Standard
729
9.2.3 Program @WebServlet
730
9.2.4 Weaknesses of Servlets
732
9.3 Spring Web MVC
732
9.3.1 Spring Containers in Web Applications
733
9.3.2 @Controller
734
9.3.3 @RestController
735
9.3.4 Controller to [Service] to Repository
737
9.4 Hot Code Swapping
738
9.4.1 Hot Swapping of the Java Virtual Machine
739
9.4.2 Spring Developer Tools
739
9.5 HTTP
740
9.5.1 HTTP Request and Response
740
9.5.2 Set Up an HTTP Client for Testing Applications
741
9.6 Request Matching
742
9.6.1 @RequestMapping
742
9.6.2 @*Mapping
743
9.6.3 More General Path Expressions and Path Matchers
743
9.6.4 @RequestMapping on Type
744
9.7 Send Response
745
9.7.1 HttpMessageConverter in the Application
745
9.7.2 Format Conversions of Handler Method Returns
746
9.7.3 Mapping to JSON Documents
746
9.7.4 ResponseEntity = Statuscode + Header + Body
752
9.8 Evaluate Request
755
9.8.1 Handler Methods with Parameters
755
9.8.2 Data Transmission from Client to Controller
756
9.8.3 Data Acceptance via Parameters
756
9.8.4 Evaluate Query Parameters
757
9.8.5 Optional Query Parameters
757
9.8.6 Map All Query Parameters
758
9.8.7 Evaluate a Path Variable
760
9.8.8 MultipartFile
763
9.8.9 Evaluate Header
765
9.8.10 HttpEntity Subclasses RequestEntity and ResponseEntity *
765
9.9 Type Conversion of the Parameters
766
9.9.1 YearMonth Converter Example
766
9.9.2 @DateTimeFormat and @NumberFormat
767
9.9.3 Map Query Parameters and Form Data to a Bean
768
9.9.4 Register Your Own Type Converters
772
9.9.5 URI Template Pattern with Regular Expressions
774
9.10 Exception Handling and Error Message
775
9.10.1 Map Exceptions to Status Codes Yourself
775
9.10.2 Escalates
775
9.10.3 Configuration Properties server.error.*
777
9.10.4 Exception Resolver
780
9.10.5 Map Exception to Status Code with @ResponseStatus
780
9.10.6 ResponseStatusException
781
9.10.7 Local Controller Exception Handling with @ExceptionHandler
783
9.10.8 RFC 7807: “Problem Details for HTTP APIs”
785
9.10.9 Global Controller Exception Handling with Controller Advice
787
9.11 RESTful API
789
9.11.1 Principles behind REST
789
9.11.2 Implement REST Endpoints for Profiles
795
9.11.3 Data Transfer Objects
797
9.11.4 Best Practice: Don’t Deliver a Complete Collection at Once
800
9.11.5 GET and DELETE on Individual Resources
800
9.11.6 POST and PUT with @RequestBody
802
9.11.7 UriComponents
805
9.12 Asynchronous Web Requests *
806
9.12.1 Long Queries Block the Worker Thread
806
9.12.2 Write Asynchronously to the Output
807
9.12.3 A Handler Method Returns Callable
808
9.12.4 WebAsyncTask
808
9.12.5 A Handler Method Returns DeferredResult
809
9.12.6 StreamingResponseBody
809
9.13 Spring Data Web Support
811
9.13.1 Loading from the Repository
811
9.13.2 Pageable and Sort as Parameter Types
812
9.13.3 Return Type Page
814
9.13.4 Querydsl Predicate as a Parameter Type
815
9.14 Documentation of a RESTful API with OpenAPI
817
9.14.1 Description of a RESTful API
817
9.14.2 OpenAPI Specification
817
9.14.3 Where Does the OpenAPI Document Come From?
819
9.14.4 OpenAPI with Spring
819
9.14.5 springdoc-openapi
820
9.14.6 Better Documentation with OpenAPI Annotations
822
9.14.7 Generate Java Code from an OpenAPI Document
822
9.14.8 Spring REST Docs
824
9.15 Testing the Web Layer
825
9.15.1 Test QuoteRestController
825
9.15.2 Annotation @WebMvcTest
827
9.15.3 Writing a Test Method with MockMvc
827
9.15.4 Test REST Endpoints with the Server
830
9.15.5 WebTestClient
831
9.16 Best Practices When Using a RESTful API
832
9.16.1 Jakarta Bean Validation
832
9.16.2 Resource ID
833
9.16.3 Map Data Transfer Objects
834
9.16.4 Versioning of RESTful Web Services
836
9.17 Secure Web Applications with Spring Security
837
9.17.1 The Importance of Spring Security
837
9.17.2 Dependency on Spring Boot Starter Security
838
9.17.3 Authentication
838
9.17.4 SecurityContext and SecurityContextHolder
839
9.17.5 AuthenticationManager
842
9.17.6 SpringBootWebSecurityConfiguration
843
9.17.7 AuthenticationManager and ProviderManager
846
9.17.8 UserDetailsService Interface
847
9.17.9 Spring-Managed Bean PasswordEncoder
852
9.17.10 BasicAuthenticationFilter
856
9.17.11 Access to the User
857
9.17.12 Authorization and the Cookie
858
9.17.13 Token-Based Authentication with JSON Web Tokens
859
9.18 Consume RESTful Web Services
867
9.18.1 Classes for Addressing HTTP Endpoints
867
9.18.2 A WebClient Example
868
9.18.3 Declarative Web Service Clients
873
9.19 Summary
877
10 Logging and Monitoring
879
10.1 Logging
879
10.1.1 Why Create a Protocol?
879
10.1.2 Log Group
880
10.2 Logging Implementation
880
10.2.1 Conversion to Log4j 2
881
10.2.2 Logging Pattern Layout
881
10.2.3 Change the Logging Configuration
883
10.2.4 Banner
883
10.2.5 Logging at Start Time
884
10.2.6 Testing Written Log Message
884
10.3 Monitor Applications with Spring Boot Actuator
885
10.3.1 Determine the Health Status via the Actuator
886
10.3.2 Activation of the Endpoints
887
10.3.3 Info Supplements
889
10.3.4 Parameters and JSON Returns
889
10.3.5 New Actuator Endpoints
891
10.3.6 Am I Healthy?
892
10.3.7 HealthIndicator
893
10.3.8 Metrics
893
10.4 Micrometer and Prometheus
894
10.4.1 Micrometer
895
10.4.2 Prometheus: The Software
898
10.5 Summary
900
11 Build and Deployment
901
11.1 Package and Run Spring Boot Programs
901
11.1.1 Deployment Options
901
11.1.2 Launching a Spring Boot Program via Maven
902
11.1.3 Packing a Spring Boot Program into a Java Archive
902
11.1.4 spring-boot-maven-plugin
903
11.2 Spring Applications in the OCI Container
904
11.2.1 Container
904
11.2.2 Install and Use Docker
906
11.2.3 H2 Start, Stop, Port Forwarding, and Data Volumes
908
11.2.4 Prepare a Spring Boot Docker Application
910
11.2.5 Docker Compose
913
11.2.6 Terminate Applications with an Actuator Endpoint
914
11.3 Summary
915
A Migration from Spring Boot 2 to Spring Boot 3
917
A.1 Preparation
917
A.2 Jakarta EE 9
917
A.3 Other Innovations
918
A.4 Spring-Boot-Properties-Migrator
919
A.5 Spring Boot Migrator Project
919
A.6 Dependency Upgrades
920
B The Author
923
Index
925