Download the Full Ebook and Access More Features - ebooknice.
com
(Ebook) Pro Spring 6 with Kotlin: An In-depth
Guide to Using Kotlin APIs in Spring Framework 6
by Peter Späth, Iuliana Cosmina, Rob Harrop, Chris
Schaefer ISBN 9781484295571, 9781484295564,
1484295579, 1484295560, B0C8RV9Q5Y
https://ebooknice.com/product/pro-spring-6-with-kotlin-an-
in-depth-guide-to-using-kotlin-apis-in-spring-
framework-6-52328224
OR CLICK HERE
DOWLOAD EBOOK
Download more ebook instantly today at https://ebooknice.com
Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...
Start reading on any device today!
(Ebook) Pro Spring 6 with Kotlin : An In-depth Guide to
Using Kotlin APIs in Spring Framework 6 by Peter Späth;
Iuliana Cosmina; Rob Harrop; Chris Schaefer ISBN
9781484295571, 1484295579
https://ebooknice.com/product/pro-spring-6-with-kotlin-an-in-depth-
guide-to-using-kotlin-apis-in-spring-framework-6-52181404
ebooknice.com
(Ebook) Biota Grow 2C gather 2C cook by Loucas, Jason;
Viles, James ISBN 9781459699816, 9781743365571,
9781925268492, 1459699815, 1743365578, 1925268497
https://ebooknice.com/product/biota-grow-2c-gather-2c-cook-6661374
ebooknice.com
(Ebook) Pro Spring 6: An In-Depth Guide to the Spring
Framework, 6th Edition by Iuliana Cosmina, Rob Harrop,
Chris Schaefer, Clarence Ho ISBN 9781484286395, 1484286391
https://ebooknice.com/product/pro-spring-6-an-in-depth-guide-to-the-
spring-framework-6th-edition-50725814
ebooknice.com
(Ebook) Matematik 5000+ Kurs 2c Lärobok by Lena
Alfredsson, Hans Heikne, Sanna Bodemyr ISBN 9789127456600,
9127456609
https://ebooknice.com/product/matematik-5000-kurs-2c-larobok-23848312
ebooknice.com
(Ebook) SAT II Success MATH 1C and 2C 2002 (Peterson's SAT
II Success) by Peterson's ISBN 9780768906677, 0768906679
https://ebooknice.com/product/sat-ii-success-
math-1c-and-2c-2002-peterson-s-sat-ii-success-1722018
ebooknice.com
(Ebook) Cambridge IGCSE and O Level History Workbook 2C -
Depth Study: the United States, 1919-41 2nd Edition by
Benjamin Harrison ISBN 9781398375147, 9781398375048,
1398375144, 1398375047
https://ebooknice.com/product/cambridge-igcse-and-o-level-history-
workbook-2c-depth-study-the-united-states-1919-41-2nd-edition-53538044
ebooknice.com
(Ebook) Pro Spring 5: an in-depth guide to the Spring
framework and its tools by Cosmina, Iuliana ISBN
9781484228074, 9781484228081, 1484228073, 1484228081
https://ebooknice.com/product/pro-spring-5-an-in-depth-guide-to-the-
spring-framework-and-its-tools-11804000
ebooknice.com
(Ebook) Master SAT II Math 1c and 2c 4th ed (Arco Master
the SAT Subject Test: Math Levels 1 & 2) by Arco ISBN
9780768923049, 0768923042
https://ebooknice.com/product/master-sat-ii-math-1c-and-2c-4th-ed-
arco-master-the-sat-subject-test-math-levels-1-2-2326094
ebooknice.com
(Ebook) Pro Spring MVC with WebFlux: Web Development in
Spring Framework 5 and Spring Boot 2 by Marten Deinum;
Iuliana Cosmina ISBN 9781484256657, 1484256654
https://ebooknice.com/product/pro-spring-mvc-with-webflux-web-
development-in-spring-framework-5-and-spring-boot-2-25767182
ebooknice.com
Pro Spring 6
with Kotlin
An In-depth Guide to Using Kotlin APIs
in Spring Framework 6
—
Peter Späth
Iuliana Cosmina
Rob Harrop
Chris Schaefer
Pro Spring 6 with Kotlin
An In-depth Guide to Using Kotlin APIs
in Spring Framework 6
Peter Späth
Iuliana Cosmina
Rob Harrop
Chris Schaefer
Pro Spring 6 with Kotlin: An In-depth Guide to Using Kotlin APIs in Spring
Framework 6
Peter Späth Iuliana Cosmina
Leipzig, Sachsen, Germany Edinburgh, UK
Rob Harrop Chris Schaefer
Reddish, UK Venice, FL, USA
ISBN-13 (pbk): 978-1-4842-9556-4 ISBN-13 (electronic): 978-1-4842-9557-1
https://doi.org/10.1007/978-1-4842-9557-1
Copyright © 2023 by Peter Späth, Iuliana Cosmina, Rob Harrop, Chris Schaefer
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image, we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Melissa Duffy
Development Editor: Laura Berendson
Coordinating Editor: Mark Powers
Copy Editor: Bill McManus
Cover designed by eStudioCalamar
Cover image by Jack Blueberry on Unsplash (https://unsplash.com)
Distributed to the book trade worldwide by Apress Media, LLC, 1 New York Plaza, New York, NY 10004,
U.S.A. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit
www.springeronline.com. Apress Media, LLC is a California LLC, and the sole member (owner) is Springer
Science + Business Media Finance Inc. (SSBM Finance Inc.). SSBM Finance Inc. is a Delaware corporation.
For information on translations, please e-mail [email protected]; for reprint,
paperback, or audio rights, please e-mail [email protected].
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at https://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the authors in this book is available to
readers on GitHub (https://github.com/Apress). For more detailed information, please visit
https://www.apress.com/gp/services/source-code.
Paper in this product is recyclable
To Alina
—Peter
Table of Contents
About the Authors���������������������������������������������������������������������������������������������������xix
About the Technical Reviewer��������������������������������������������������������������������������������xxi
Introduction����������������������������������������������������������������������������������������������������������xxiii
■
■Chapter 1: Introducing Spring������������������������������������������������������������������������������� 1
About This Book��������������������������������������������������������������������������������������������������������������� 1
What Is Spring?���������������������������������������������������������������������������������������������������������������� 2
Evolution of the Spring Framework�������������������������������������������������������������������������������������������������������� 2
Spring Projects��������������������������������������������������������������������������������������������������������������������������������������� 3
Inverting Control or Injecting Dependencies?������������������������������������������������������������������ 6
Evolution of Dependency Injection��������������������������������������������������������������������������������������������������������� 7
Beyond Dependency Injection���������������������������������������������������������������������������������������������������������������� 8
The Spring Community��������������������������������������������������������������������������������������������������� 12
Alternatives to Spring����������������������������������������������������������������������������������������������������� 13
Summary������������������������������������������������������������������������������������������������������������������������ 13
■
■Chapter 2: Getting Started����������������������������������������������������������������������������������� 15
Conventions�������������������������������������������������������������������������������������������������������������������� 15
Who This Book Is For������������������������������������������������������������������������������������������������������ 16
What You Need for This Book����������������������������������������������������������������������������������������� 16
Prepare Your Development Environment������������������������������������������������������������������������ 18
Understanding Spring Packaging����������������������������������������������������������������������������������� 20
Choosing Modules for Your Application�������������������������������������������������������������������������� 24
v
■ Table of Contents
Accessing Spring Modules on the Maven Repository��������������������������������������������������������������������������� 25
Accessing Spring Modules Using Gradle���������������������������������������������������������������������������������������������� 25
Using Spring Boot Dependency Management�������������������������������������������������������������������������������������� 26
Using Spring Documentation������������������������������������������������������������������������������������������ 28
Putting a Spring into Hello World����������������������������������������������������������������������������������� 28
Building the Sample Hello World Application���������������������������������������������������������������������������������������� 28
Refactoring with Spring������������������������������������������������������������������������������������������������������������������������ 35
Summary������������������������������������������������������������������������������������������������������������������������ 39
■
■Chapter 3: Introducing IoC and DI in Spring�������������������������������������������������������� 41
Inversion of Control and Dependency Injection�������������������������������������������������������������� 42
Types of Inversion of Control���������������������������������������������������������������������������������������������������������������� 42
Setter Dependency Injection����������������������������������������������������������������������������������������������������������������� 45
Setter Injection vs. Constructor Injection��������������������������������������������������������������������������������������������� 47
Inversion of Control in Spring����������������������������������������������������������������������������������������� 49
Dependency Injection in Spring�������������������������������������������������������������������������������������� 49
Beans and BeanFactory������������������������������������������������������������������������������������������������������������������������ 49
Configuring ApplicationContext������������������������������������������������������������������������������������������������������������ 51
Basic Configuration Overview�������������������������������������������������������������������������������������������������������������� 51
Declaring Spring Components�������������������������������������������������������������������������������������������������������������� 52
Using Setter Injection��������������������������������������������������������������������������������������������������������������������������� 55
Using Constructor Injection������������������������������������������������������������������������������������������������������������������ 56
Using Field Injection����������������������������������������������������������������������������������������������������������������������������� 59
Using Injection Parameters�������������������������������������������������������������������������������������������� 61
Injecting Simple Values������������������������������������������������������������������������������������������������������������������������ 61
Injecting Values Using SpEL����������������������������������������������������������������������������������������������������������������� 62
Injection and ApplicationContext Nesting��������������������������������������������������������������������������������������������� 64
Injecting Collections����������������������������������������������������������������������������������������������������������������������������� 68
Using Method Injection��������������������������������������������������������������������������������������������������� 72
Lookup Method Injection���������������������������������������������������������������������������������������������������������������������� 72
Considerations for Lookup Method Injection���������������������������������������������������������������������������������������� 76
vi
■ Table of Contents
Understanding Bean Naming����������������������������������������������������������������������������������������� 77
Default Bean Naming Style for Beans Declared with @Component����������������������������������������������������� 77
Customizing Bean Naming Style���������������������������������������������������������������������������������������������������������� 78
Bean Naming Style for Beans Declared with @Bean��������������������������������������������������������������������������� 80
Explicit Bean Naming��������������������������������������������������������������������������������������������������������������������������� 82
The @AliasFor Annotation�������������������������������������������������������������������������������������������������������������������� 83
Understanding Bean Instantiation Mode���������������������������������������������������������������������������������������������� 85
Choosing an Instantiation Mode������������������������������������������������������������������������������������� 87
Additional Bean Scopes������������������������������������������������������������������������������������������������� 88
Resolving Dependencies������������������������������������������������������������������������������������������������ 89
Autowiring Your Bean����������������������������������������������������������������������������������������������������� 90
Constructor Autowiring������������������������������������������������������������������������������������������������������������������������� 91
byType Autowiring�������������������������������������������������������������������������������������������������������������������������������� 94
byName Autowiring������������������������������������������������������������������������������������������������������������������������������ 96
Yet Another Pickle��������������������������������������������������������������������������������������������������������������������������������� 98
When to Use Autowiring��������������������������������������������������������������������������������������������������������������������� 101
Summary���������������������������������������������������������������������������������������������������������������������� 101
■
■Chapter 4: Advanced Spring Configuration and Spring Boot����������������������������� 103
Spring’s Impact on Application Portability������������������������������������������������������������������� 104
Bean Life-Cycle Management�������������������������������������������������������������������������������������� 105
Hooking into Bean Creation������������������������������������������������������������������������������������������ 106
Executing a Method When a Bean Is Created������������������������������������������������������������������������������������� 107
Implementing the InitializingBean Interface��������������������������������������������������������������������������������������� 111
Using the JSR-250 @PostConstruct Annotation��������������������������������������������������������������������������������� 113
Understanding Order of Resolution���������������������������������������������������������������������������������������������������� 114
Hooking into Bean Destruction������������������������������������������������������������������������������������� 117
Executing a Method When a Bean Is Destroyed����������������������������������������������������������� 118
Implementing the DisposableBean Interface�������������������������������������������������������������������������������������� 119
Using the JSR-250 @PreDestroy Annotation�������������������������������������������������������������������������������������� 120
vii
■ Table of Contents
Understanding Order of Resolution���������������������������������������������������������������������������������������������������� 121
Using a Shutdown Hook��������������������������������������������������������������������������������������������������������������������� 122
Making Your Beans “Spring Aware”����������������������������������������������������������������������������� 122
Using the BeanNameAware Interface������������������������������������������������������������������������������������������������� 123
Using the ApplicationContextAware Interface������������������������������������������������������������������������������������ 125
Use of FactoryBeans���������������������������������������������������������������������������������������������������� 127
FactoryBean Example: The MessageDigestFactoryBean�������������������������������������������������������������������� 128
Accessing a FactoryBean Directly������������������������������������������������������������������������������������������������������ 132
JavaBeans PropertyEditors������������������������������������������������������������������������������������������ 133
Using the Built-in PropertyEditors������������������������������������������������������������������������������������������������������ 133
Creating a Custom PropertyEditor������������������������������������������������������������������������������������������������������ 138
More Spring ApplicationContext Configuration������������������������������������������������������������ 141
Internationalization������������������������������������������������������������������������������������������������������ 141
Internationalization with the MessageSource������������������������������������������������������������������������������������ 142
Using the getMessage() Method��������������������������������������������������������������������������������������������������������� 143
Why Use ApplicationContext As a MessageSource?��������������������������������������������������������������������������� 144
Using MessageSource in Stand-Alone Applications��������������������������������������������������������������������������� 145
Using Application Events�������������������������������������������������������������������������������������������������������������������� 145
Considerations for Event Usage���������������������������������������������������������������������������������������������������������� 147
Accessing Resources��������������������������������������������������������������������������������������������������� 148
Advanced Java/Kotlin Configuration Classes��������������������������������������������������������������� 150
Profiles������������������������������������������������������������������������������������������������������������������������� 153
An Example of Using the Spring Profiles Feature������������������������������������������������������������������������������� 153
Considerations for Using Profiles������������������������������������������������������������������������������������������������������� 158
Environment and PropertySource Abstraction������������������������������������������������������������� 158
Testing Spring Applications������������������������������������������������������������������������������������������ 164
Using Spring Test Annotations������������������������������������������������������������������������������������������������������������ 165
Implementing Logic Unit Tests������������������������������������������������������������������������������������������������������������ 167
Implementing an Integration Test������������������������������������������������������������������������������������������������������� 170
viii
■ Table of Contents
Configuring Profile for Integration Testing�������������������������������������������������������������������� 174
Implementing a Front-End Unit Test��������������������������������������������������������������������������������������������������� 175
Introducing Selenium������������������������������������������������������������������������������������������������������������������������� 176
Configuration Using Groovy������������������������������������������������������������������������������������������ 176
Using Spring Boot��������������������������������������������������������������������������������������������������������� 178
Summary���������������������������������������������������������������������������������������������������������������������� 187
■
■Chapter 5: Spring AOP��������������������������������������������������������������������������������������� 189
AOP Concepts��������������������������������������������������������������������������������������������������������������� 190
Types of AOP����������������������������������������������������������������������������������������������������������������� 191
Static AOP������������������������������������������������������������������������������������������������������������������������������������������� 191
Dynamic AOP�������������������������������������������������������������������������������������������������������������������������������������� 191
Choosing an AOP Type������������������������������������������������������������������������������������������������������������������������ 192
AOP in Spring��������������������������������������������������������������������������������������������������������������� 192
The AOP Alliance��������������������������������������������������������������������������������������������������������������������������������� 192
Spring AOP Architecture����������������������������������������������������������������������������������������������� 192
Joinpoints in Spring���������������������������������������������������������������������������������������������������������������������������� 193
Aspects in Spring�������������������������������������������������������������������������������������������������������������������������������� 193
Choosing an Advice Type�������������������������������������������������������������������������������������������������������������������� 200
Advisors and Pointcuts in Spring��������������������������������������������������������������������������������� 201
The Pointcut Interface������������������������������������������������������������������������������������������������������������������������ 201
Available Pointcut Implementations��������������������������������������������������������������������������������������������������� 203
Using DefaultPointcutAdvisor������������������������������������������������������������������������������������������������������������� 205
Using DynamicMethodMatcherPointcut��������������������������������������������������������������������������������������������� 208
Using Simple Name Matching������������������������������������������������������������������������������������������������������������ 211
Creating Pointcuts with Regular Expressions������������������������������������������������������������������������������������� 214
Creating Pointcuts with AspectJ Pointcut Expression������������������������������������������������������������������������ 215
Creating Annotation Matching Pointcuts�������������������������������������������������������������������������������������������� 216
Understanding Proxies������������������������������������������������������������������������������������������������� 218
Using JDK Dynamic Proxies���������������������������������������������������������������������������������������������������������������� 219
Using CGLIB Proxies��������������������������������������������������������������������������������������������������������������������������� 219
ix
■ Table of Contents
Comparing Proxy Performance����������������������������������������������������������������������������������������������������������� 221
Choosing a Proxy to Use��������������������������������������������������������������������������������������������������������������������� 225
Advanced Use of Pointcuts������������������������������������������������������������������������������������������� 225
Using Control Flow Pointcuts�������������������������������������������������������������������������������������������������������������� 225
Using a Composable Pointcut������������������������������������������������������������������������������������������������������������� 228
Composition and the Pointcut Interface��������������������������������������������������������������������������������������������� 232
Pointcut Summary������������������������������������������������������������������������������������������������������������������������������ 232
Getting Started with Introductions������������������������������������������������������������������������������� 232
Introduction Basics����������������������������������������������������������������������������������������������������������������������������� 233
Object Modification Detection with Introductions������������������������������������������������������������������������������ 235
Creating an Advisor���������������������������������������������������������������������������������������������������������������������������� 238
Putting It All Together������������������������������������������������������������������������������������������������������������������������� 238
Introduction Summary������������������������������������������������������������������������������������������������������������������������ 240
Framework Services for AOP���������������������������������������������������������������������������������������� 241
Configuring AOP Declaratively������������������������������������������������������������������������������������������������������������ 241
Using ProxyFactoryBean��������������������������������������������������������������������������������������������������������������������� 241
Using ProxyFactoryBean for Introductions����������������������������������������������������������������������������������������� 245
ProxyFactoryBean Summary�������������������������������������������������������������������������������������������������������������� 246
Using @AspectJ-Style Annotations������������������������������������������������������������������������������ 247
Declarative Before Advice with AspectJ Annotations������������������������������������������������������������������������� 248
Declarative Around Advice with AspectJ annotations������������������������������������������������������������������������� 254
Declarative After Advice with AspectJ Annotations���������������������������������������������������������������������������� 257
Declarative Introductions with AspectJ Annotations�������������������������������������������������������������������������� 261
Aspect Instantiation Models��������������������������������������������������������������������������������������������������������������� 263
Spring Boot AOP����������������������������������������������������������������������������������������������������������� 267
Considerations for Declarative Spring AOP Configuration������������������������������������������������������������������ 269
Summary���������������������������������������������������������������������������������������������������������������������� 269
x
■ Table of Contents
■
■Chapter 6: Spring Data Access with JDBC�������������������������������������������������������� 271
Sample Data Model for Example Code������������������������������������������������������������������������� 272
Exploring the JDBC Infrastructure�������������������������������������������������������������������������������� 277
Spring JDBC Infrastructure������������������������������������������������������������������������������������������ 283
Overview and Used Packages������������������������������������������������������������������������������������������������������������ 283
Database Connections and DataSources�������������������������������������������������������������������������������������������� 284
Embedded Database Support������������������������������������������������������������������������������������������������������������� 288
Using DataSources in DAO Classes���������������������������������������������������������������������������������������������������� 289
Exception Handling����������������������������������������������������������������������������������������������������������������������������� 291
The JdbcTemplate Class��������������������������������������������������������������������������������������������������������������������� 293
Spring Classes That Model JDBC Operations������������������������������������������������������������������������������������� 302
Spring Data Project: JDBC Extensions������������������������������������������������������������������������������������������������ 319
Spring JDBC Testing Annotations������������������������������������������������������������������������������������������������������� 320
Introducing Testcontainers����������������������������������������������������������������������������������������������������������������� 325
Considerations for Using JDBC����������������������������������������������������������������������������������������������������������� 331
Spring Boot JDBC������������������������������������������������������������������������������������������������������������������������������� 332
Summary���������������������������������������������������������������������������������������������������������������������� 340
■
■Chapter 7: Spring with Hibernate���������������������������������������������������������������������� 341
Sample Data Model for Example Code������������������������������������������������������������������������� 342
Configuring Hibernate’s SessionFactory���������������������������������������������������������������������� 343
ORM Mapping Using Hibernate Annotations���������������������������������������������������������������� 348
Simple Mappings���������������������������������������������������������������������������������������������������������� 349
One-to-Many Mappings���������������������������������������������������������������������������������������������������������������������� 354
Many-to-Many Mappings������������������������������������������������������������������������������������������������������������������� 355
The Hibernate Session Interface�������������������������������������������������������������������������������������������������������� 356
Querying Data by Using the Hibernate Query Language���������������������������������������������� 357
Simple Querying with Lazy Fetching�������������������������������������������������������������������������������������������������� 357
Querying with Associations Fetching������������������������������������������������������������������������������������������������� 361
Inserting Data��������������������������������������������������������������������������������������������������������������� 365
Updating Data��������������������������������������������������������������������������������������������������������������� 369
xi
■ Table of Contents
Deleting Data���������������������������������������������������������������������������������������������������������������� 372
Executing SQL Native Queries�������������������������������������������������������������������������������������� 374
Calling Stored Functions with Hibernate���������������������������������������������������������������������� 375
Configuring Hibernate to Generate Tables from Entities���������������������������������������������� 376
Annotating Methods or Fields?������������������������������������������������������������������������������������ 380
Considerations When Using Hibernate������������������������������������������������������������������������� 382
Introducing jOOQ���������������������������������������������������������������������������������������������������������� 383
Summary���������������������������������������������������������������������������������������������������������������������� 397
■
■Chapter 8: Spring with JPA������������������������������������������������������������������������������� 399
Introducing JPA 3.1������������������������������������������������������������������������������������������������������ 400
Sample Data Model for Example Code����������������������������������������������������������������������������������������������� 400
Configuring JPA’s EntityManagerFactory�������������������������������������������������������������������������������������������� 401
Using JPA Annotations for ORM Mapping������������������������������������������������������������������������������������������� 404
Performing Database Operations with JPA������������������������������������������������������������������ 407
Using the Java Persistence Query Language to Query Data�������������������������������������������������������������� 408
Querying with Untyped Results���������������������������������������������������������������������������������������������������������� 417
Querying for a Custom Result Type with a Constructor Expression���������������������������������������������������� 420
Inserting Data������������������������������������������������������������������������������������������������������������������������������������� 422
Updating Data������������������������������������������������������������������������������������������������������������������������������������� 424
Deleting Data�������������������������������������������������������������������������������������������������������������������������������������� 426
Using a Native Query���������������������������������������������������������������������������������������������������� 427
Using a Simple Native Query�������������������������������������������������������������������������������������������������������������� 427
Native Querying with SQL ResultSet Mapping������������������������������������������������������������������������������������ 428
Executing Stored Functions and Procedures�������������������������������������������������������������������������������������� 429
Using the JPA Criteria API for a Criteria Query������������������������������������������������������������� 430
Summary���������������������������������������������������������������������������������������������������������������������� 435
xii
■ Table of Contents
■
■Chapter 9: Spring Transaction Management����������������������������������������������������� 437
Exploring the Spring Transaction Abstraction Layer����������������������������������������������������� 438
Transaction Types������������������������������������������������������������������������������������������������������������������������������� 438
Implementations of the PlatformTransactionManager Interface���������������������������������� 440
Analyzing Transaction Properties��������������������������������������������������������������������������������� 441
The TransactionDefinition Interface���������������������������������������������������������������������������������������������������� 442
The TransactionStatus Interface��������������������������������������������������������������������������������������������������������� 444
Sample Data Model and Infrastructure for Example Code������������������������������������������� 445
Using Declarative Transactions����������������������������������������������������������������������������������������������������������� 449
Rolling Back Transactions������������������������������������������������������������������������������������������������������������������� 460
Using Programmatic Transactions������������������������������������������������������������������������������������������������������ 466
Considerations on Transaction Management�������������������������������������������������������������������������������������� 469
Transactional Configuration with Spring Boot�������������������������������������������������������������� 470
Transactional Tests����������������������������������������������������������������������������������������������������������������������������� 475
Considerations on Transaction Management�������������������������������������������������������������������������������������� 476
Summary���������������������������������������������������������������������������������������������������������������������� 477
■
■Chapter 10: Spring Data with SQL and NoSQL Databases��������������������������������� 479
Introducing Spring Data JPA���������������������������������������������������������������������������������������� 480
Using Spring Data JPA Repository Abstraction for Database Operations������������������������������������������� 481
Using JpaRepository��������������������������������������������������������������������������������������������������������������������������� 489
Spring Data JPA with Custom Queries������������������������������������������������������������������������������������������������ 490
Projection Queries������������������������������������������������������������������������������������������������������������������������������ 496
Keeping Track of Changes on the Entity Class������������������������������������������������������������� 497
Keeping Entity Versions by Using Hibernate Envers����������������������������������������������������� 504
Adding Tables for Entity Versioning���������������������������������������������������������������������������������������������������� 506
Configuring EntityManagerFactory for Entity Versioning�������������������������������������������������������������������� 507
Enabling Entity Versioning and History Retrieval���������������������������������������������������������� 510
Custom Implementations for Spring Data Repositories���������������������������������������������������������������������� 511
Spring Boot Data JPA��������������������������������������������������������������������������������������������������� 516
Considerations Using Spring Data JPA����������������������������������������������������������������������������������������������� 523
xiii
■ Table of Contents
Spring Data with MongoDB������������������������������������������������������������������������������������������ 524
MongoDB Concepts���������������������������������������������������������������������������������������������������������������������������� 525
Considerations Using Spring Data�������������������������������������������������������������������������������� 530
Summary���������������������������������������������������������������������������������������������������������������������� 530
■
■Chapter 11: Validation, Formatting, and Type Conversion��������������������������������� 531
Spring Type Conversion System����������������������������������������������������������������������������������� 531
Conversion from a String Using PropertyEditors�������������������������������������������������������������������������������� 532
Introducing Spring Type Conversion����������������������������������������������������������������������������� 536
Implementing a Custom Converter����������������������������������������������������������������������������������������������������� 536
Converting Between Arbitrary Types��������������������������������������������������������������������������������������������������� 537
Field Formatting in Spring�������������������������������������������������������������������������������������������� 540
Implementing a Custom Formatter����������������������������������������������������������������������������������������������������� 540
Validation in Spring������������������������������������������������������������������������������������������������������ 544
Using the Spring Validator Interface��������������������������������������������������������������������������������������������������� 545
Using JSR-349 Bean Validation������������������������������������������������������������������������������������ 552
Dependencies������������������������������������������������������������������������������������������������������������������������������������� 552
Defining Validation Constraints on Domain Object Properties������������������������������������������������������������ 553
Configuring Bean Validation Support in Spring����������������������������������������������������������������������������������� 554
Creating a Custom Validator��������������������������������������������������������������������������������������������������������������� 557
Using AssertTrue for Custom Validation���������������������������������������������������������������������������������������������� 559
Deciding Which Validation API to Use������������������������������������������������������������������������������������������������� 561
Configuring Validation in a Spring Boot Application��������������������������������������������������������������������������� 561
Summary���������������������������������������������������������������������������������������������������������������������� 564
■
■Chapter 12: Task Scheduling����������������������������������������������������������������������������� 565
About Tasks������������������������������������������������������������������������������������������������������������������ 565
Task Executing in Java and Kotlin�������������������������������������������������������������������������������� 566
Task Executing in Spring���������������������������������������������������������������������������������������������� 571
Task Scheduling in Spring�������������������������������������������������������������������������������������������� 573
xiv
■ Table of Contents
Introducing the Spring TaskScheduler Abstraction����������������������������������������������������������������������������� 574
Exploring a Sample Task��������������������������������������������������������������������������������������������������������������������� 575
Asynchronous Task Execution in Spring��������������������������������������������������������������������������������������������� 583
Summary���������������������������������������������������������������������������������������������������������������������� 590
■
■Chapter 13: Spring Remoting���������������������������������������������������������������������������� 591
Communication Using HTTP����������������������������������������������������������������������������������������� 592
Introducing Spring Data REST������������������������������������������������������������������������������������������������������������ 593
Using JMS in Spring����������������������������������������������������������������������������������������������������� 608
Working with Apache ActiveMQ Artemis��������������������������������������������������������������������������������������������� 609
Using Spring for Apache Kafka������������������������������������������������������������������������������������� 616
Summary���������������������������������������������������������������������������������������������������������������������� 629
■
■Chapter 14: Spring MVC������������������������������������������������������������������������������������ 631
Setting Up the Data and Lower Level Layers��������������������������������������������������������������� 632
Introducing Spring MVC����������������������������������������������������������������������������������������������� 636
Introducing MVC��������������������������������������������������������������������������������������������������������������������������������� 636
Spring MVC Additions������������������������������������������������������������������������������������������������������������������������� 637
Enabling Internationalization (i18n)���������������������������������������������������������������������������������������������������� 654
Using Theming and Templating���������������������������������������������������������������������������������������������������������� 657
Implementing More Complex Views��������������������������������������������������������������������������������������������������� 661
Enabling JSR-349 (Bean Validation)��������������������������������������������������������������������������������������������������� 681
Exception Handling����������������������������������������������������������������������������������������������������������������������������� 685
Switching to Spring Boot�������������������������������������������������������������������������������������������������������������������� 690
Summary���������������������������������������������������������������������������������������������������������������������� 698
■
■Chapter 15: Spring REST Support���������������������������������������������������������������������� 699
Introducing RESTful Web Services������������������������������������������������������������������������������� 699
Using Spring MVC to Expose RESTful Web Services��������������������������������������������������������������������������� 700
Implementing SingerController����������������������������������������������������������������������������������������������������������� 702
Testing the RESTful-WS Application��������������������������������������������������������������������������������������������������� 708
REST Exception Handling Using ResponseEntity<T>������������������������������������������������������������������������� 715
REST Exception Handling Using @RestControllerAdvice�������������������������������������������������������������������� 720
xv
■ Table of Contents
RESTful-WS with Spring Boot�������������������������������������������������������������������������������������� 724
Summary���������������������������������������������������������������������������������������������������������������������� 726
■
■Chapter 16: Spring Native and Other Goodies��������������������������������������������������� 727
Spring Native Images��������������������������������������������������������������������������������������������������� 728
The Spring Application������������������������������������������������������������������������������������������������������������������������ 730
Spring for GraphQL������������������������������������������������������������������������������������������������������� 740
Summary���������������������������������������������������������������������������������������������������������������������� 759
■
■Chapter 17: Securing Spring Web Applications������������������������������������������������� 761
Configuring Spring Security - The Classic Way������������������������������������������������������������ 762
JDBC Authentication��������������������������������������������������������������������������������������������������������������������������� 787
Testing Secured Web Applications������������������������������������������������������������������������������������������������������ 791
Configuring Spring Security: The Spring Boot Way������������������������������������������������������ 796
Summary���������������������������������������������������������������������������������������������������������������������� 798
■
■Chapter 18: Monitoring Spring Applications����������������������������������������������������� 799
JMX Support in Spring������������������������������������������������������������������������������������������������� 800
Exporting a Spring Bean to JMX��������������������������������������������������������������������������������������������������������� 800
Using VisualVM for JMX Monitoring���������������������������������������������������������������������������������������������������� 802
Monitoring Hibernate Statistics���������������������������������������������������������������������������������������������������������� 806
JMX with Spring Boot��������������������������������������������������������������������������������������������������� 809
Monitoring Applications with Spring Boot Actuator������������������������������������������������������ 810
Using Spring Boot Actuator with Micrometer������������������������������������������������������������������������������������� 817
Summary���������������������������������������������������������������������������������������������������������������������� 828
■
■Chapter 19: Spring WebSocket Support������������������������������������������������������������ 829
Introducing WebSocket������������������������������������������������������������������������������������������������ 829
Using WebSocket with Spring�������������������������������������������������������������������������������������� 830
Using the WebSocket API��������������������������������������������������������������������������������������������� 831
Using SockJS��������������������������������������������������������������������������������������������������������������� 839
xvi
■ Table of Contents
Sending Messages with STOMP����������������������������������������������������������������������������������� 843
Spring Boot Equivalent Application����������������������������������������������������������������������������������������������������� 852
Summary���������������������������������������������������������������������������������������������������������������������� 853
■
■Chapter 20: Reactive Spring������������������������������������������������������������������������������ 855
Introduction to Reactive Programming in Spring��������������������������������������������������������� 856
Introducing Spring WebFlux����������������������������������������������������������������������������������������� 861
Spring Boot Configuration for a Reactive Application������������������������������������������������������������������������� 864
Reactive Repository and Database����������������������������������������������������������������������������������������������������� 866
Reactive Services������������������������������������������������������������������������������������������������������������������������������� 873
Reactive Controllers��������������������������������������������������������������������������������������������������������������������������� 881
Handler Classes and Functional Endpoints���������������������������������������������������������������������������������������� 883
Reactive Error Handling���������������������������������������������������������������������������������������������������������������������� 891
Testing Reactive Endpoints with WebTestClient��������������������������������������������������������������������������������� 893
Reactive Web Layer���������������������������������������������������������������������������������������������������������������������������� 896
Handler Functions Validation�������������������������������������������������������������������������������������������������������������� 903
Summary���������������������������������������������������������������������������������������������������������������������� 913
Index��������������������������������������������������������������������������������������������������������������������� 915
xvii
About the Authors
Peter Späth graduated in 2002 as a physicist and soon afterward became an IT consultant, mainly for
Java-related projects. In 2016, he decided to concentrate on writing books on various aspects, but with a
main focus on software development. With two books about graphics and sound processing, three books
on Android app development, and a couple of books about Java, Jakarta EE, and Kotlin, Späth continues his
effort in writing software development–related literature.
Iuliana Cosmina is a Spring Certified Web Developer and a Spring Certified Core Spring Professional.
She is a Spring certified expert, as defined by Pivotal, the makers of Spring Framework, Spring Boot, and
other tools. Cosmina has authored books with Apress on Core Spring certification and Spring Certified web
development. She is a Lead Engineer at Cloudsoft, located in Edinburgh, Scotland, and is an active coder
and software contributor on Apache Brooklyn, GitHub, StackOverflow, and more.
Rob Harrop is a software consultant specializing in delivering high-performance, highly scalable enterprise
applications. He is an experienced architect with a particular flair for understanding and solving complex
design issues. With a thorough knowledge of both Java and.NET, Harrop has successfully deployed projects
across both platforms. He also has extensive experience across a variety of sectors, retail and government
in particular. Harrop is the author of five books, including the book you are currently reading, not at its sixth
edition, a widely acclaimed, comprehensive resource on the Spring Framework.
Chris Schaefer is a principle software developer for Spring projects at Pivotal, the makers of Spring
Framework, Boot, and other Spring tools.
xix
About the Technical Reviewer
Massimo Nardone has more than 25 years of experience in security, web/
mobile development, cloud, and IT architecture. His true IT passions are
security and Android. He has been programming and teaching how to
program with Android, Perl, PHP, Java, VB, Python, C/C++, and MySQL
for more than 20 years. He holds a master of science degree in computing
science from the University of Salerno, Italy. He has worked as a CISO,
CSO, security executive, IoT executive, project manager, software engineer,
research engineer, chief security architect, PCI/SCADA auditor, and senior
lead IT security/cloud/SCADA architect for many years. His technical
skills include security, Android, cloud, Java, MySQL, Drupal, Cobol, Perl,
web and mobile development, MongoDB, D3, Joomla, Couchbase, C/
C++, WebGL, Python, Pro Rails, Django CMS, Jekyll, Scratch, and more. He
worked as visiting lecturer and supervisor for exercises at the Networking
Laboratory of the Helsinki University of Technology (Aalto University). He
holds four international patents (PKI, SIP, SAML, and Proxy areas). He is currently working for Cognizant as
head of cyber security and CISO to help both internally and externally with clients in areas of information
and cyber security, like strategy, planning, processes, policies, procedures, governance, awareness, and so
forth. In June 2017 he became a permanent member of the ISACA Finland Board.
Massimo has reviewed more than 45 IT books for different publishing companies and is the co-author
of Pro Spring Security: Securing Spring Framework 5 and Boot 2-based Java Applications (Apress, 2019),
Beginning EJB in Java EE 8 (Apress, 2018), Pro JPA 2 in Java EE 8 (Apress, 2018), and Pro Android Games
(Apress, 2015).
xxi
Introduction
Covering version 6 of the Spring Framework, this book is the most comprehensive Spring reference and
practical guide available for harnessing the power of this leading enterprise Java application development
framework.
This edition covers core Spring and its integration with other leading Java technologies, such as
Hibernate, JPA 3, Thymeleaf, Kafka, GraphQL, and WebFlux, using Kotlin as a programming language. The
focus of the book is on using Kotlin configuration classes, lambda expressions, Spring Boot, and reactive
programming. We share our insights and real-world experiences with enterprise application development,
including remoting, transactions, web and presentation tiers, and much more.
With Pro Spring 6 with Kotlin, you’ll learn how to do the following:
• Use inversion of control (IoC) and dependency injection (DI)
• Discover what is new in Spring Framework 6
• Build Spring-based web applications using Spring MVC and WebSocket
• Build Spring web reactive applications with Spring WebFlux
• Test Spring applications using Junit 5
• Genuinely use Kotlin constructs
• Use Spring Boot to an advanced level to get any kind of Spring application up and
running in no time
• Package your Spring Native application into a Docker image with Cloud Native
Buildpacks
There is a multimodule project associated with this book, configured using Gradle 8. The project is
available on the Apress official repository: https://github.com/apress/pro-spring-6-kotlin. The project
can be built immediately after cloning according to the instructions in its README.adoc file. If you do not
have Gradle installed locally, you can rely on IntelliJ IDEA to download it and use it to build your project by
using the Gradle Wrapper (https://docs.gradle.org/current/userguide/gradle_wrapper.html).
As the book was being written, new versions of Spring 6 and Spring Boot 3 were released, a new version
of IntelliJ IDEA was released, and new versions of Gradle and other technologies used in the book were
updated. We upgraded to the new versions to provide the most recent information and keep this book
synchronized with the official documentation. Several reviewers have checked the book for technical
accuracy, but if you notice any inconsistencies, please send an email to [email protected] and errata will
be created.
You can access the example source code for this book at https://github.com/apress/pro-spring-6-
kotlin. It will be maintained, synchronized with new versions of the technologies, and enriched based on
the recommendations of the developers using it to learn Spring.
We truly hope you will enjoy using this book to learn Spring as much as we enjoyed writing it.
xxiii
CHAPTER 1
Introducing Spring
Every year there are tweets and blog posts announcing that Java is no longer relevant and there is a shiny
new technology taking its place. And every year these turn out to be just industry rumors. Java is an ever-
evolving technology that has been in the top 10 of most used technologies by companies to build software
solutions since its initial release in 1995. A lot of libraries and frameworks have been built on Java, some of
them available to developers as open source projects, others safely locked away in a private cloud because of
the sensitive information they manage(e.g., banking applications).
One of the most popular frameworks written in Java is the Spring Framework. The first version of Spring
was released in October 2002 and consisted of a small core with an inversion of control container that was
easy to configure and use. Over the years the Spring Framework has become the main replacement of Java
Enterprise Edition (JEE) servers and has grown into a full-blown technology made up of many distinct
projects, each with its own purpose. Whether you want to build microservices applications, build classical
Enterprise Resource Planning (ERPs), or compile your app into a native image to run on GraalVM, Spring
has a project for that.
Throughout this book, you will see many applications of different open source technologies, all of which
are unified under the Spring Framework. When working with Spring, application developers can use a large
variety of open source tools, without needing to write reams of code and without coupling their application
too closely to any particular tool.
This is an introductory chapter that covers important details about this book, introduces you to the
Spring Framework, explains why understanding Spring in depth is so useful for developers, and describes
how powerful Spring can be when used correctly. If you are already familiar with Spring, you might want to
skip this chapter and proceed straight to Chapter 2.
About This Book
Covering version 6 of the Spring Framework, this book is the most comprehensive Spring reference and
practical guide available for harnessing the power of this leading enterprise Java application development
framework when using Kotlin as a programming language.
This edition covers core Spring and its integration with other leading Java technologies, such
as Hibernate, JPA 2, Thymeleaf, Apache Kafka, and others. The focus of the book is on using Kotlin
as a programming language for Spring, Java/Kotlin configuration classes, Spring Boot, and reactive
programming. We share our insights and real-world experiences with enterprise application development,
including remoting, transactions, the web and presentation tiers, and much more.
With Pro Spring 6 with Kotlin, you’ll learn how to do the following:
• Use and understand inversion of control (IoC) and dependency injection (DI)
• Discover what’s new in Spring Framework 6
• Build Spring-based web applications using Spring MVC and WebSocket
© Peter Späth, Iuliana Cosmina, Rob Harrop, Chris Schaefer 2023 1
P. Späth et al., Pro Spring 6 with Kotlin, https://doi.org/10.1007/978-1-4842-9557-1_1
Chapter 1 ■ Introducing Spring
• Test Spring applications using Junit 5 and other Java/Kotlin testing libraries
• Utilize the capabilities of Kotlin 1.8
• Use Spring Boot to an advanced level, but learn how to do without it as well
• Secure Spring applications
• Monitor Spring applications
• Write reactive applications using Spring
• Build your Spring application and run it on a compact native image with
Spring Native
To make sure the focus of the book is on Spring and Kotlin, instructions on how to install additional
technologies mentioned in the book are provided in documentation files for each project in the book
repository. This, of course, will be pointed out to you in the book when necessary.
What Is Spring?
Perhaps one the hardest parts of explaining Spring is classifying exactly what it is. Spring was described
since the beginning as a lightweight framework for building Java applications, but that statement brings up
two interesting points:
• You can use Spring to build any application in Java/Kotlin (for example, stand-alone,
web, mobile, or JEE applications), unlike many other frameworks (such as Apache
Struts, which is limited to web applications).
• The lightweight part of the description is not related to the number of classes or the
size of the distribution but rather defines the principle of the Spring philosophy as a
whole—that is, minimal impact. Spring is lightweight in the sense that you have to
make few, if any, changes to your application code to gain the benefits of the Spring
Core, and should you choose to stop using Spring at any point, you will find that
doing so is quite simple.
Notice that we qualified that last statement to refer to the Spring Core only—many of the extra Spring
components, such as data access, require a much closer coupling to the Spring Framework. However, the
benefits of this coupling are quite clear, and throughout the book we present techniques for minimizing the
impact this has on your application. Also, if coupling your code to a framework brings with it development
speed and better dependency management, which reduces the number of build failures during upgrades,
isn’t the price worth it? Also, with Spring Native, Spring applications now can be run on native images(e.g.,
GraalVM) that provide various advantages, such as an instant startup and reduced memory consumption, so
gone are the days when JavaScript or .NET developers could diss on Spring by saying it is heavyweight.
Evolution of the Spring Framework
The Spring Framework originated from the book Expert One-on-One: J2EE Design and Development by
Rod Johnson (Wrox, 2002). In his book, Johnson presented his own framework, called the Interface 21
Framework, which he developed to use in his own applications. Released into the open source world, this
framework formed the foundation of the Spring Framework as we know it today. Over the last decade, the
Spring Framework has grown dramatically in core functionality, associated projects, and community support.
Spring 0.9 started as a community project made of a few core modules and without an official documentation.
VMware took it over and started its transition from XML to Java Config (using annotations) in version 2.5.
2
Chapter 1 ■ Introducing Spring
In 2012, Pivotal Software split from VMware and took over Spring and grew it from a framework to a
collection of projects. There were two major releases under Pivotal: 4.x, which was the first version to fully
support Java 8, and 5.x, which dropped support for XML configurations completely.
Together with Spring 4.x, Spring Boot was released and became one of the most used Spring projects.
Spring Boot takes an opinionated view of building Spring applications. Developers at Pivotal have identified
a few types of applications being built and have created templates for them using a set of default component
dependencies and automatic configuration of components. These application templates are modeled by
a set of Spring Boot starter projects. For example, if you would want to create a Spring web application,
just add the spring-boot-starter-web dependency to your project and you have a minimal, Spring web
application with default configurations. This is possible because Spring Boot has some cool features such
as embedded application server (Jetty/Tomcat), a command-line interface based on Groovy, and health/
metrics monitoring.
Spring Boot provides the ability to develop applications quickly, based on a stable, curated set
of dependencies with all the required Spring Framework components configured correctly. This is
good because it reduces the developer setup effort. However, this also reduces the need for a deeper
understanding of the Spring Framework, which might trick developers into a false sense of confidence in
their knowledge and understanding of the Spring Framework.
■■Note In the previous edition of this book, this chapter contained a list with all the Spring versions ever
release and their most important features. Since that information is available publicly on the internet, a decision
was made to skip that to reduce the book in size and also dedicate that space to something more interesting
such as Project Reactor1 and Spring Native2.
At the end of 2019, VMware bought Pivotal Software and took over Spring again, so at the end of 2021,
Spring 6.x will be out, the first major Spring Release under VMware. At the time this chapter is being written,
the first milestone has already been released and the most important thing about it is that the codebase has
been upgraded to JDK 17. This version is considered the first JDK3 produced by Oracle that provides enough
performance and security improvements for a migration from 1.8 to be worth it for companies that are (still)
reluctant to do so.
A lot of deprecated classes and packages that provided support for deprecated third-party technologies
have been removed and existing classes have been updated to work with newer versions of certain
technologies (for example: Tomcat 10, Jetty 11, or Undertow 2.2.14)
Spring Projects
The current Spring Projects are listed on the official Spring site4, but for your convenience here is a list of
them with a short summary of each.
• Spring Boot consists of a set of libraries (called starters) that provide default
application templates that can be customized easily to quickly develop multiple
types of stand-alone, production-grade Spring-based applications.
1
https://projectreactor.io
2
https://docs.spring.io/spring-native/docs/current/reference/htmlsingle
3
https://blogs.oracle.com/javamagazine/post/its-time-to-move-your-applications-to-
java-17-heres-why-and-heres-how
4
https://spring.io/projects
3
Chapter 1 ■ Introducing Spring
• Spring Framework consists of a set of libraries that provide support for dependency
injection, transaction management, data access, messaging, and other core
functionalities for any type of application. The Spring Framework now includes the
Spring WebFlux framework that represents the Spring reactive-stack designed to
build fully non-blocking, with back-pressure support reactive applications on servers
such as Netty, Undertow, and Servlet 3.1+ containers.
• Spring Data consists of a set of libraries that provide a consistent programming
model for accessing various databases both relational (e.g., MySQL and Oracle) and
nonrelational (e.g., MongoDB and CouchBase). Support for in-memory databases
(e.g., H2 and MongoDB) is included, which is pretty useful for testing applications
without the drag of a concrete database. Also, Spring Data R2DBC makes it easy to
access reactive databases.
• Spring Security provides the ability to secure applications easily, with a simple
model for authentication and authorization.
• Spring Cloud provides a set of common tools for writing microservices applications
destined to run in distributed systems.
• Spring Cloud Data Flow provides a set of common tools for streaming and
batch processing of data between microservices running in Cloud Foundry and
Kubernetes.
• Spring Integration provides support for building Spring applications that make
use of lightweight messaging and integrate with external systems via declarative
adapters.
• Spring Session provides an API and implementations for managing a user’s session
information.
• Spring HATEOAS provides some APIs to ease creating REST representations that
follow the HATEOAS principle when working with Spring and especially Spring
MVC. Some developers/architects consider that the hypermedia5 pollutes the
REST data and a better solution is to use Swagger6 to expose (and document) an
application’s API or Spring REST Docs.
• Spring for GraphQL provides the tools to build Spring applications on GraphQL
Java. GraphQL7 is a query language to retrieve data from a server.
• Spring REST Docs provides the tools to expose and document a Spring
application’s API.
• Spring Batch is a framework that provides the tools to build lightweight and robust
Spring applications that handle immense volumes of data.
• Spring AMQP provides the tools to build AMQP-based messaging solutions
using Spring.
• Spring CredHub is part of the Spring Cloud project family and provides client-side
support for storing, retrieving, and deleting credentials from a CredHub server
running in a CloudFoundry platform.
5
https://en.wikipedia.org/wiki/HATEOAS
6
https://swagger.io
7
https://www.graphql-java.com
4
Chapter 1 ■ Introducing Spring
• Spring Flo is a JavaScript library that offers a basic embeddable HTML5 visual
builder for pipelines and simple graphs. Spring Cloud Data Flow is an extension of
this project.
• Spring for Apache Kafka provides tools for building Kafka-based messaging
solutions using Spring.
• Spring LDAP is a library to simplify LDAP programming in Java, built on the same
principles as Spring JDBC.
• Spring Shell provides the tools to build a full-featured shell (aka command line)
application by depending on the Spring Shell jars and adding their own commands
(which come as methods on Spring beans).
• Spring Statemachine is a framework for application developers to use state machine
concepts with Spring applications.
• Spring Vault provides familiar Spring abstractions and client-side support
for accessing, storing, and revoking secrets. It offers both low-level and high-
level abstractions for interacting with HashiCorp’s Vault8, freeing the user from
infrastructural concerns.
• Spring Web Flow extends Spring MVC to provide the tools for implementing the
"flows" of a web application. A flow encapsulates a sequence of steps that guide a
user through the execution of some business task. It spans multiple HTTP requests,
has state, deals with transactional data, is reusable, and may be dynamic and long-
running in nature.
• Spring Web Services (Spring-WS) is a product of the Spring community focused
on creating document-driven web services. Spring Web Services aims to facilitate
contract-first SOAP service development, allowing for the creation of flexible web
services using one of the many ways to manipulate XML payloads.
• Spring Native (currently still considered experimental, but quicky being adopted
in the industry) provides support for compiling Spring applications to native
executables using the GraalVM native-image compiler.
• Spring Initializr (not actually a project, but good to know), available at https://
start.spring.io, provides a quick start for creating custom Spring Boot projects
completely configurable according to the developer’s necessities: programming
language, build tool, Spring Boot version, and project requirements (database
access, web access, event messaging, security, etc.).
There are a few projects that over the years have lost the developer community’s interest (e.g., Spring
Scala) and are now in a state called in the attic. If developers’ interest continues to drop, these projects will
be archived and others will surely take their place. If you want to keep up to date with the Spring projects
ecosystem, check https://spring.io/projects from time to time.
That’s enough about Spring projects to pique your interest; let’s talk more in depth about Spring.
8
https://www.vaultproject.io
5
Chapter 1 ■ Introducing Spring
Inverting Control or Injecting Dependencies?
The core of the Spring Framework is based on the principle of inversion of control (IoC). IoC is a technique
that externalizes the creation and management of component dependencies. The action performed by any
program (not only Java) is the result of interaction between its interdependent components, usually named
objects. Explaining IoC also requires an explanation of dependency injection (DI), a concept that describes
how dependent objects are connected at runtime by an external party. Take a look at Figure 1-1, which
depicts two types of relationships between objects and how those objects “meet” each other.
Figure 1-1. Object relationships and how they “meet”
Object A needs an object of type B to perform its functions, thus A depends on B. The ways these two
objects get to interact shown in Figure 1-1 can be explained as follows:
• Composition: Object A directly creates object B. This ties them together, and basically
object B exists as long as object A exists. This situation is depicted in section (1) in
Figure 1-1.
• Aggregation: Object A itself retrieves object B that already exists. This ties them
together as well, and object B must exist as long as object A needs it to. Also, object
A must include the logic to be able to retrieve object B. This situation is depicted in
section (2) in Figure 1-1.
Dependency injection allows severing that tie, as depicted in section (3) in Figure 1-1, by using an
external party to provide object B to object A, which is still aggregation, but with no direct ties and a twist.
Inversion of control is a design principle in which generic reusable components are used to control
the execution of problem-specific code, as in retrieving dependencies. Thus, you can say that Spring is
a dependency handler used to perform dependency injection, and it was designed following the IoC
principle, also known as the Hollywood Principle: Don’t call us, we’ll call you.
Spring’s DI implementation is based on two core Java/Kotlin concepts: JavaBeans (also known as
POJOs, plain old Java objects) and interfaces. When you use Spring as the DI provider, you gain the flexibility
of defining dependency configuration within your applications in different ways. Up to Spring 2.5, XML
was the only way to do it. Spring 2.5 introduced a few annotations to support configuration within the
code. Spring 3 introduced Java/Kotlin configuration classes, which became the norm, although XML is
still supported in case you really need it. Starting with version 4, Spring provides support for Groovy-based
configurations. This means that Groovy classes can be legitimate Spring beans.
6
Chapter 1 ■ Introducing Spring
JavaBeans (POJOs) provide a standard mechanism for creating Java/Kotlin resources that are
configurable in a number of ways, such as constructors and setter methods. In Chapter 3, you will see how
Spring uses the JavaBean specification to form the core of its DI configuration model; in fact, any Spring-
managed resource is referred to as a bean. If you are unfamiliar with JavaBeans, we present a quick primer at
the beginning of Chapter 3.
Interfaces and DI are technologies that are mutually beneficial. Clearly designing and coding
an application to interfaces makes for a flexible application, but the complexity of wiring together an
application designed using interfaces is quite high and places an additional coding burden on developers.
By using DI, you reduce to almost zero the amount of code you need to use an interface-based design in your
application. Likewise, by using interfaces, you can get the most out of DI because your beans can utilize any
interface implementation to satisfy their dependency. The use of interfaces also allows Spring to utilize JDK
dynamic proxies (the Proxy pattern) to provide powerful concepts such as aspect-oriented programming
(AOP) for crosscutting concerns.
In the context of DI, Spring acts more like a container than a framework—providing instances of your
application classes with all the dependencies they need—but it does so in a much less intrusive way. Using
Spring for DI relies on nothing more than following the JavaBeans naming conventions within your classes—
there are no special classes from which to inherit or proprietary naming schemes to follow. If anything, the
only change you make in an application that uses DI is to expose more properties on your JavaBeans, thus
allowing more dependencies to be injected at runtime.
Evolution of Dependency Injection
In the past few years, thanks to the popularity gained by Spring and other DI frameworks, DI has gained wide
acceptance among Java developer communities. At the same time, developers were convinced that using
DI was a best practice in application development, and the benefits of using DI were also well understood.
The popularity of DI was acknowledged when the Java Community Process (JCP) adopted JSR-330
(“Dependency Injection for Java”) in 2009. JSR-330 had become a formal Java specification request, and as
you might expect, one of the specification leads was Rod Johnson—the founder of the Spring Framework.
In JEE 6, JSR-330 became one of the included specifications of the entire technology stack. In the
meantime, the EJB architecture (starting from version 3.0) was also revamped dramatically; it adopted the DI
model in order to ease the development of various Enterprise JavaBeans apps.
Although we leave the full discussion of DI until Chapter 3, it is worth taking a look at the benefits of
using DI rather than a more traditional approach.
• Reduced glue code: DI dramatically reduces the amount of code you have to
write to glue the components of your application together. Code required to glue
components together is often trivial, but repetitive, and a lot of it can increase
the overall complexity of your solution. It gets trickier when you need to look up
dependencies in a Java Naming and Directory Interface (JNDI) repository or when
the dependencies cannot be invoked directly, as is the case with remote resources. In
these cases, DI can really simplify the glue code by providing automatic JNDI lookup
and automatic proxying of remote resources.
• Simplified application configuration: A variety of ways can be used to configure
classes that are injectable to other classes. You can use the same technique to
express the dependency requirements to the “injector” for injecting the appropriate
bean instance or property. In addition, DI makes it much simpler to swap one
implementation of a dependency for another. For example, using DI, a DAO
component that performs data operations against a PostgreSQL database can easily
be switched to perform the same operations on an Oracle database via configuration
(as you will see in Chapter 6).
7
Chapter 1 ■ Introducing Spring
• Ability to manage common dependencies in a single repository: Using a traditional
approach to dependency management of common services—for example, data
source connection, transaction, and remote services—you create instances (or lookup
from some factory classes) of your dependencies where they are needed (within the
dependent class). This causes the dependencies to spread across the classes in your
application, and changing them can prove problematic. When you use DI, all the
information about those common dependencies is contained in a single repository,
making the management of dependencies much simpler and less error-prone.
• Improved testability: Classes designed for DI are easily testable because
dependencies can be replaced easily. For example, if you want to test a DAO
component, you can replace the concrete database with an in-memory database via
configuration. This has the benefit of your tests being executed faster but within an
appropriate context that mimics as much as possible a production environment. This
mechanism can be extended for testing any tier of your application and is especially
useful for testing web components where you can create mock implementations of
HttpServletRequest and HttpServletResponse.
• Fostering of good application design: A typical injection-oriented application is
designed so that all major components are defined as interfaces, and then concrete
implementations of these interfaces are created and hooked together using the
DI container. This kind of design was possible in Java before the advent of DI and
DI-based containers such as Spring, but by using Spring, you get a whole host of DI
features for free, and you are able to concentrate on building your application logic,
not a framework to support it.
As you can see from this list, DI provides a lot of benefits for your application, but it is not without its
drawbacks. In particular, DI can make it difficult for someone not intimately familiar with the code to see
just what implementation of a particular dependency is being hooked into which objects. Typically, this is a
problem only when developers are inexperienced with DI. I’ve heard a lot of my colleagues in this situation
mentioning that Spring auto-magically injects beans, or complaining that they don’t understand where a
bean is coming from, or, worst of all asking “Why is Spring is not finding my bean?” After becoming more
experienced and following good DI coding practice (for example, putting all injectable classes within each
application layer into the same package), developers will be able to discover the whole picture easily. For the
most part, the massive benefits of DI far outweigh this small drawback, but you should consider this when
planning your application.
Beyond Dependency Injection
Spring Core alone, with its advanced DI capabilities, is a worthy tool, but where Spring really excels is in its
myriad of additional features, all elegantly designed and built using the principles of DI. Spring provides
features for all layers of an application, from helper application programming interfaces (APIs) for data
access right through to advanced Model-View-Controller (MVC) capabilities. What is great about these
features in Spring is that, although Spring often provides its own approach, you can easily integrate them
with other tools in Spring, making these tools first-class members of the Spring family.
The following list describes the most important Spring features and indicates the chapters in which they
are covered in this book:
• Aspect-oriented programming: AOP provides the ability to implement crosscutting
logic—that is, logic that applies to many parts of your application—in a single
place and to have that logic applied across your application automatically. Spring’s
approach to AOP, covered in Chapter 5, is to create dynamic proxies to the target
8
Chapter 1 ■ Introducing Spring
objects and weave the objects with the configured advice to execute the crosscutting
logic. By the nature of JDK dynamic proxies, target objects must implement an
interface declaring the method in which the AOP advice will be applied.
• Spring Expression Language: Expression Language (EL) is a technology to allow an
application to manipulate Java/Kotlin objects at runtime. However, the problem with
EL is that different technologies provide their own EL implementations and syntax.
For example, Java Server Pages (JSP) and Java Server Faces (JSF) both have their
own EL, and their syntax are different. To solve the problem, the Unified Expression
Language (EL) was created. Spring Expression Language (SpEL) was introduced
in Spring 3.0 and provides powerful features for evaluating expressions and for
accessing Java/Kotlin objects and Spring beans at runtime.
• Validation: Data managed by an application must abide by specific validation rules.
The ideal scenario is that the validation rules of the attributes within JavaBeans
containing business data can be applied in a consistent way, regardless of whether
the data manipulation request is initiated from the front end, a batch job, or remotely
(for example, via web services, RESTful web services, or remote procedure calls
[RPCs]). To address these concerns, Spring provides a built-in validation API by way
of the Validator interface. This interface provides a simple yet concise mechanism
that allows you to encapsulate your validation logic into a class responsible for
validating the target object. In addition to the target object, the validation method
takes an Errors object, which is used to collect any validation errors that may occur.
The topic of validation and all aspects of it are covered in detail in Chapter 11.
• Accessing data: Data access and persistence seem to be the most discussed topics in
the Java world. Spring provides excellent integration with a choice selection of data
access tools. In addition, Spring makes plain-vanilla JDBC a viable option for many
projects, with its simplified wrapper APIs around the standard API. Spring’s data
access module provides out-of-the-box support for JDBC (Chapter 6), Hibernate
(Chapter 7), JDO the JPA (Chapter 8), and various NoSQL databases (Chapter 10).
When using the Spring APIs to access data via any tool, you are able to take
advantage of Spring’s excellent transaction support. You’ll find a full discussion of
this in Chapter 9.
• Managing transactions: Spring provides an excellent abstraction layer for transaction
management, allowing for programmatic and declarative transaction control. By
using the Spring abstraction layer for transactions, you can make it simple to change
the underlying transaction protocol and resource managers. You can start with
simple, local, resource-specific transactions and move to global, multi-resource
transactions without having to change your code. Transactions are covered in full
detail in Chapter 9.
• Object mapping: Most applications need to integrate or provide services to other
applications. One common requirement is to exchange data with other systems,
either on a regular basis or in real time. In terms of data format, XML used to
be the most commonly used, but nowadays JSON and YAML have taken over,
mostly because the excellent support provided by the Jackson Project9. Starting
with Chapter 13, in which we discuss remotely accessing a Spring application for
business data in various formats, you will see how to use Spring’s object mapping
support in your application.
9
https://github.com/FasterXML/jackson
9
Chapter 1 ■ Introducing Spring
• Job scheduling support: Most nontrivial applications require some kind of scheduling
capability. Whether this is for sending updates to customers or performing
housekeeping tasks, the ability to schedule code to run at a predefined time is an
invaluable tool for developers. Spring provides scheduling support that can fulfill
most common scenarios. A task can be scheduled either for a fixed interval or by
using a Unix cron expression. On the other hand, for task execution and scheduling,
Spring integrates with other scheduling libraries as well. For example, in the
application server environment, Spring can delegate execution to the CommonJ
library that is used by many application servers. For job scheduling, Spring also
supports libraries including the JDK Timer API and Quartz, a commonly used open
source scheduling library. The scheduling support in Spring is covered in full in
Chapter 12.
• MVC in the web tier: Although Spring can be used in almost any setting, from
the desktop to the Web, it provides a rich array of classes to support the creation
of web-based applications. Using Spring, you have maximum flexibility when
you are choosing how to implement your web front end. For developing web
applications, the MVC pattern is the most popular practice. In recent versions,
Spring has gradually evolved from a simple web framework into a full-blown MVC
implementation. First, view support in Spring MVC is extensive. In addition to
standard support for JSP and Java Standard Tag Library (JSTL), which is greatly
bolstered by the Spring tag libraries, you can take advantage of fully integrated
support for Apache Velocity, FreeMarker, Thymeleaf, XSLT, React, and Mustache
templates. In addition, you will find a set of base view classes that make it simple to
add Microsoft Excel, PDF, and JasperReports output to your applications. Starting
with Chapter 15, we discuss developing web applications by using Spring MVC.
• Remoting support: Accessing or exposing remote components in Java, and later in
Kotlin, has never been the simplest of jobs. Using Spring, you can take advantage
of extensive support for a wide range of remoting techniques to quickly expose and
access remote services: JMS, Advanced Message Queuing Protocol (AMQP), and
REST. Accessing remote services nowadays more often than not involves real-time
streaming data, and applications must adapt to the data streams; this is where
Apache Kafka comes in handy. How Spring integrates with these technologies is
covered in Chapter 13, except REST, which is covered in Chapter 16.
• Simplified exception handling: One area where Spring really helps reduce the amount
of repetitive, boilerplate code you need to write is in exception handling. The core of
the Spring philosophy in this respect is that checked exceptions are overused in Java
and that a framework should not force you to catch any exception from which you
are unlikely to be able to recover—a point of view that we agree with wholeheartedly.
In reality, many frameworks are designed to reduce the impact of having to write
code to handle checked exceptions. However, many of these frameworks take the
approach of sticking with checked exceptions but artificially reducing the granularity
of the exception class hierarchy. One thing you will notice with Spring is that because
of the convenience afforded to the developer from using unchecked exceptions,
the exception hierarchy is remarkably granular. Throughout the book, you will see
examples in which the Spring exception-handling mechanisms can reduce the
amount of code you have to write and, at the same time, improve your ability to
identify, classify, and diagnose errors within your application.
10
Chapter 1 ■ Introducing Spring
• WebSocket support: Starting with Spring Framework 4.0, support for JSR-356 (“Java
API for WebSocket”) is available. WebSocket defines an API for creating a persistent
connection between a client and server, typically implemented in web browsers
and servers. WebSocket-style development opens the door for efficient, full-duplex
communication enabling real-time message exchanges for highly responsive
applications. Use of WebSocket support is detailed further in Chapter 19. The Spring
Framework provides a reactive WebSocket API that you can use to write client and
server-side applications that handle WebSocket messages, which is covered briefly in
Chapter 20.
• Reactive programming: Reactive programming describes a design paradigm
that relies on asynchronous programming logic to handle real-time updates to
otherwise static content. It provides an efficient means — the use of automated data
streams — to handle data updates to content whenever a user makes an inquiry.
The Spring team created its own reactive streams implementation, Project Reactor,
when the JDK Reactive support was delayed, so Spring could have a jump-start into
providing support for building reactive applications with Spring. How to develop
reactive Spring applications in covered in Chapter 20.
Kotlin has its own idea of reactive programming: Coroutines. In order to avoid confusion by mingling two
different technologies, we present only the Spring way in this book.
• Securing applications: In a world where almost any business transaction is done
over the Internet, securing data and ensuring access to it is no longer an option but
a requirement. The Spring Security project10, formerly known as the Acegi Security
System for Spring, is another important project within the Spring portfolio. Spring
Security provides comprehensive support for both web application and method-
level security. It tightly integrates with the Spring Framework and other commonly
used authentication mechanisms, such as HTTP basic authentication, form-based
login, X.509 certificate, OAuth2 and single sign-on (SSO) products (for example, CA
SiteMinder). It provides role-based access control (RBAC) to application resources,
and in applications with more-complicated security requirements (for example,
data segregations), it supports use of an access control list (ACL). Spring Security is
mostly used in securing web applications, which is covered in Chapter 17. Reactive
security is briefly touched upon in Chapter 20.
• Monitoring applications: An application made of multiple components should
have a setup that, after being put into production, ensures the smooth functioning
of the many components that make up the application. You need to monitor
its performance—its resource usage, user traffic, request rates, response times,
bottlenecks, memory issues, and so forth—to be able to overcome these limitations
and ensure a good end-user experience. Spring Actuator is used to expose
operational information about the running application—health, metrics, info, dump,
env, and so on. It uses HTTP endpoints or JMX beans to enable you to interact with it.
Actuator uses Micrometer, a dimensional-first metrics collection facade whose aim is
10
https://projects.spring.io/spring-security
11
Chapter 1 ■ Introducing Spring
to allow you to time, count, and gauge your code with a vendor-neutral API. Despite
its focus on dimensional metrics, Micrometer does map to hierarchical names to
continue to serve older monitoring solutions like Ganglia or narrower scoped tools
like JMX. The change to Micrometer arose out of a desire to better serve a wave of
dimensional monitoring systems (think Prometheus, Datadog, Wavefront, SignalFx,
Influx, etc.). This flexibility is an advantage of Spring being designed for DI, which
allows easily swapping monitoring systems as well. Working with Actuator is covered
in Chapter 18.
• Run everywhere: For a long time the technical evolution allow us to go big - we’ve
found new ways of keeping CPUs cool while increasing their frequency, and we’ve
managed to provide more memory with smaller chips, but recently a new trend
has arisen. Deploying applications on privately owned clouds has made people
worry about the cloud costs, so an emerging trend is to build compact applications
that require smaller CPUs and less memory to run. Better performance with less
resource consumption means less cloud costs, and this is why the age of compact
native images is coming. The experimental (for now) Spring Native project provides
support for compiling Spring applications to native executables using the GraalVM
native-image compiler. GraalVM is a high-performance runtime that provides
significant improvements in application performance and efficiency, which is ideal
for microservices. This means applications start faster and need less resources while
running. This makes them suitable to be deployed in a private cloud (Amazon,
GCP, Hetzner, etc.) with decent costs. How to build a Spring project to be runnable
using a GraalVM native image using Spring Native and other goodies is covered in
Chapter 14.
The Spring Community
The Spring community is one of the best in any open source project we have encountered. The mailing
lists and forums are always active, and progress on new features is usually rapid. The development team is
truly dedicated to making Spring the most successful of all the Java application frameworks, and this shows
in the quality of the code that is reproduced. As we mentioned already, Spring also benefits from excellent
relationships with other open source projects, a fact that is extremely beneficial when you consider the large
amount of dependency the full Spring distribution has. From a user’s perspective, perhaps one of the best
features of Spring is the excellent documentation and test suite that accompany the distribution.
Documentation is provided for almost all the features of Spring, making it easy for new users to pick up
the framework. The test suite Spring provides is impressively comprehensive—the development team writes
tests for everything. If they discover a bug, they fix that bug by first writing a test that highlights the bug and
then getting the test to pass. Fixing bugs and creating new features is not limited just to the development
team! You can contribute code through pull requests against any portfolio of Spring projects through the
official GitHub repositories11. Or you can help experimental projects grow their wings by contributing
though the official experimental GitHub repositories12.
What does all this mean to you? Well, put simply, it means you can be confident in the quality of the
Spring Framework and confident that, for the foreseeable future, the Spring development team will continue
to improve what is already an excellent framework.
11
https://github.com/spring-projects
12
https://github.com/spring-projects-experimental
12
Chapter 1 ■ Introducing Spring
Alternatives to Spring
Going back to our previous comments on the number of open source projects, you should not be surprised
to learn that Spring is not the only framework offering dependency injection features or full end-to-end
solutions for building applications.
A popular DI framework is Google Guice13. Led by the search engine giant Google, Guice is a
lightweight framework that focuses on providing DI for application configuration management. It was also
the reference implementation of JSR-330 (Dependency Injection for Java).
Vaadin14 is an open source web application development platform for Java. Vaadin includes a set of
Web Components, a Java web framework, and a set of tools that enable developers to implement modern
web graphical user interfaces using the Java programming language only, TypeScript only, or a combination
of both. It’s scope is limited to web applications, but for more complex applications it easily integrates with
Spring and can harness the power of the Spring IoC container.
The now defunct JBoss Seam Framework15 used to be a good alternative to Spring. When I took my first
Spring training in 2012, I was pretty convinced the Spring annotation model for configuring its beans was
inspired from it.
The now defunct PicoContainer16 was an exceptionally small DI container that allowed you to use
DI for your application without introducing any dependencies other than PicoContainer. Being nothing
more than a DI container, writing a more complex application required adding of extra frameworks, such as
Spring, in which case you would have been better off using Spring from the start. However, if all you needed
was a tiny DI container, then PicoContainer was a good choice.
Summary
In this chapter, you were provided a 10,000-foot view of the Spring Framework and its evolution onto a
collection of projects that can be used to build any type of application you might need, complete with
discussions of all the important features. A guide to the relevant sections of the book where these features
are discussed in detail was provided, together with references to the additional technologies that will be
used throughout the book.
After reading this chapter, you should understand what Spring can do for you; all that remains is to see
how it can do it. In the next chapter, you will be provided all the information you need to know to prepare
your development environment to get up and running with a basic Spring application. Chapter 2 introduces
some basic Spring code and configuration, including a time-honored Hello World example in all its DI-
based glory.
13
https://github.com/google/guice
14
https://vaadin.com
15
https://www.seamframework.org
16
http://picocontainer.com
13
CHAPTER 2
Getting Started
The most difficult part when starting a new project is setting up a development process that involves
selecting and optimizing the tooling, so that you can focus on writing the code. Fortunately, this book
intends to make that easier. The project for this book is a Kotlin project that uses Spring components, which
means there are quite a few choices when it comes to editors, build tools, and even JDKs.
This chapter provides all the basic knowledge you need to get off to a flying start, but first let’s look at a
few conventions.
C
onventions
This book uses several formatting conventions that should make it easier to read. To that end, the following
conventions are used within the book:
• Code or concept names in paragraphs appear as follows: java.util.List
• Code listings and configurations appear as follows:
fun main(args: Array<String>) {
println("Hello World!")
}
• Logs in console outputs appear as follows:
01:24:07.809 [main] INFO c.a.Application - Starting Application
01:24:07.814 [main] DEBUG c.a.p.c.Application - Running in debug mode
• {xx} is a placeholder, where the xx value is a pseudo-value giving a hint about the
real value that should be used in the command or statement. For example, {name_
of_your_bean} means that in a concrete example, the whole construct should be
replaced by the name of your bean.
• Italic font is used for humorous metaphors, expressions, and bits of text that need
some kind of separation from the text around them. For example, in Chapter 1 the
Hollywood Principle is introduced as Don’t call us, we’ll call you.
• Bold font is used for chapter references and important terms.
• (..) is used to replace sets of parameter declarations and arguments in methods
and constructors, to avoid distracting you from the actual code.
© Peter Späth, Iuliana Cosmina, Rob Harrop, Chris Schaefer 2023 15
P. Späth et al., Pro Spring 6 with Kotlin, https://doi.org/10.1007/978-1-4842-9557-1_2
Chapter 2 ■ GETTING STARTED
• …is used to replace code, configuration, and logs not relevant to the context.
• Package import statements are kept to a minimum, and only the ones relevant to the
component being discussed are shown. This is to reduce the space taken up by code
in the book, a better use of which is for more in-depth explanations. You have the full
code in the project anyway!
• Each chapter has a few footnotes and links pointing you to documentation, tools,
and blog articles. The book is readable without consulting them, so feel free to ignore
them, but you might find them useful.
• Some paragraphs are shown in a rectangle and labeled with one of the icons in
Table 2-1. The table also shows the meaning of each icon.
Table 2-1. Special Paragraphs Icons and Meanings
Label Meaning
You might find this useful.
You will definitely find this useful.
This is really useful.
Be careful when using this.
Whatever this is about, it is recommended
not to do it.
Whatever this is about, just don’t do it.
As for my style of writing, I like to write my books in the same way I have technical conversations with
colleagues and friends, sprinkling in jokes, giving production examples, and making analogies to non-
programming situations. Because programming is nothing but just another way to model the real world.
Who This Book Is For
This book assumes you are somewhat familiar with Java, Kotlin, and tools involved in development of Java/
Kotlin applications. If you are not, that might not be too much of a problem, because the project is neatly set
up such that you could build it without having any knowledge about what Gradle does. Also, if you stick to
the recommended editor, which is IntelliJ IDEA, you should be able to just clone the repository, build the
project, and get right to business.
What You Need for This Book
You obviously need a computer, desktop or laptop, the choice of which doesn’t really matter as long as it is
up to date, running Windows, Linux, or macOS, and is connected to the Internet.
16
Chapter 2 ■ GETTING STARTED
You need to have JDK 17 (or OpenJDK 17) installed locally. Instructions on how to do so on any
operating system are available on the Oracle official page1,2.
For any Unix-based system, SDKMAN!3 is very useful. SDKMAN! is a tool for managing parallel versions
of multiple software development kits on most Unix-based systems. It provides a convenient command-line
interface (CLI) and API for installing, switching, removing, and listing candidates. It works for JDK, Gradle, and
many more.
As previously mentioned, the recommended editor is IntelliJ IDEA4; you can use the Enterprise
version for free for 30 days, or you can help test Early Access versions. IntelliJ IDEA is a great editor for
Spring applications because it comes with a great set of plug-ins that help you be very aware if your beans
are properly configured. If you are more familiar with Eclipse IDE, you can try Spring Tools 45 to simplify
developing for Spring.
There is also a community edition of IntelliJ IDEA, which is free to use (licensed under Apache 2.0).
It lacks some extended support for Spring, but you still can use it for all the book’s Kotlin sources.
You need the sources where all the code samples referenced in the book come from. Depending on
how you are getting the project associated with this book, you might need Git6 installed. You can use Git
from the command line to clone the repository, or you can use the IDE, or you can download the sources as
a zip from the repository page.
This is the project repository page: https://github.com/Apress/pro-spring-6-kotlin
Any project dependencies that are more complex than a Java/Kotlin library and need to run services
that the Spring applications interact with are provided via Docker containers; thus, you need to install
Docker7 on your computer. Instructions on how to download images and start them are provided in README.
adoc files for the respective chapters.
To summarize the requirements for you to become a Spring professional: this book, a computer,
Internet, Java 17, Git, the sources, Docker, and a little bit of time and determination.
1
https://docs.oracle.com/en/java/javase/17/install/overview-jdk-installation.html
2
https://openjdk.org/, https://jdk.java.net/archive/, https://jdk.java.net/19/
3
https://sdkman.io
4
https://www.jetbrains.com/idea
5
https://spring.io/tools
6
https://git-scm.com/
7
https://www.docker.com/
17
Chapter 2 ■ GETTING STARTED
Prepare Your Development Environment
Here is the list of steps you have to go through to start running the code associated with the book:
• Sit comfortably in front of your computer.
• Install JDK 17 (or OpenJDK 17). Later versions might do as well.
If you have older versions installed, make sure JDK 17 is the default one used on your system by
opening a terminal (Command Prompt or Power Shell on Windows systems) and running java -version.
Expect the output to mention Java version 17, as depicted in Listing 2-1.
Listing 2-1. Output of Command java -version Showing JDK 17 Set As Default
> java -version
java version "17.0.1" 2021-10-19 LTS
Java(TM) SE Runtime Environment (build 17.0.1+12-LTS-39)
Java HotSpot(TM) 64-Bit Server VM (build 17.0.1+12-LTS-39, mixed mode, sharing)
• Clone the project repository or download the sources from the Apress official page
and unzip them on your computer. Make sure you select the Kotlin variant of the
sources. You should have a directory named pro-spring-6 containing the modules
as shown in Figure 2-1.
Figure 2-1. The pro-spring-6 project and its modules
• Open the IntelliJ IDEA editor, choose File ➤ Openin the main menu, and in the file
selector window that opens, select the pro-spring-6 directory. After a short while,
on the left side (in a pane we’ll call the Project View in this book), you should see the
18
Chapter 2 ■ GETTING STARTED
pro-spring-6 project and its modules listed. On the right side of the window, you
should see a section showing you the Gradle configuration (we’ll call this the Gradle
View in this book). These views are shown in Figure 2-2.
For the Kotlin variant of the book, the build process concentrates on using Gradle as a build tool. Gradle
setups are just a lot more concise compared to Maven setups. If you really need to use Maven, the Java variant
of the sources plus the information provided at https://kotlinlang.org/docs/maven.html should
help you.
Figure 2-2. The pro-spring-6 project, Gradle View
The project is made up of a main Gradle project and multiple subprojects, each representing a Kotlin
project. The name of each module includes the chapter number where its contents are referenced. Every
project depends on a lot of libraries that will be automatically downloaded when your project is opened in
an editor for the first time.
The project can be built right after cloning according to the instructions in its README.adoc file. The
project does not need Gradle installed locally, since it is configured to use wrappers respectively IDE plugins.
The Gradle version used to build the project at the time this chapter is being written is 7.4. The version
likely will change by the time the book is released, but the version will be mentioned in the main README.
adoc file and in the Gradle wrapper configuration file: gradle/wrapper/gradle-wrapper.properties.
19
Chapter 2 ■ GETTING STARTED
IntelliJ IDEA identifies the wrapper configurations and builds your project from them. If you want to
explicitly trigger any of them from the interface, just click the symbol that you can see in the upper-left
corner of Gradle View.
IntelliJ IDEA keeps the state of your project internally and sometimes gets…ahem…confused. If your
project shows class names in red and complains about missing dependencies, try building it from the command
line as explained in the README.adoc file. If that works, you might to one of these options under the File menu:
Invalidate Caches, Reload All from Disk, Restart IDE, Repair IDE.
Now that you have the project loaded and building successfully on your computer, we’ll tell you more
about Spring internals before explaining the pro-spring-6 project Gradle configurations.
Understanding Spring Packaging
Spring packaging is modular; it allows you to pick and choose which components you want to use in your
application and to include only those components when you are distributing your application. Spring has
many modules, but you need only a subset of these modules depending on your application’s needs. Each
module has its compiled binary code in a JAR file along with corresponding Javadoc and source JARs. IntelliJ
IDEA scans the dependencies of your project and on request it can download the sources and Javadoc. This
means that you can see the code and read about Spring classes in your editor.
The Javadoc for a class is shown in a rectangle when hovering over its name, as depicted in Figure 2-3
for the @SpringBootApplication annotation (the figure shows the Java variant; for Kotlin the view looks
similar).
Figure 2-3. IntelliJ IDEA displaying the Javadoc for the @SpringBootApplication annotation
20
Chapter 2 ■ GETTING STARTED
You can also choose to press the Ctrl (Command for macOS) key and click a class name, and IntelliJ
IDEA will download the sources for it and open them in a new tab. In Figure 2-4 you can see on the right the
source for the @SpringBootApplication annotation (again, the figure shows the Java variant, and the view
looks similar for Kotlin).
Figure 2-4. IntelliJ IDEA displaying the source for the @SpringBootApplication annotation
Back to the Spring modules. Spring modules are simply JAR files that package the required code for
that module. The code base for the Spring Framework is publicly available on GitHub. If you are curious
about what the code of the Spring Framework looks like and want and to be on the cutting edge of Spring
development, check out the latest version of the source code from Spring’s GitHub repository8.
After you understand the purpose of each module, you can select the modules required in your project
and include them in your code. As shown by the most recent tag on GitHub, it seems that Spring Framework
version 6.0 comes with 22 modules. Table 2-2 describes these JAR files and their corresponding modules.
The actual JAR file name is, for example, spring-aop-6.0.0.jar, though we have included only the specific
module portion for simplicity (as in aop, for example).
8
https://github.com/spring-projects/spring-framework
21
Chapter 2 ■ GETTING STARTED
Table 2-2. Spring Modules
Module Description
aop This module contains all the classes you need to use Spring’s AOP features within your
application. You also need to include this JAR in your application if you plan to use other
features in Spring that use AOP, such as declarative transaction management. Moreover,
classes that support integration with AspectJ are packed in this module.
aspects This module contains all the classes for advanced integration with the AspectJ AOP library.
For example, if you are using Java classes for your Spring configuration and need AspectJ-style
annotation-driven transaction management, you need this module.
beans This module contains all the classes for supporting Spring’s manipulation of Spring beans.
Most of the classes here support Spring’s bean factory implementation. For example, the
classes required for processing the Spring XML configuration file and Java annotations are
packed into this module.
context This module contains classes that provide many extensions to Spring Core. You will find that
all classes need to use Spring’s ApplicationContext feature (covered in Chapter 5), along
with classes for Enterprise JavaBeans (EJB), Java Naming and Directory Interface (JNDI), and
Java Management Extensions (JMX) integration. Also contained in this module are the Spring
remoting classes, classes for integration with dynamic scripting languages (for example,
JRuby, Groovy, and BeanShell), JSR-303 (“Bean Validation”), scheduling and task execution,
and so on.
context- This module contains an indexer implementation that provides access to the candidates that
indexer are defined in META-INF/spring.components. The core class CandidateComponentsIndex is
not meant to be used externally.
context- This module contains further extensions to the spring-context module. On the user-
support interface side, there are classes for mail support and integration with templating engines such
as Velocity, FreeMarker, and JasperReports. Also, integration with various task execution and
scheduling libraries, including CommonJ and Quartz, are packaged here.
core This is the main module that you will need for every Spring application. In this JAR file, you
will find all the classes that are shared among all other Spring modules (for example, classes
for accessing configuration files). Also, in this JAR, you will find selections of extremely useful
utility classes that are used throughout the Spring codebase and that you can use in your own
application.
expression This module contains all support classes for Spring Expression Language (SpEL).
instrument This module includes Spring’s instrumentation agent for JVM bootstrapping. This JAR file is
required for using load-time weaving with AspectJ in a Spring application.
jcl This module is only present for binary compatibility with existing Apache Commons Logging
usage, such as in Apache Commons Configuration.
jdbc This module includes all classes for JDBC support. You will need this module for all
applications that require database access. Classes for supporting data sources, JDBC data
types, JDBC templates, native JDBC connections, and so on, are packed in this module.
(continued)
22
Chapter 2 ■ GETTING STARTED
Table 2-2. (continued)
Module Description
jms This module includes all classes for Java Message Service (JMS) support.
messaging This module contains key abstractions taken from the Spring Integration project to serve as a
foundation for message-based applications and adds support for STOMP messages.
orm This module extends Spring’s standard JDBC feature set with support for popular ORM
tools including Hibernate, JDO, and JPA. Many of the classes in this JAR depend on classes
contained in the spring-jdbc JAR file, so you definitely need to include that in your
application as well.
oxm This module provides support for Object/XML Mapping (OXM). Classes for the abstraction
of XML marshalling and unmarshalling and support for popular tools such as Castor, JAXB,
XMLBeans, and XStream are packed into this module.
r2dbc This module makes R2DBC easier to use and reduces the likelihood of common errors. It
provides simple error handling and a family of unchecked concise exceptions agnostic of the
underlying RDBM (Reactive Database Manager).
test Spring provides a set of mock classes to aid in testing your applications, and many of
these mock classes are used within the Spring test suite, so they are well tested and make
testing your applications much simpler. Certainly we have found great use for the mock
HttpServletRequest and HttpServletResponse classes in unit tests for our web applications.
On the other hand, Spring provides a tight integration with the JUnit unit-testing framework,
and many classes that support the development of JUnit test cases are provided in this
module; for example, SpringExtension integrates the Spring TestContext Framework into
JUnit 5’s Jupiter programming model.
tx This module provides all classes for supporting Spring’s transaction infrastructure. You will
find classes from the transaction abstraction layer to support the Java Transaction API (JTA)
and integration with application servers from major vendors.
web This module contains the core classes for using Spring in your web applications, including
classes for loading an ApplicationContext feature automatically, file upload support classes,
and a bunch of useful classes for performing repetitive tasks such as parsing integer values
from the query string.
webflux This module contains core interfaces and classes for the Spring Web Reactive model.
webmvc This module contains all the classes for Spring’s own MVC framework. If you are using a
separate MVC framework for your application, you won’t need any of the classes from this
JAR file. Spring MVC is covered in more detail in Chapter 15.
websocket This module provides support for JSR-356 (“Java API for WebSocket”).
23
Chapter 2 ■ GETTING STARTED
If you use Spring Boot, you don’t have to select Spring modules to add as dependencies explicitly,
because the appropriate set of Spring dependencies are configured depending on the Spring Boot starter
dependencies used. The codebase for Spring Boot is also publicly available on GitHub. If you are curious
about how the Spring Boot code looks like and want to be on the cutting edge of Spring Boot development,
check out the latest version of the source code from Spring’s GitHub repository9. Under spring-boot-
project/spring-boot-starters there is a list of Spring Boot starter modules that can be used as
dependencies for a Spring project to build a certain type of Spring application, with a default configuration
and curated set of dependencies. The modules are nothing but dependency descriptors that can be added
inside the dependencies { } section in build.gradle. There are currently more than 30 of them, and
Table 2-3 lists the ones most often used and the dependencies they configure for your application.
Table 2-3. Spring Boot Starter Modules
Module Description
spring-boot-starter This is the simplest Spring Boot starter that adds the spring-core
module as a dependency for your project. It can be used to create
a very simple Spring application. It is used mostly for learning
purposes and for creating base projects, that encapsulate common
functionality shared among other modules in a project.
spring-boot-starter-aop Adds the spring-aop as a dependency for your project.
spring-boot-starter-data-* This type of starter adds various Spring dependencies for working
with data in your project. The * replaces the technology from which
data is coming. For example, spring-boot-starter-data-jdbc adds
classes for creating Spring Repository beans for handling data from
databases supporting a JDBC driver: MySQL, PostgreSQL, Oracle,
etc.
spring-boot-starter-web Configures minimal dependencies for creating a web application.
spring-boot-starter-security Configures minimal dependencies for securing a Spring web
application.
spring-boot-starter-webflux Configures minimal dependencies for creating a reactive web
application.
spring-boot-starter-actuator Configures Spring Boot Actuator, which enables a set of endpoints
for monitoring a Spring web application.
spring-boot-starter-test Configures the following set of libraries: Spring Test, JUnit, Hamcrest,
and Mockito.
Choosing Modules for Your Application
Without a dependency management tool such as Maven or Gradle, choosing which modules to use in your
application may be a bit tricky. For example, if you require Spring’s bean factory and DI support only, you
still need several modules, including spring-core, spring-beans, spring-context, and spring-aop. If you
need Spring’s web application support, you then need to further add spring-web and so on. Thanks to build
tools features such as Gradle’s transitive dependencies support, all required third-party libraries would be
included automatically.
9
https://github.com/spring-projects/spring-boot/
24
Chapter 2 ■ GETTING STARTED
Accessing Spring Modules on the Maven Repository
Founded by Apache Software Foundation, Maven10 has become one of the most popular tools in managing
the dependencies for Java applications, from open source to enterprise environments. Maven is a powerful
application building, packaging, and dependency management tool. It manages the entire build cycle
of an application, from resource processing and compiling to testing and packaging. There also exists a
large number of Maven plug-ins for various tasks, such as updating databases and deploying a packaged
application to a specific server (for example: Tomcat, WildFly, or WebLogic). As of this writing, the current
Maven version is 3.8.4.
Almost all open source projects support distribution of libraries via the Maven repository. The most
popular one is the Maven Central repository hosted on Apache, and you can access and search for the
existence and related information of an artifact on the Maven Central website11.
A detailed discussion of Maven is not in the scope of this book, and you can always refer to the online
documentation or books that give you a detailed reference to Maven.
Accessing Spring Modules Using Gradle
The Maven project standard structure is depicted in Figure 2-5.
Figure 2-5. Gradle typical project structure
The main directory contains the application codebase in the kotlin directory and application
configuration files in the resources directory. The test directory contains the application test code in the
kotlin directory and the application test configuration files in the resources directory (not shown in the
figure—you can easily add it).
10
https://maven.apache.org
11
https://mvnrepository.com/
25
Chapter 2 ■ GETTING STARTED
Maven sources and other artifact categorization and organization is important because Gradle12
respects the same rules and even uses the Maven Central repository to retrieve artifacts. Various other
repositories can be configured as well. Gradle is a powerful build tool that has given up the bloated XML
for configuration and switched to the simplicity and flexibility of Groovy. Which is very good and provides a
lot of flexibility, up until a developer gets too creative with their configuration, that is. At the time of writing,
the current version of Gradle is 7.3.3 Starting with version 4.x, the Spring team has switched to using Gradle
for the configuration of every Spring product. That is why the source code for this book can be built and
executed using Gradle. The default name of a Gradle configuration file for a project is build.gradle. An
example of this file is shown in Listing 2-2.
Listing 2-2. build.gradle Snippet
plugins {
id 'org.jetbrains.kotlin.jvm' version '1.8.10'
id 'application' // make it runnable via Gradle
}
group 'com.apress.prospring6.ch02'
version '6.0-SNAPSHOT'
repositories {
mavenCentral()
}
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}
dependencies {
implementation group: 'org.apache.logging.log4j', name: 'log4j-core', version: '2.17.1'
}
application {
// For running from Gradle. Note that the file name reads
// HelloApplication.kt – the "Kt" gets added by the compiler.
mainClass = 'book.spring6.helloworld.HelloApplicationKt'
}
That’s quite readable, right? As you can observe, the artifacts are identified using the group, artifact, and
version. Gradle itself is not in the scope of this book, so detailed coverage of it must end here.
Using Spring Boot Dependency Management
Since Gradle does not have a parent concept similar to Maven, dependency management is done using the
io.spring.dependency-management plug-in. Listing 2-3 depicts a Gradle configuration.
12
https://gradle.org/
26
Other documents randomly have
different content
niinpä hänet maalasikin mr. Jervis; Esmondilla oli muotokuvassa
punainen takkinsa ja hän hymyili pommille, joka räjähti muotokuvan
kulmassa. Lady vakuutti, ettei hän koskaan kuolisi rauhallisena, ellei
Esmond tekisi loistavaa naimiskauppaa, ja hän toi yhtämittaa
Chelsea'hen nuoria ladyjä, joilla oli sievät kasvot ja sievät
omaisuudet, jotta eversti saisi valita. Esmond hymyili ajatellessaan,
miten ajat olivat muuttuneet samalla kuin hän itsekin, sekä
lapsuuden aikaansa isänsä eläessä, jolloin hän oli seisonut
vapisevana paashina ladyn vaununastimella. Ainoa virhe, jonka lady
hänessä havaitsi oli, että hän oli raittiimpi kuin Esmondin sopi olla
eikä kannatuttanut itseään vuoteeseen kamaripalvelijallaan eikä
menettänyt sydäntään millekään kaunottarelle, olipa tämä St
Jamesista tai Covent Gardenista.
Mitä merkitsee uskollisuus rakkaudessa ja mistä se johtuu? Se on
eräs mielentila, johon miehet joutuvat, ja riippuu miehestä enemmän
kuin naisesta. Me rakastamme rakastuneena olemista, se on totuus.
Ellemme olisi kohdanneet Hannaa, olisimme kohdanneet Katrin ja
ihailleet häntä. Me tiedämme, etteivät meidän rakastettumme ole
sen parempia kuin useat muutkaan naiset, eivätkä kauniimpiakaan,
eivätkä viisaampia eivätkä nerokkaampia. Näiden syiden vuoksi
emme rakasta naista, emmekä tietääkseni minkään erikoisen avun
tai sulon vuoksi. Voisimmekin aivan yhtä hyvin vaatia, että nainen
olisi maailman pisin nainen, kuten Shropshiren jättiläisnainen [siten
ei nainen rakasta: eversti E. on myöntänyt olleensa hullaantunut
vielä useihin muihinkin naisiin. — R.], kuin että hän olisi minkään
muun avun esikuva ennenkuin aloimme häntä rakastaa. Esmondin
rakastetulla oli tuhansia virheitä lumojensa ohella. Esmond tunsi nuo
molemmat puolet hänessä erinomaisen hyvin! Hän oli itsevaltainen,
hän oli kevytmielinen, hän oli pikainen, hän oli petollinen, hän ei
tuntenut kunnioitusta mitään kohtaan; hän oli kaikessa
kauneudessaankin, äitinsä vastakohta, tämä kun oli mitä
helläluonteisin ja epäitsekkäin nainen. Niin, aivan ensi hetkestä,
silloin kun Esmond näki Beatrixin Walcoten rappusilla, hän tunsi
rakastavansa Beatrixia. Parempia naisia saattoi olla: hän halusi
omistaa tämän. Hän ei välittänyt kenestäkään muusta. Siksikö, että
Beatrix oli ylevän kaunis? Vaikka hän olikin kaunis, oli Esmond
kuullut ihmisten monta monituista kertaa sanovan heidän ollessaan
saapuvilla, että Beatrixin äiti näytti yhtä nuorelta ja oli noista
kahdesta kauniimpi. Miksi värisi Beatrixin ääni Esmondin korvissa niin
kummasti? Hän ei osannut laulaa läheskään niin hyvin kuin Nicolini
tai mrs. Tofts — ei, hänhän lauloi epäpuhtaasti — ja kuitenkin
kuunteli Esmond mieluummin häntä kuin Pyhää Ceciliaa. Hänellä ei
ollut sen raikkaampi hipiä kuin mrs. Steelellä (Dickin vaimolla, jonka
tämä nyt oli voittanut itselleen ja joka hallitsi Dick-parkaa kovin
peloittavalla valtikalla) ja kuitenkin huikaisi hänen muotonsa
Esmondin; Esmond saattoi sulkea silmänsä ja kuitenkin huikaisi
hänet hänen mielessään väikkyvä kuva. Beatrix oli puheessaan
loistava ja vilkas, mutta hän ei sentään ollut niin verrattoman
nerokas kuin hänen äitinsä, joka hyvällä tuulella ollessaan keskusteli
tavattoman henkevästi; ja kuitenkin oli Esmondin suurin ilo saada
kuunnella Beatrixia ja olla hänen seurassaan. Päivät kuluivat näiden
naisten seurassa niin että Esmond tuskin tiesi miten. Esmond ilmoitti
heille avomielisesti kaikki sydänsalaisuutensa, ja sitä ei hän koskaan
voinut tehdä missään muussa seurassa, missä häntä tavallisesti
pidettiinkin ärtyisenä tai kopeana tai hiljaisena. Tämä seura [ja niin
oli hänenkin seuransa heille monta monituista kertaa suloisempaa,
sillä missäpä olisi ollut hänen vertaistaan? — R.] oli hänelle
ihastuttavampi kuin suurimpienkaan älyniekkojen seura. Suokoon
taivas hänelle anteeksi ne valheet, jotka hän lateli Chelsean leski
varakreivittärelle saadakseen tekosyyn Kensingtoniin menemistä
varten, kaikki ne tykistökonttoriin olevat asiat mitkä hän keksi, ne
matkat, jotka hän teki muka haastatellakseen kenraaliaan, ne hovit
ja valtiomiesten vastaanotot, joissa hän ei käynyt ja joista hän
kertoi, — kellä oli ollut uusi puku sunnuntaina St. Jamesissa tai
kuningattaren syntymäpäivänä, miten monta vaunua täytti kadun mr.
Harleyn vastaanotossa, miten monta pulloa hänellä toissa yönä oli
ollut kunnia tyhjentää mr. St. Johnin seurassa "Kaakaopuussa" tai mr.
Walpolen ja mr. Steelen kera "Sukkanauhassa".
Mistress Beatrix Esmond oli ollut monta monituista kertaa
tekemäisillään loistavan naimiskaupan, niin sanoivat hovijuorut;
mutta Esmond puolestaan ei koskaan halunnut uskoa juttuja, joita
puhuttiin häntä vastaan, ja Esmond palasi, oltuaan kolme vuotta
poissa hänen luotaan, vaikka ei kenties juuri yhtä hurjasti
rakastuneena kuin hän oli ollut, niin kuitenkin kaihoten vain yksin
häntä — yhä toivoen, polvistuen, sydän kädessään tarjona nuorelle
ladylle. Olimme nyt päässeet vuoteen 1709. Beatrix oli lähes
kaksikymmentäkaksi vuotias, ja hän oli ollut kolme vuotta hovissa
eikä hänellä vielä ollut miestä.
"Se ei johdu siitä, ettei häntä olisi kosittu", virkkoi lady
Castlewood, joka näki kuten tavallisesti Esmondin sisimmät ajatukset
tarkkanäköisyydellä, minkä rakkaus antaa. "Mutta hän ei halua tehdä
huonoa naimiskauppaa, Henry; hän ei halua naida niinkuin hänen
minä tahtoisin naivan; sille henkilölle, jota minä mielelläni sanoisin
pojakseni — ja Henry Esmond tietää, kuka se on — teen parhaan
palveluksen sillä, etten aja hänen asiaansa. Beatrix on niin
itsepäinen, että hän varmaan vastustaisi sitä, mihin minä häntä
kehoittaisin. Mies, joka hänet nai, ei ole onnellinen hänen kanssaan,
ellei hän ole joku suuruus, joka voi koroittaa hänet mahtavaan
asemaan. Beatrix pitää enemmän ihailusta kuin rakkaudesta, ja
kaikkea muuta mieluisampaa on hänestä käskeminen. Miksi puhuu
äiti näin lapsestaan? Sinäkin olet minun poikani, Henry. Sinun tulee
tietää totuus sisarestasi. Luulin, että voisit parantua intohimostasi",
lisäsi lady lempeästi. "Tiedäthän, että toiset ihmiset voivat parantua
tuosta hullutuksesta. Mutta näen, että sinä olet yhä yhtä
hurmaantunut kuin ennenkin. Kun luimme sinun nimesi Gazettesta,
rukoilin sinun puolestasi, poikaparkani. Poikaparka tosiaankin!
Sinähän alat käydä vakavaksi vanhaksi herraksi ja minä olen jo
vanha vaimo. Beatrix pitää kyllä paljon sinun kuuluisuudestasi ja hän
pitää myös sinusta itsestäsi. Hän sanoo, että sinussa on neroa ja
tulta ja että olet hyvin kasvatettu ja luonnollisempi kuin hovin hienot
herrat. Mutta tämä ei riitä. Hän haluaa itselleen ylipäällikön eikä
mitään everstiä. Jos joku herttua kosisi häntä, hylkäisi hän jaarlin,
jolle jo oli lupautunut. Tämän olen sinulle jo ennenkin sanonut. En
ymmärrä miksi tyttöparkani on niin maallinen mieleltään."
"Niin", virkkoi Esmond, "mies ei voi enempää kuin antaa
parhaimpansa ja kaikkensa. Sen minä hänelle tarjoan. Vakuutan,
että välitin siitä vähäisestä kunniasta, minkä olen voittanut, vain
siksi, että luulin sen miellyttävän Beatrixia. Mitäpä minä välittäisin
everstin tai kenraalin arvosta? Onko tosiaankaan sillä, mitkä meidän
tyhmät arvomme nykyään ovat, mitään merkitystä muutamain
vuosikymmenien kuluttua? Minä vain halusin saada hieman
mainetta, jotta hän käyttäisi sitä koristeena hatussaan, jos minulla
olisi jotain parempaa, niin koristaisin hänet sillä. Jos hän haluaisi
elämäni, antaisin sen hänelle. Jos hän menee naimisiin jonkun toisen
kanssa, niin Jumala suojelkoon sitä miestä, sanon minä. Minä en
kerskaile enkä valita. Uskollisuuteni saattaa olla vain hullutusta,
mutta niin vain ajattelen. En voi sitä auttaa. Minä rakastan häntä. Te
olette tuhat kertaa parempi, — olette lempein, ihanin, armain
naisista. Minä näen kyllä, armas lady, kaikki Beatrixin virheet yhtä
hyvin kuin tekin. Mutta hän on kohtaloni. Häntä en voi välttää. En
kuole, jollen häntä saa. Luulenpa, etten olisi yhtään sen
onnellisempi, jos hänet itselleni voittaisinkin. Que voulez-vous?
sanoisi Chelsean lady. Je t'aime." [Joka tapauksessa rakastan häntä.]
"Minä toivon, että hän ottaisi sinut", sanoi Harryn lempeä emäntä
ojentaen hänelle kätensä. Esmond suuteli kaunista kättä (se oli
sievin kuopikas pikku kätönen maailmassa, ja lady Castlewood näytti
ainakin kymmentä vuotta nuoremmalta, vaikka hän oli jo melkein
neljänkymmenen vuoden vanha). Esmond suuteli kaunista kättä eikä
hellittänyt siitä kun he jatkoivat puhettaan.
"Niin", sanoi hän, "kallistaako hän minulle korvaansa? Hän tietää
mitä sanomista minulla on. Olinpa kaukana tai lähellä, hän tietää,
että olen hänen orjansa. Saattaa olla, että olen myynyt itseni
ilmaiseksi. No niin, se on ainakin hinta, jonka itse haluan. Joko en
ole minkään arvoinen tai olen kaiken arvoinen."
"Minusta sinä olet sellainen aarre", suvaitsi Esmondin emäntä
sanoa, "että naisen, jolla on sinun rakkautesi, ei tulisi vaihtaa sitä
kuningaskuntaankaan. Minä olen maalla kasvatettu nainen enkä voi
muuta sanoa kuin että kaupunkilainen kunnianhimo näyttää minusta
kehnolta. Minä en ole koskaan tuntenut pelonsekaista kunnioitusta
herttuattaren arvoa enkä hepeniä kohtaan tai pelännyt", hän lisäsi
viekkaasti nauraen, "mitään muuta kuin hänen luonnettaan. Minulle
puhutaan hovinaisista, jotka riutuvat siksi, että kuningatar katsoo
heihin kylmästi, ja suurista aatelismiehistä, jotka antaisivat toisen
raajoistaan saadakseen pitää sukkanauhan ritarimerkkiä toisessa.
Tämä maailmanmielisyys, jota minä en voi käsittää, on synnynnäistä
Beatrixissa, joka jo ensimmäisenä hovipalveluspäivänään oli
täydellinen hovinainen. Olemme aivan kuin sisaria ja jotenkin on hän
vanhempi sisar. Hän vakuuttaa minulle, että minulla on matala
käsitys. Naurahdan siihen ja sanon, että hän ihailee kuusivaljakkoa.
Minä en voi järkeillä hänestä hänen kunnianhimoaan. Se on hänelle
luontaista samoinkuin minulle on hiljaisen elämän rakkaus ja
välinpitämättömyys arvoa ja rikkaatta kohtaan. Mitä ne merkitsevät,
Harry, ja miten kauan ne kestävät? Meidän kotimme ei ole täällä."
Hän hymyili puhuessaan ja näytti enkeliltä, joka oli vain vierailulla
maan päällä. "Meidän kotimme on siellä, missä oikeamieliset ovat ja
minne eivät meidän syntimme ja surumme seuraa meitä." Isäni
tapasi moittia minua ja sanoa, että olin liian toivehikas taivaan
suhteen. Mutta minä en voi luonteelleni mitään ja käyn
itsepintaiseksi samalla kuin käyn vanhaksi vaimoksi; ja koska minä
rakastan lapsiani niin suuresti, niin varmaan rakastaa Isämme meitä
tuhansia, tuhansia kertoja suuremmalla rakkaudella. Kyllä me
varmaan kohtaamme toisemme siellä ja olemme onnellisia. Niin, sinä
— ja minun lapseni ja rakas lordini. Tiedätkö Harry, hänen
kuolemansa jälkeen minusta on aina tuntunut kuin olisin taas
voittanut hänen rakkautensa ja kuin ei meitä enää mikään erottaisi.
Kenties hän on täällä nyt, Harry — minä luulen, että hän on. Olen
varma, että hän on saanut anteeksi — mr. Atterburykin antoi hänelle
synninpäästön ja hän kuoli anteeksi antavana. Oi miten jalo sydän
hänellä oli! Miten hän oli jalomielinen! Minä olin vain
viisitoistavuotias ja lapsi, kun hän nai minut. Miten hyvä hän oli
alentuessaan ottamaan minut. Hän oli aina hyvä köyhille ja nöyrille.
Lady vaikeni, mutta sitten kohosi hänen kasveilleen pian omituinen
ilme, aivan kuin hänen silmänsä katsoisivat taivaaseen ja näkisivät
siellä mylordin, ja hän hymyili naurahtaen vienosti. "Minä iloitsen,
kun näen teidät, sir", sanoi hän; "kun te tulette, tuntuu kuin ette
milloinkaan olisikaan poissa." Hänen sanansa saattaa kyllä jäljentää
ja muistaa, mutta miten voi kuvailla hänen suloisen äänensä
vivahteita, suloisempia kuin musiikki!
Nuori lordi ei tullut kotiin sotaretken päätyttyä ja kirjoitti, että
sotilasvelvollisuudet pidättivät häntä Brysselissä. Mutta minä uskon,
että hän oli kiintynyt piirittämään erästä ladyä, joka kuului madame
de Soissonsin, Savoijin prinssin äidin, seurueeseen. Mr. Esmond ei
tietenkään ajatellut sopivaksi selostaa lady Castlewoodille nuoren
syntipukin puuhia; hän ei myöskään ollut maininnut sanaakaan lordi
Mohunin kanssa tapahtuneesta asiasta, koska hän tiesi miten
katkerasti hänen emäntänsä vihasi tuon miehen nimeä. Frank ei
kuluttanut paljoa aikaa eikä rahaa kynään ja musteeseen, ja kun
Harry saapui kotiin päällikkönsä kanssa, kirjoitti Frank äidilleen vain
kaksi riviä, ilmoittaen, että haava hänen sääressään oli jo melkein
parantunut ja että hänen jo ennen mainitsemansa velvollisuus piti
häntä Brysselissä ja että Harry-serkku kertoi kaikki uutiset.
Mutta koska mylord tiesi, miten lady Castlewood aina ihastui, kun
hän sai kirjeen tuon kuuluisan joulukuun 29 päivän johdosta, hän
kirjoitti tälle Brysselistä pitkän ja sisältörikkaan kirjeen, ja siinä hän
varmaankin kuvaili Mohunin kanssa tapahtunutta kaksintaistelua;
sillä kun mr. Esmond eräänä päivänä uuden vuoden ollessa alulla tuli
tervehtimään emäntäänsä, tulivat hänen ihmeekseen sekä lady että
hänen tyttärensä häntä suutelemaan ja heidän jälkeensä myös
Chelsean leskivarakreivitär, sillä kantoi tuolin kuljettaja juuri oli
tuonut ladyn kylästään peltojen poikki Kensingtoniin. Kun siis nuo
kaksi Castlewoodin ladyä olivat näin Esmondia kunnioittaneet, astui
leskiä varakreivitär kovin juhlallisena esiin kuningas Jaakon aikaisen
suuren, korkean hiuslaitteen somistamana, jota hän ei milloinkaan
jättänyt, ja sanoi: "Harry-serkku, koko meidän perheemme on
kokoontunut, ja me kiitämme teitä, serkku, jalosta käytöksestänne
perheemme päämiestä kohtaan." Ja viitaten rusoittavaan poskeensa
hän antoi Esmondin tietää, että tätä odotti ihana nautinto saada
suudella sitä. Kun hän oli suudellut yhtä poskea, käänsi lady hänelle
toisen. "Harry-serkku", sanoivat molemmat nuoremmista naisista
yhteen ääneen, "me kiitämme sinua jalosta käytöksestäsi"; ja Harry
alkoi käsittää, että juorut Lillessä tapahtuneesta kaksintaistelusta
olivat tulleet näiden hänen sukulaistensa korviin. Hän oli onnellinen,
kun he kaikki näin tervehtivät häntä perheensä jäsenenä.
Ruokasalin pöydät olivat katetut suurta kestitystä varten ja ladyt
olivat juhlapuvuissa — Chelsean varakreivitär oli kaikkein
upeimmassa vieraspuvussaan, varakreivitär Castlewood oli poistanut
mustan pukunsa, ja hän näytti ihastuttavan kauniilta ja onnelliselta,
ja hovineiti oli puettu sillä loistolla, mikä hänet luontaisesti erotti
muista, ja hänen kauniilla povellaan oli tuo ranskalaisen upseerin
tähti, minkä Frank oli lähettänyt kotiin Ramillies'n taistelun jälkeen.
"Näet, että vietämme juhlaa", sanoi hän, katsahtaen tyytyväisesti
tähteen; "ja olemme siis ripustaneet kunniamerkkimme
rinnoillemme. Eikö äiti näytä lumoavalta? Minä olen hänet pukenut."
Esmondin hyvä emäntä, joka punasteli, kun Esmond häneen katsoi,
näytti sekä vartalonsa että hipiänsä puolesta kauniine hiuksineen ja
komeine muodinmukaisine pukuineen kaksikymmenvuotiaalta
tytöltä.
Pöydällä oli hieno miekka, jossa oli punainen samettinen huotra ja
kaunis siselöity hopeakahva, jossa miekan kannikkeena riippui
sininen koristenauha. "Mikä tämä on?" kysäisi kapteeni ja meni
katsomaan tuota kaunista esinettä.
Miss Beatrix saapui sen ääreen. "Polvistu", virkkoi hän, "tällä
lyömme me sinut ritariksemme", — ja hän heilutti miekkaa Esmondin
pään päällä. "Chelsean varakreivitär lady on antanut tämän miekan
ja minä annoin nauhan ja äiti on neulonut siihen tuon ripsun."
"Aseta miekka hänen vyölleen, Beatrix", sanoi hänen äitinsä. "Sinä
olet meidän ritarimme, Harry, — meidän uskollinen ritarimme. Äiti
kiittää sinua ja rukoilee puolestasi, koska olet puolustanut hänen
poikaansa, rakas, rakas ystäväni." Hän ei kyennyt jatkamaan; ja
leskivarakreivitärkin oli liikutettu, sillä joukko itsepintaisia kyyneleitä
teki surullisia uurteita noille ryppyisille vanhoille ruusuille, joita
Esmondin oli juuri suotu suudella.
"Me saimme kirjeen Frank-kullalta", sanoi lady Castlewood,
"sillävälin kun sinä olit katsomassa hyvää ystävääsi kapteeni Steeleä
Hamptonissa, kolme päivää sitten. Frank kertoi meille kaikki mitä
sinä olet tehnyt ja miten jalosti olit asettunut hänen ja tuon — tuon
roiston väliin."
"Ja tänä päivänä otan minä sinut lapsekseni", sanoi
leskivarakreivitär, "ja sinun vuoksesi, poikani Esmond, toivon, että
olisin rikkaampi", lisäsi hän tehden liikkeen kädellään; ja kun Esmond
kuuliaisena polvistui ladyn eteen, loi lady silmänsä kattoon (jossa oli
kullatussa kynttiläkruunussa kaksitoista vahakynttilää, sillä odotettiin
paljon vieraita) ja rukoili siltä taholta siunausta vast'ikään otetulle
pojalleen.
"Rakas Frank", sanoi toinen varakreivitär, "miten paljon hän pitää
sota-alasta! Hän tutkii nyt linnoitusasioita kovin uutterasti. Kunpa
hän olisi täällä! Ensi vuonna vietämme hänen täysi-ikäiseksi tuloaan
Castlewoodissa."
"Jos vain sotaretki sen sallii", virkkoi mr. Esmond. "Minä en
milloinkaan pelkää, kun hän on sinun seurassasi", sanoi Frankin äiti.
"Olen varma, että Henry-poika aina pitää hänen puoltaan."
"Mutta ennen ensi vuotta tulee rauha, me tiedämme sen
varmasti", huudahti hovineiti. "Lordi Marlborough saa eron ja tuolta
hirveältä herttuattarelta riistetään paikka. Hänen majesteettinsa ei
enää halua puhua hänelle. Näitkö hänet Bushyssa, Harry? Hän on
raivoissaan ja hän harhailee puistossa kuin naarasleijona ja repii
ihmisiltä silmät päästä."
"Ja prinsessa Anna lähettää hakemaan erästä", sanoi Chelsean
lady ottaen esiin mitalinsa ja suudellen sitä.
"Näitkö kuninkaan Oudenardessa, Harry?" kysyi hänen emäntänsä.
Hän oli jyrkkä Jaakon puoluelainen ja hänen olisi ollut yhtä
mahdotonta kieltää kuninkaansa kuin kieltää Jumalansa.
"Minä näin ainoastaan Hannoverin nuoren prinssin", vastasi Harry.
"Chevalier de St. George —"
"Kuningas, sir, kuningas", virkkoivat molemmat rouvat ja neiti
Beatrix; ja Beatrix taputti kauniita käsiään ja huusi "Vive le Roy!"
[Eläköön kuningas!]
Samalla kuului jyrisevää koputusta, joka melkein oli kaataa talon
ovet. Kello oli kolme ja vieraat saapuivat; ja hetken kuluttua ilmoitti
palvelija kapteeni Steelen ja hänen rouvansa.
Kapteeni ja mrs. Steele, jotka olivat ensimmäiset saapujat, olivat
ajaneet Kensingtoniin maatilukseltaan Hampton Wickissä olevasta
Majasta. "Emme tulleet Bloomsbury Squarelta olevasta talostamme",
antoi mrs. Steele rouvien tietää. Harry oli juuri samana aamuna
ratsastanut Hamptonista ja jättänyt tuon pariskunnan sotatilaan.
Sillä huoneesta, jossa hän nukkui, hän saattoi illoin ja aamuin kuulla
sen kotiripityksen, jota mrs. Steele antoi Dick-paralle.
Illalla ei se suuresti surettanut rikollista; Dick oli humalassa, ja kun
hän oli siinä tilassa, eivät mitkään nuhteet voineet, häiritä hänen
hyvää tuultaan; mr. Esmond kuuli hänen mairittelevan ja puhuvan
pehmeään tapaan jommoiseen punssi ja punaviini aiheuttavat,
rakastetulle Prue-rouvalleen, kehoittaen tätä muistamaan että
viedeisessä huodeessa oli kuopaddava ufsheeri, joka saattoi kuulla
kaiken. Siitä huolimatta jatkoi Prue-rouva meluamistaan, nimittäen
Dickiä humalaiseksi hylyksi, ja sen keskeytti vasta kapteenin
kuorsaaminen.
Aamulla onneton uhri heräsi päänkivistykseen ja tajuntaan ja
yöllinen vuoropuhelu uudistettiin. "Miksi tuot kotiisi kapteeneja
päivälliselle, kun ei talossa ole ainuttakaan guineaa? Miten kykenen
tarjoamaan päivällisiä, kun et jätä minulle kolikkoakaan? Miten voin
mennä kummittelemaan Kensingtoniin keltaisessa satiinipuvussani
koko tuon hienon seuran eteen? Minulla ei ole mitään sopivaa ylleni
pantavaa, ei minulla koskaan ole", ja niin jatkui kinailu. Kun
keskustelu alkoi käydä liian arkaluontoiseksi keskeytti mr. Esmond
niistämällä nenäänsä niin kovaa kuin suinkin voi, ja se merkkitoitotus
palautti rauhan. Mutta Dick oli herttainen, vaikka hänen vaimonsa
olikin epämiellyttävä, ja Dickin ilahuttamishalusta johtui, että
Castlewoodin ladyt, jotka eivät olleet pieniä tekijöitä hienossa
maailmassa, kutsuivat luokseen mrs. Steelen.
Kapteenin ja hänen rouvansa ohella tuli lukuisasti huomattavia
vieraita, ja Chelsean lady oli lähettänyt lakeijansa ja livreiansa
avustamaan Kensingtonin vaatimatonta palveluskuntaa. Vieraiden
joukossa oli kenraaliluutnantti Webb, Harryn hyvä päämies, jonka
leskivarakreivitär otti huostaansa ja joka loisti sametissa ja
kultanauhoissa. Ja siellä oli Harryn uusi tuttava, kunnianarvoisa herra
Henry St. John, kenraalin sukulainen, joka oli ihastunut lady
Castlewoodiin vielä enemmän kuin tämän tyttäreen. Siellä oli
kuningaskuntamme suurimpia aatelismiehiä, skotlantilainen herttua
Hamilton, jolle juuri oli annettu Brandonin herttuan arvo Englannissa.
Siellä oli myös kaksi muuta jalosukuista lordia torypuolueesta, lordi
Ashburnham ja eräs toinen, jonka olen unohtanut. Ja naisista
puhuakseni siellä oli hänen ylhäisyytensä Ormondin herttuatar ja
hänen tyttärensä lady Mary ja lady Betty, joista edellinen oli miss
Beatrixin virkatoveri kuningattaren hovinaisena.
"Kylläpä on suuri toryseurue!" kuiskasi kapteeni Steele Esmondille,
kun ennen päivällistä olimme kokoontuneet saliin. Tosiaankin oli
koko seura Steeleä lukuunottamatta sitä puoluetta.
Mr. St. John osoitti erikoista kohteliaisuutta mrs. Steelelle ja lumosi
tämän niin, että rouva sanoi toivovansa, että Steelekin olisi
torypuoluelainen.
"Tai ettekö haluaisi, että minä olisin whig?" kysyi mr. St. John.
"Kyllä te, rouva, voitte kääntää miehen miksi tahansa?"
"Jos mr. St. John joskus tulee Bloomsbury Square'iin, niin kyllä
opetan teille sen, mitä tiedän", sanoi mrs. Steele luoden kaunoiset
silmänsä maahan. "Tunnetteko te Bloomsbury Squarea?"
"Tunnenko Mallia? Tunnenko Oopperaa? Bloomsburyhan on itse
muodin keskus", virkkoi mr. St. John. "Se on rus in urbe
[maaseutukaupungissa]. Siellä on puistoja, jotka ulottuvat
Hampsteadiin asti, ja joka puolella palatseja — Southampton House
ja Montague House."
"Ja siellä te ilkimykset taistelette kaksintaisteluja!" huudahti mrs.
Steele.
"Joiden aiheena ovat naiset", virkkoi hänen huvittajansa. "Onko
Dick hyvä miekankäyttäjä, rouva? Miten ihastuttava Tatler onkaan!
Me kaikki tunsimme teidän kuvanne 49:ssä numerossa, ja siitä
saakka kuin sen luin, olen kuollakseni halunnut tutustua teihin.
'Suotakoon Aspasialle ensimmäinen sija rakkauden sulosarjassa.'
Eikö siinä luvussa ollut niin? 'Tässä hienosti sivistyneessä naisessa on
rakkaus pysyvä ilmiö, vaikka se ei koskaan ole tarkoituksellista.
Mutta vaikka hänen olemuksessaan on paljon enemmän lempeätä
pyyntöä kuin käskemistä, merkitsee hänen näkemisensä heti
luopumista huonosta käytöksestä ja häntä rakastaminen on jaloa
kasvatusta.'"
"Ah, tosiaankin!" sanoi mrs. Steele, joka ei näyttänyt ymmärtävän
sanaakaan siitä, mitä tuo herra sanoi.
"Kukapa saattaisi jäädä jalostamattomaksi sellaisen rakastajattaren
alaisena?" jatkoi mr. St. John yhä ritarillisena kumartaen.
"Rakastajattaren! Hyvänen aika, sir", huudahti kapteenin rouva.
"Jos tarkoitatte minua, sir, niin tietäkää, että olen kapteenin vaimo."
"Kyllä me sen kaikki tiedämme", vastasi mr. St. John, pysytellen
yhä kovin vakavana; ja Steele keskeytti heidät sanoen: "Minä en
kirjoittanut sitä lehteä mrs. Steelestä — vaikka hän totisesti
ansaitsee kaikki ne kohteliaisuudet, joita kykenen hänelle
osoittamaan — vaan lady Elizabeth Hastingsista."
"Ja minä kun olen aina luullut, että se oli mr. Congreven
kirjoittama", huudahti mr. St. John, osoittaen, että hän tiesi
enemmän tuosta aineesta kuin hän tahtoi mr. Steelelle näyttää sekä
senkin, kuka oli se aihe, jota mr. Bickerstaffe edusti.
"Tom Boxer sanoi kyllä niin Observator lehdessään Mutta Tomin
oraakkeli erehtyy usein", huudahti Steele.
"Mr. Boxer ja mieheni olivat kerran ystäviä ja kun kapteeni oli
kuumesairaana ei kukaan olisi voinut olla ystävällisempi kuin mr.
Boxer, joka tapasi tulla hänen vuoteensa ääreen joka päivä, ja hän
se toikin tohtori Arbuthnot'in, joka paransi mieheni", kuiskasi mrs.
Steele.
"Niinkö, rouva! Miten perin mielenkiintoista", virkkoi mr. St. John.
"Mutta kun kapteenin viimeinen näytelmä ilmestyi, ei mr. Boxer
kiinnittänyt siihen mitään huomiota — tiedättehän, että hän on mr.
Congreven miehiä eikä anna koskaan sanaakaan toiselle puolueelle
— ja se suututti kovin miestäni."
"Vai on mr. Boxer mr. Congreven miehiä!" virkkoi mr. St. John.
"Mr. Congrevella on vallan tarpeeksi omintakeista neroa", virkkoi
mr. Steele. "Kukaan ei ole koskaan kuullut minun kadehtivan häneltä
tai keltään muultakaan heidän osaansa."
"Olen kuullut, että mr. Addison on yhtä kuuluisa älyniekkana kuin
runoilijanakin", sanoi mr. St. John. "Onko se totta, että teidän Tatler-
lehdessänne, mr. Steele, on hänenkin käsialaansa?"
"Käsittelipä hän ylevää tai leikillistä ainetta, niin ei kukaan voi
hänelle vetää vertoja", huomautti Steele.
"Pötyä, Dick, tuo sinun Addisonisi!" sanoi hänen vaimonsa —
"semmoinen herra, joka on niin kopea ja pitää nyt nokkaansa niin
pystyssä. Toivon, että arvoisa lady ajattelee kuten minäkin. Minä en
voi kärsiä noita kovin vaaleita miehiä, joilla on valkoiset silmäripset
— tumma mies on minun makuuni." (Kaikki pöydän ääressä olevat
tummat miehet osoittivat suosiotaan ja kumarsivat mrs. Steelelle
tämän kohteliaisuuden johdosta). "Ja mitä tähän mr. Addisonian
tulee", jatkoi lady, "niin hän tulee toisinaan päivälliselle kapteenin
luo, mutta ei sano halaistua sanaakaan minulle. Ja sitten he menevät
yläkertaan, humalaisina molemmat, juomaan teetä. Kyllä minä
muistan mr. Addisonin, kun hänellä oli vain yksi takki, ja siinäkin oli
paikka kyynärpäässä."
"Niinkö tosiaankin — paikka kyynärpäässä? Se on
mielenkiintoista", sanoi mr. St John. "On suloista kuulla toisesta
kirjailijasta toisen kirjailijan suloiselta vaimolta."
"Niin, kyllä minä voisin kertoa teille miten paljon hyvänsä niistä",
jatkoi liukaskielinen rouva. "Mutta mitä luulette kapteenin nyt
keksineen? — Pienen kyssäselkäisen olennon — pienen
peukaloispahaisen, jota hän sanoo runoilijaksi — pienen
paavilaiskakaran."
"Sh, täällä huoneessa on niitä kaksi", kuiskasi hänen toverinsa.
"Niin, minä kutsun häntä paavilaiseksi, koska hänen nimensä on
'Pope'", virkkoi lady. "Minä vain lasken leikkiä siten. Ja tämä pieni
kääpiöolento on kirjoittanut paimenrunoelman — semmoisista
paimenpojista ja — tytöistä, tiedättehän."
"Paimenella tulee olla jotain käyrää", huomautti emäntäni nauraen
toiselta puolelta pöytää; siihen tokaisi mrs. Steele: "Minä en tiedä,
mutta kapteeni toi kotiimme tämän kumman pikku olion, kun olin
lapsivuoteessa saatuani ensimmäisen poikani, ja oli ihan jumalan
onni, ettei hän ollut tullut ennen. Ja Dick piti suurta melua hänen
nerollisuudestaan, ja piti alinomaa suurta hälinää kaikennäköisestä
hölynpölystä."
"Mistä Tatler-julkaisusta pidätte enin, mrs. Steele?" kysäisi mr. St.
John.
"Minä en ole lukenutkaan muuta kuin yhden, ja se on kaikki
paljasta roskaa, sir", vastasi rouva. "Se on sellaista pötyä
Bickerstaffista ja Distaffista ja Quarterstaffista. Mutta kapteenihan
jatkaa yhä burgundilaisen nauttimista — minä tiedän, että hän
humaltuu ennenkuin lopettaa — kapteeni Steele!"
"Juon silmäisi maljan, kultaseni", vastasi kapteeni joka näytti
pitävän vaimoaan ihastuttavana ja ottavan täydestä kaikki ne
satiiriset kohteliaisuudet, joita mr. St. John hänen vaimolleen lateli.
Koko tämän ajan oli hovineiti ponnistellut saadakseen mr.
Esmondin puhumaan ja epäilemättä hän piti tätä ikävänä otuksena.
Sillä jostakin erehdyksestä johtui, että juuri kun Esmond aikoi
kiiruhtaa tyhjäksi jääneeseen paikkaan, hän joutui kauaksi Beatrixin
istuimesta; Beatrix istui lordi Hamiltonin ja lordi Ashburnhamin
välissä ja kohautti hurmaavia valkeita olkapäitään ja loi serkkuunsa
katseen aivankuin sanoakseen: "Sääli minua". Herttua ja hänen
nuori vierustoverinsa joutuivat pian hyvin vilkkaaseen yksityiseen
keskusteluun. Miss Beatrix ei voinut olla käyttämättä silmiensä
viehätysvoimaa paremmin kuin aurinko voi estyä paistamasta ja
polttamasta niitä, joihin se paistaa. Ensimmäisen ruokalajin tarjoilun
päätyttyä tuntui päivällinen Esmondista pitkäveteiseltä; liemen
tarjoilun alettua luuli hän heidän olleen jo tuntikausia pöydän
ääressä; ja kun käytiin käsiksi jälkiruokiin ja hyytelöihin, ajatteli hän,
etteivät ne koskaan loppuisi.
Viimein nousivat naiset, ja Beatrix loi viehättävän katseen
herttuaansa, kun he vetäytyivät pois. Uusi pullo ja laseja tuotiin ja
juotiin maljoja. Mr. St. John pyysi hänen ylhäisyyttään Hamiltonin
herttuaa ja toisia juomaan hänen ylhäisyytensä Brandonin herttuan
terveydeksi. Toinen lordi esitti kenraali Webbin maljan "ja saakoon
hän aseman, jonka maailman urhoollisin upseeri ansaitsee". Mr.
Webb kiitti vieraita, onnitteli adjutanttiaan ja taisteli taas uudestaan
kuuluisan taistelunsa.
"Il est fatiguant", kuiskasi mr. St. John, "avec sa trompete de
Wynendael." [Hän väsyttää Vynendaelin-toitotuksellaan.]
Kapteeni Steele, joka ei ollut meidän puolellamme, ehdotti
lojaalisesti
Marlborough'n herttuan, aikamme suurimman sotapäällikön maljan.
"Juon suurimman sotapäällikön maljan koko sydämelläni", sanoi
mr. Webb; "sitä hänen ominaisuuttaan vastaan ei ole mitään
muistuttamista. Minä tyhjennän maljan sotapäällikölle enkä
herttualle, mr. Steele." Ja jäykkä vanha herra tyhjensi lasinsa; tähän
vastasi Dick siten, että täytti ja tyhjensi kaksi viinilasia, toisen
sotapäällikön ja toisen herttuan kunniaksi.
Ja nyt hänen ylhäisyytensä Hamiltonin herttua nousi silmät
säteilevinä (olimme kaikki juoneet melko vapaasti) ja ehdotti maljan
rakastettavalle, verrattomalle miss Beatrix Esmondille. Joimme sen
kaikki eläköönhuudoin ja kovin innostuneina, erittäinkin lordi
Ashburnham.
"Ikävää, että jo ennestään on olemassa Hamiltonin herttuatar";
kuiskasi St. John, joka joi enemmän viiniä ja oli kuitenkin tasaisempi
kuin useimmat muut; ja me menimme vierashuoneeseen, jossa
naiset olivat teen ääressä. Meidän täytyi jättää Dick-parka yksin
ruokapöydän ääreen, jossa hän tavoitteli säkeitä "Sotaretkestä",
missä suurin runoilija oli ikuistanut maailman suurimman
sotapäällikön. Ja Harry Esmond löysi hänet puolentunnin kuluttua
vielä kehittyneemmässä humaluuden tilassa itkemässä Tom Boxerin
petollisuutta.
Harry-paralle oli vierashuone aivan pimeä huolimatta upeasta
valaistuksesta. Beatrix tuskin puhutteli häntä. Kun herttua poistui,
alkoi hän viehätellä lähinnä ylhäisintä ja kiehtoi nuorta lordi
Ashburnhamia kaikella silmiensä tulella ja älynsä viehätyskeinoilla.
Suurin osa seuraa asettui korttien ääreen; ja mr. St. John,
haukoteltua vasten naamaa mrs. Steelelle, jota hän ei enää halunnut
viehättää ja keskusteltuaan loistavimpaan, vilkkaimpaan tapaansa
lady Castlewoodin kanssa, jonka hän julisti kauniiksi sekä paljon
korkeamman kauneuden omaajaksi kuin tämän tyttären, heitti
jäähyväiset ja poistui. Jäljelle jääneet vieraat seurasivat nopeasti
häntä, viimeiseksi lordi Ashburnham, joka lähetti tulisia katseita
hymyilevään nuoreen viettelijättäreen, joka oli loihtinut lumoihinsa
muitakin sydämiä.
Mr. Esmond piti läheisenä sukulaisena epäilemättä sopivana viipyä
muita kauemmin talossa; hän viipyi vielä kun vaunut olivat vierineet
pois — kun hänen tätinsä leski varakreivittären kantotuoli ja
soihdunkantaja olivat hälvenneet pimeyteen Chelsea'hen päin ja kun
kaupunkilaiset, jotka olivat tulleet ihmettelemään tavatonta
kantotuolien, vaunujen, lakeijain ja soihdunkantajani paljoutta, olivat
menneet vuoteisiinsa. Onneton miesparka viipyi vielä hiukan aikaa
nähdäkseen, soisiko tyttö hänelle hymyn tai lohduttavan
jäähyväissanan. Mutta Beatrixin aamuinen innostus oli joko
kokonaan häipynyt tai häntä huvitti olla toisenlaisella tuulella. Hän
alkoi laskea leikkiä lady Bettyn huolimattomasta pukeutumisesta ja
matki sivistymätöntä mrs. Steeleä; ja sitten hän pani pienen kätensä
suulleen ja haukotteli, sytytti vahakynttilän ja kohautti olkapäitään ja
teki mr. Esmondille viehkeän kumarruksen poistuen huoneesta.
"Päivä alkoi niin hyvin, Henry, että olisin toivonut sen loppuvan
paremmin", se oli ainoa lohdutus, minkä Esmond-paran lempeä
emäntä kykeni hänelle antamaan; ja kun Esmond käveli pimeässä
yksinään kotiin, tunsi hän sydämessään katkeraa tuskaa ja ajatteli
mikein kapinoiden sitä uhria, minkä hän oli tehnyt. "Beatrix ottaisi
minut", ajatteli hän, "jos minulla vain olisi arvo, jonka voisin hänelle
antaa. Kun en vain olisi antanut tuota lupausta hänen isälleen, saisin
arvoni ja rakastettuni myöskin."
Luulenpa, että miehen turhamaisuus on väkevämpi kuin mikään
muu intohimo hänessä, sillä nytkin punastun, kun muistan noiden
kaukaisten päivien nöyryytyksiä, joiden muisto yhä kirveltää, vaikka
tyhjiin rauenneen lemmen hehku on häipynyt jo useita
vuosikymmeniä sitten. Kun kirjoittajan jälkeläiset tulevat lukemaan
tätä hänen muistokokoelmaansa, niin ovatkohan he kokeneet
elämässään samanlaisen häviön ja häpeän? Lienevätkö he koskaan
polvistuneet naisen eteen, naisen, joka on kuunnellut heitä ja
leikkinyt heidän kanssaan ja nauranut heille — naisen, joka viitaten
heille mairitellen ja hyväillen, myöntymys säteillen silmistään, on
puijannut heidät polvilleen ja kääntänyt heille selkänsä ja poistunut.
Kaikki tämä häpeä täytyi mr. Esmondin kestää. Ja hän alistui ja
kapinoi, mutta palasi taas pian ryömien saadakseen lisää
samanlaista.
Tämän juhlan jälkeen vierivät nuoren lordi Ashburnhamin vaunut
yhtämittaa Kensington Square'iin ja sieltä pois; hänen äitinsä tuli
vierailulle Esmondin emännän luokse. Ja saattoi olla varma siitä, että
tapasi tuon nuoren herran joka viikko uudessa puvussa sekä kaiken
sen loiston koristamana, minkä hänen räätälinsä tai korukauppiaansa
kykeni hänelle hankkimaan, jokaisessa kaupungin tilaisuudessa,
missä vain hovineitimme oli. Lordi oli uupumattoman kohtelias mr.
Esmondille — pyysi häntä päivälliselle ja tarjosi hänelle ratsuhevosia
ja antoi hänelle tuhansia outoja osoituksia kunnioituksestaan ja
hyvänsuopaisuudestaan. Sitten, eräänä iltana kahvilassa, jonne lordi
tuli aika lailla höpertyneenä ja kiihtyneenä juomisesta, hän syöksähti
mr. Esmondin luokse ja huudahti: "Onnitelkaa minua, paras everstini;
olen miehistä onnellisin."
"Miehistä onnellisin ei kaipaa parhaan everstin onnitteluja", virkkoi
Esmond. "Mikä on tämän autuaallisen onnen aihe?"
"Ettekö ole kuullut?" kysyi lordi. "Ettekö tiedä? Minä luulin, että
siellä kerrotaan teille kaikki: Jumalainen Beatrix on luvannut tulla
omakseni."
"Mitä!" huudahti mr. Esmond, joka oli viettänyt onnellisen hetken
Beatrixin seurassa juuri sinä aamuna — oli kirjoittanut hänelle
säkeitä, joita hän oli laulanut klaverin ääressä.
"Niin", sanoi lordi, "minä odotin häntä tänään. Minä näin teidän
kävelevän Knightsbridge'iin päin, kun ajoin sinne vaunuissani. Hän
näytti niin ihanalta ja puhui niin lempeästi, että en voinut olla
polvistumatta ja — ja — minä olen totisesti maailman onnellisin
mies. Olen kovin nuori, mutta hän vakuuttaa, että minä vanhenen.
Ja tiedättehän, että tulen täysi-ikäiseksi neljän kuukauden kuluttua,
ja iän ero meidän välillämme on kovin pieni. Olen niin onnellinen.
Tahtoisin tarjota vierailleni jotain. Ottakaamme pullo — tai vaikkapa
tusina — ja juokaamme Englannin suloisimman naisen malja."
Esmond jätti nuoren lordin tyhjentelemään maljoja ja harhaili
Kensingtoniin kysymään, oliko uutinen totta. Se oli liiankin totta:
hänen emäntänsä surullinen, säälivä ulkomuoto ilmaisi hänelle
kaikki. Ja sitten kertoi lady mitä yksityiskohtia hän siitä tiesi ja miten
nuori lordi oli esittänyt kosintansa puoli tuntia Esmondin poistumisen
jälkeen sinä aamuna ja juuri siinä huoneessa, missä vielä oli
klaverilla laulu, jonka Esmond oli kirjoittanut ja jonka he olivat
yhdessä laulaneet.
III KIRJA.
KUVAA MR. ESMONDIN VIIMEISET
VAIHEET ENGLANNISSA.
I luku.
TAISTELUNI JA VAIVANI PÄÄTTYVÄT.
Kuumeinen halu voittaa jonkun verran mainetta, halu, mikä
Esmondia oli kannustanut, häipyi nyt, kun hän jo oli saavuttanut
osan siitä, mitä oli toivonut ja kun hänen kunnianhimonsa suuri
vaikutin oli poissa. Hänen halunsa soturin kunniaan johtui toivosta,
että se koroittaisi häntä Beatrixin silmissä. Aateluuden ja rikkauden
jälkeen se oli ainoa arvolaji, jota Beatrix piti arvossa. Se oli panos,
minkä saattoi helpoimmin sekä voittaa että hävitä. Sillä lakimiehen
ura on kovin pitkä peli ja vaatii koko elämän harjoittamiseensa, ja
kirjailijana tai hengenmiehenä huomatuksi tuleminen ei olisi
vähääkään auttanut poloisen herran pyrkimyksiä. Hänellä ei siis ollut
muuta osaa ehdolla kuin punatakin osa, ja niinpä hän näytteli sitä.
Ja tästä todellakin johtui hänen nopea edistyksensä, hän kun pani
itsensä vaaralle alttiiksi enemmän kuin useimmat miehet ja uskalsi
enemmän voittaakseen enemmän. Onko hän ainoa mies, joka on
asettanut elämänsä panosta vastaan, joka ehkä ei ole voittamisen
arvoinen? Toinen uskaltaa elämänsä (ja toisinaan myös kunniansa)
rahapinkkaa tai metriä sinistä ritarinauhaa vastaan tai istuinta
vastaan parlamentissa; ja toiset taas tekevät sen nauttien ja kiihtyen
itse urheilusta — kuten tekee metsästäjäjoukko, josta kukin koettaa
huutaa ja nelistää kovemmin kuin toiset likaisen ketun hännässä,
ketun, joka on oleva etummaisen onnellisen voittajan palkinto.
Kun eversti Esmond sai kuulla tämän uutisen Beatrixin
kihlauksesta, alistui hän kohtaloonsa ja päätti luopua miekastaan,
joka ei nyt enää voisi voittaa hänelle mitään, mistä hän välitti; ja
tällaisella synkällä mielellä hän päätti erota rykmentistään. Tämä
ihastutti suuresti kapteenia, joka oli häntä lähinnä arvossa ja joka
sattui olemaan varakas nuori herra; hän maksoi ihastuneena mr.
Esmondille tuhannen guineaa Esmondin majurin arvosta Webbin
rykmentissä ja sai kuulan päähänsä seuraavassa taistelussa. Esmond
ei varmaankaan olisi ollut pahoillaan, jos hän olisi joutunut saamaan
saman kohtalon. Hän oli nyt enemmän Ritari Murhemuoto kuin hän
oli milloinkaan ennen ollut. Hänen surullisuutensa teki hänet
varmaankin aivan inhoittavaksi hänen leiriystävilleen, jotka yleensä
pitävät iloisesta veikosta ja pilkkaavat synkkää soturia, joka aina vain
huokailee kotona olevan Dulcinean vuoksi.
Molemmat Castlewoodin ladyt hyväksyivät mr. Esmondin
luopumisen sotaväestä; ja Esmondin kelpo kenraali hyväksyi hänen
eroamishalunsa ja avusti häntä tämän toimenpiteen ratkaisussa, joka
toi sievoisen summan Esmondin taskuun. Mutta kun ylipäällikkö
palasi kotiin ja hänen oli pakko vasten tahtoaankin määrätä
kenraaliluutnantti Webb erään Flanderissa olevan armeijamme
divisionan johtoon, pyysi kenraaliluutnantti eversti Esmondia niin
hartaasti adjutantikseen ja sotakirjurikseen, ettei Esmond voinut
antaa kieltoa hyvälle päämiehelleen, ja hän asettui uudestaan
paikkaansa. Mitkä ainaiset tuskat ja pelot [Mitkä tosiaankin? Psalmi
91: 2, 3, 7. — R.E.] ja huolet raastivatkaan vaimojen ja äitien
sydämiä noina kauhun päivinä, jolloin jokainen Gazette toi surman ja
sodan sanomia ja jolloin aina, vaikka äskeinen mielen jännitys olikin
häipynyt ja rakastettu säästynyt, kuitenkin jäi kytemään ajatus, että
vielä voitiin taistella taistelu, josta seuraava Flanderin kirje toisi
tietoja. Siten noiden lempeitten olentoparkain täytyi kärsiä ja vavista
koko sodan ajan. Miten suurta pelkoa Esmondin emäntä mahtoikin
tuntea (ja tuon naisista helläsydämisimmän on täytynyt tuntea
niiden katkeruutta molempien poikiensa vuoksi, niin hän heitä
nimitti), niin ei hän milloinkaan antanut sen ilmetä olennossaan,
vaan hän peitti huolensa samaten kuin hän peitti laupeudentyönsä ja
hartautensa. Vain sattumalta joutui Esmond näkemään ollessaan
kävelyretkellä Kensingtonissa, emäntänsä tulevan siellä olevasta
köyhästä majasta, ja Esmond sai kuulla, että tällä oli kokonainen
joukko köyhiä holhokkeja, joiden luona hän kävi ja joita hän lohdutti
heidän sairaudessaan ja köyhyydessään ja jotka joka päivä
siunasivat häntä. Lady otti osaa aamujumalanpalvelukseen joka
päivä (vaikka hän erittäinkin sunnuntaisin järjesti ja edisti iloisuutta
ja viatonta leikkiä pienessä perhepiirissään). Ja muistiinpanoista,
joita hän näihin aikoihin on erääseen päiväkirjaansa tehnyt, sekä
uskonnollisista, kirjoitelmista, mitkä ovat laaditut suloisen
koruttomassa innostuksessa, ilmenee miten hellä sydän hänellä oli,
miten nöyrä ja hurskas mieli, mitä huolia hän kärsi vaiteliaana ja
miten hartaan luottavaisena hän jätti ne, joita hän rakasti, kuolon ja
elon kaikkivoivan Jakajan hoivaan.
Chelsean varakreivitär, Esmondin uusi emintimä, oli nyt tullut
ikään, jossa pelko toista puoluetta kohtaan ei suuresti häiritse lepoa.
Hän piti valteista enemmän kuin useimmista muista asioista maan
päällä. Hän oli kyllä horjumaton omassa uskossaan, mutta hänen
katkeruutensa ei silti enää ollut kovinkaan polttava meidän
uskoamme kohtaan. Hänellä oli kovin hyväluontoinen, myöntyväinen
ranskalainen rippi-isä, jonka nimi oli monsieur Gauthier. Hän oli
maailmanmies ja saattoi ryhtyä kortinlyöntiin tuomiorovasti
Atterburyn kanssa, joka oli Chelsean varakreivittären naapuri, ja
samoin oli rippi-isä hyvissä väleissä koko korkeakirkollisen puolueen
kanssa. Epäilemättä monsieur Gauthier tiesi, mikä asema olisi
kuulunut Esmondille, sillä hän oli kirjevaihdossa Holtin kanssa ja
kohteli aina eversti Esmondia erikoisen kunnioittavasti ja
ystävällisesti, mutta eversti ja apotti eivät, syystä kyllä, milloinkaan
keskustelleet tästä asiasta, ja niin he pysyivät erittäin hyvinä
ystävinä.
Kaikki Chelsean varakreivittären kestivieraat olivat toryja ja
korkeakirkollisia. Madame Beatrix oli yhtä touhuissaan kuninkaasta
kuin hänen vanhempi sukulaisensakin: hän kantoi kuninkaan kuvaa
sydämellään; hänellä oli kiehkura kuninkaan hiuksia; hän vakuutti,
että kuningas oli ruhtinaista sorretuin, urhoollisin, kyvykkäin,
onnettomin ja kaunein. Steele, joka oli riidoissa kovin useitten tory-
ystäviensä kanssa, ei kuitenkaan milloinkaan Esmondin kanssa, sanoi
tavallisesti Esmondille, että tämän sukulaisen talo oli torypuolueen
juonittelijain pesäpaikka, että Gauthier oli vakoilija, että Atterbury oli
vakoilija ja että kirjeitä alinomaa lähti siitä talosta kuningattarelle St.
Germain'iin. Tähän Esmond nauraen vastasi, että armeijassa
vakuutettiin myöskin Marlborough'n herttuan olevan vakoojan ja että
tämä oli yhtä paljon kirjevaihdossa kuningasperheen kanssa kuin
paras jesuiitta. Ja niin oli Esmond, ottamatta kovin innostuneena
osaa yleiseen väittelyyn, liittynyt lujasti perheensä jäseniin. Hänestä
oli selvää, että kuningas Jaakko III oli eittämättömästi Englannin
oikea kuningas ja että oli parempi saada hänet kuin joku
muukalainen meitä hallitsemaan hänen sisarensa kuoltua. Kukaan ei
enää ihaillut kuningas Wilhelmiä — sankaria ja valloittajaa, miehistä
urhoollisinta, oikeudenmukaisinta ja viisainta. Sillä hän valloitti
maamme miekalla ja piti sen hallussaan ja hallitsi sitä aivan samalla
oikeudella kuin sitä oli pitänyt hallussaan suuri Cromwell, joka oli
oikea ja suuri hallitsija, mutta että muukalainen, itsevaltias
saksalainen ruhtinas, joka sattumalta polveutui kuningas Jaakko
I:stä, oli ottava haltuunsa tämän valtakunnan, tuntui mr. Esmondista
hirveältä vääryydeltä — ainakin oli jokaisella englantilaisella oikeus
panna vastalauseensa, ja ennen muita englantilaisella ruhtinaalla,
laillisella perillisellä. Ketäpä elinvoimaista miestä ei innostaisi
sellainen asia? Kukapa kelpo mies, jolla oli tarjona sellainen kruunu,
ei taistelisi sen puolesta? Mutta tuo kilpailu oli kohtalokasta. Tuo
ruhtinas oli itse itseään vastaan vihollisena, jota hän ei voinut
voittaa. Vaikka hänellä oli miekka, ei hän koskaan uskaltanut vetää
sitä esiin. Hän antoi tilaisuuksien liukua käsistään istuessaan
oopperatyttöjen sylissä tai nyyhkyttäessään pappien jaloissa
anteeksiantoa rukoillen; ja hänelle uhrattu sankarien veri ja kelpo
sydämien rakkaus, horjumattomuus, rohkeus ja uskollisuus menivät
hukkaan.
Mutta palatkaamme Chelsean ladyn luo. Kun hänen poikansa
Esmond ilmoitti hänen armolleen aikovansa lähteä seuraavalle
sotaretkelle, hyvästeli tämä hänet vallan hilpeästi ja istuutui
pelaamaan pikettiä kamarineitinsä kanssa, ennenkuin Esmond
kunnolla ennätti poistua huoneesta ollessaan viimeisellä vierailullaan.
"Kolme panosta kuningasta vastaan", olivat viimeiset sanat, jotka
Esmond kuuli hänen lausuvan; tuolta hyvältä ladyltä oli elämän peli
melkein lopussa, ja kolme kuukautta myöhemmin hän joutuikin
vuoteelle, jossa elämä hänestä tuskattomasti sammui, niin kirjoitti
abbe Gauthier Esmondille, joka silloin oli kenraalinsa kanssa Ranskan
rajalla. Lady Castlewood oli hänen luonaan hänen kuollessaan ja hän
oli myös kirjoittanut Esmondille. Mutta varmaankin ovat nämä kirjeet
joutuneet kaapparin saaliiksi postilaivasta, koska Esmond ei saanut
tietää mitään niiden sisällöstä, ennen kuin hän palasi Englantiin.
Lady Esmond oli testamentannut koko omaisuutensa eversti
Esmondille "korvaukseksi tälle tehdystä vääryydestä", niin oli
kirjoitettu jälkisäädökseen. Mutta hänen omaisuutensa ei ollut suuri,
ei koskaan ollut ollutkaan, ja kelpo varakreivitär oli, viisaasti kyllä,
käyttänyt suurimman osan siitä rahasta, minkä omisti, vuotuiseen
elinkorkoon, joka loppui hänen kuollessaan. Mutta Chelseassa oli
kuitenkin jäljellä talo ja kalusto, hopeat ja muotokuvat sekä eräs
rahamäärä ladyn kauppiaan, sir Josiah Childin huostassa, summa,
joka kokonaisuudessaan antoi lähes kolmensadan punnan vuotuiset
korot. Niinpä havaitsi mr. Esmond olevansa, joskaan ei rikas, niin
ainakin turvattu elinajakseen. Siellä olivat myös nuo kuuluisat
timantit, joiden oli huhuiltu olevan satumaisten summien arvoiset,
mutta kultaseppä ilmoitti, että niillä saisi vain neljätuhatta puntaa.
Nämä timantit eversti Esmond kuitenkin talletti, sillä hänellä oli niille
erikoinen tarkoitus; mutta Chelsean talo, kalusto, tavarat y.m.
lukuunottamatta muutamia esineitä, jotka hän pidätti itselleen,
myytiin hänen määräyksestään ja näin karttunut summa sijoitettiin
valtion obligatsioneihin, jotka tuottivat hänelle jo mainitun
kolmensadan punnan vuotuisen tulon.
Hän teki jälkisäädöksen, koska hänellä nyt oli omaisuutta, ja
lähetti sen Englantiin. Armeijamme oli nyt vihollisen, läheisyydessä ja
suurta taistelua odotettiin joka päivä. Tiedettiin, että ylipäällikkö oli
epäsuosiossa ja että kotona olevat puolueet olivat hänen kiihkeitä
vastustajiaan; ei ollut ainoatakaan panosta, jota ei tämä suuri ja
päättäväinen peluri olisi pannut alttiiksi palauttaakseen
menestyksensä aina kun hänen asemansa näytti epätoivoisimmalta.
Frank Castlewood oli eversti Esmondin lähettyvillä, sillä Esmondin
kenraali oli mielellään ottanut tuon nuoren aatelismiehen
esikuntaansa. Hänen linnoitusopiskelunsa Brysselissä olivat silloin jo
päättyneet. Se linna, jota hän oli piirittänyt, oli luullakseni
antautunut, ja lordi ei ollut ainoastaan marssinut hulmuavin lipuin
sinne vaan oli marssinut poiskin. Hän tapasi kertoa poikamaisista
kujeistaan herttaisen veikeästi ja hän oli armeijamme viehättävin
nuori syntipukki.
Tarpeetonta on sanoa, että eversti Esmond oli testamentannut
koko pienen omaisuutensa tälle pojalle. Eversti oli täysin vakuutettu
siitä, että seuraava taistelu lopettaisi hänen elämänsä; hän tuntui
väsyneensä aurinkoon ja oli valmis sanomaan sille ja maalle
jäähyväiset. Frank ei halunnut kuunnella toverinsa synkkiä
ennustuksia, vaan vakuutteli, että he viettäisivät hänen
syntymäpäiväänsä sinä syksynä Castlewoodissa sodan tauottua. Hän
oli kuullut kotona tapahtuneesta kihlauksesta. "Jos prinssi Eugene
menee Lontooseen", virkkoi Frank, "ja Trix saa hänet käsiinsä, niin
hän hylkää Ashburnhamin prinssin tähden. Kuuleppas, hänellä oli
tapana liehitellä Marlborough'n herttuata, kun hän oli vasta
neljätoistavuotias, ja iskeä silmää pikku Blandford-paralle. Minä en
vain häntä naisi, Harry, — en, vaikka hänen silmänsä olisivat puolta
suuremmat. Minua haluttaa huvitella. Kolmen tulevan vuoden
kuluessa aion nauttia kaikkia mahdollisia iloja. Sitten nain jonkun
hiljaisen, vakavan, kainon ja järkevän varakreivittären, metsästelen
ja sijoittaudun Castlewoodiin. Minä voin samalla edustaa koko
kreivikuntaa — ei, turkanen, sinä edustat kreivikuntaa. Sinulla on
sukumme lahjakkuus. Jumalan tähden, rakas Harry poikani, sinulla
on terävin pää ja hellin sydän koko armeijassa, kaikkihan sen
myöntävät. Ja mikäpä estäisi sinua menemästä Alahuoneeseen ja
tulemasta ministeriksi ja saamasta päärin arvoa ja muuta hyvää,
sittenkuin kuningatar kuolee ja kuningas palaa? Sinutko ammuttaisiin
ensi taistelussa? Tuhannen burgundipulloa siitä, että et saa
naarmuakaan! Mohunin haava on parantunut. Hän on nykyjään aina
korpraali Johnin seurassa. Näyttäköönpä vain inhottavan naamansa
niin minä syljen hänelle vasten silmiä! Minä sain opetusta isä —
kapteeni Holtilta Brysselissä. Se vasta mies on! Hän tietää kaiken."
Esmond pyysi Frankia olemaan varuillaan — isä Holtin tieto oli
vaarallista; Esmond ei näet vielä tietänyt miten pitkälle isä oli mennyt
nuoren oppilaansa ohjauksessa.
Sekä ranskalaiset että englantilaiset sanomalehtimiehet ja kirjailijat
ovat antaneet riittäviä selostuksia Blarignies'n eli Malplaquet'n
verisestä taistelusta, joka oli viimeinen ja vaikein niistä voitoista,
mitkä suuri Marlborough'n herttua saavutti. Tähän hirveään
kamppailuun otti osaa lähes kaksisataaviisikymmentä tuhatta miestä,
joista enemmän kuin kolmekymmentä tuhatta sai surmansa tai
haavoittui. (Liittoutuneet menettivät kaksi kertaa niin paljon omia
miehiään kuin he surmasivat ranskalaisia, jotka he voittivat). Hyvin
todennäköisesti tämä tavaton teurastus aiheutui siitä, että luottamus
suurta päällikköä kohtaan horjui kotimaassa ja hän aikoi palauttaa
sen voiton avulla. Jos sellaiset vaikuttimet saivat Marlborough'n
herttuan yrittämään niin tavatonta panosta ja panivat hänet
epätoivoissaan uhraamaan kolmekymmentä tuhatta miestä, jotta
hän vielä kerran voisi loistaa jossain Gazettessa ja hiukan kauemmin
säilyttää paikkansa ja eläkkeensä, niin sattuma teki tyhjäksi tuon
kauhean ja itsekkään suunnitelman. Voitto ostettiin hinnasta, jota ei
mikään kansa, olipa se miten kunnianhimoinen tahansa,
vapaaehtoisesti uhraa voitolle. Ranskalaisten urhoollisuus oli aivan
yhtä ihmeellinen kuin heidän ahdistajiensakin sankarillinen voima.
Me valloitimme paljon heidän lippujaan ja joitakuita tykkejä, mutta
meiltä jäi kaksikymmentä tuhatta maailman urhoollisinta soturia
juoksuhautojen peittämälle rintamalinjalle, josta vihollinen
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebooknice.com