SlideShare a Scribd company logo
Spring Start Here Learn What You Need And Learn
It Well 1st Edition Laurentiu Spilc download
https://ebookbell.com/product/spring-start-here-learn-what-you-
need-and-learn-it-well-1st-edition-laurentiu-spilc-34883312
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Spring Persistence A Running Start 1st Edition Paul Tepper Fisher
https://ebookbell.com/product/spring-persistence-a-running-start-1st-
edition-paul-tepper-fisher-4201510
Naruto Vol 69 The Start Of A Crimson Spring Masashi Kishimoto
https://ebookbell.com/product/naruto-vol-69-the-start-of-a-crimson-
spring-masashi-kishimoto-11518468
How To Start A Business Analyst Career 2nd Edition 2nd Edition Laura
Brandenburg
https://ebookbell.com/product/how-to-start-a-business-analyst-
career-2nd-edition-2nd-edition-laura-brandenburg-43232362
Star Spring
https://ebookbell.com/product/star-spring-35553234
Star Spring Bischoff David
https://ebookbell.com/product/star-spring-bischoff-david-8359318
A Maze Of Stars And Spring Water Bing Xin
https://ebookbell.com/product/a-maze-of-stars-and-spring-water-bing-
xin-48992526
Storm In The Desert Britains Intervention In Libya And The Arab Spring
Mark Muller Stuart
https://ebookbell.com/product/storm-in-the-desert-britains-
intervention-in-libya-and-the-arab-spring-mark-muller-stuart-42885888
Blazing Hot Spring A Blaze Family Romance Collection Fiona Starr Flirt
Club
https://ebookbell.com/product/blazing-hot-spring-a-blaze-family-
romance-collection-fiona-starr-flirt-club-44761374
The Star Harbor Series 4book Bundle Deep Autumn Heat Blaze Of Winter
Long Simmering Spring Slow Summer Burn Elisabeth Barrett
https://ebookbell.com/product/the-star-harbor-series-4book-bundle-
deep-autumn-heat-blaze-of-winter-long-simmering-spring-slow-summer-
burn-elisabeth-barrett-47048340
Spring Start Here Learn What You Need And Learn It Well 1st Edition Laurentiu Spilc
Spring Start Here Learn What You Need And Learn It Well 1st Edition Laurentiu Spilc
inside front cover
Spring Start Here
LEARN WHAT YOU NEED AND LEARN IT WELL
LAURENŢIU SPILCĂ
To comment go to liveBook
Manning
Shelter Island
For more information on this and other Manning titles go to
www.manning.com
Copyright
For online information and ordering of these and other Manning books, please visit
www.manning.com. The publisher offers discounts on these books when ordered in
quantity.
For more information, please contact
Special Sales Department
Manning Publications Co.
20 Baldwin Road
PO Box 761
Shelter Island, NY 11964
Email: orders@manning.com
©2021 by Manning Publications Co. All rights reserved.
No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
in any form or by means electronic, mechanical, photocopying, or otherwise, without prior
written permission of the publisher.
Many of the designations used by manufacturers and sellers to distinguish their products
are claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial
caps or all caps.
♾ Recognizing the importance of preserving what has been written, it is Manning’s policy to
have the books we publish printed on acid-free paper, and we exert our best efforts to that
end. Recognizing also our responsibility to conserve the resources of our planet, Manning
books are printed on paper that is at least 15 percent recycled and processed without the
use of elemental chlorine.
Manning Publications Co.
20 Baldwin Road Technical
PO Box 761
Shelter Island, NY 11964
Development editor: Marina Michaels
Technical development editor: Al Scherer
Review editor: Mihaela Batinić
Production editor: Andy Marinkovich
Copy editor: Michele Mitchell
Proofreader: Keri Hales
Technical proofreader: Jean-François Morin
Typesetter: Gordan Salinović
Cover designer: Marija Tudor
ISBN: 9781617298691
contents
foreword
preface
acknowledgments
about this book
about the author
about the cover illustration
Part 1 Fundamentals
1 Spring in the real world
1.1 Why should we use frameworks?
1.2 The Spring ecosystem
Discovering Spring Core: The foundation of Spring
Using Spring Data Access feature to implement the app’s persistence
The Spring MVC capabilities for developing web apps
The Spring testing feature
Projects from the Spring ecosystem
1.3 Spring in real-world scenarios
Using Spring in the development of a backend app
Using Spring in a test automation app
Using Spring for the development of a desktop app
Using Spring in mobile apps
1.4 When not to use frameworks
You need to have a small footprint
Security needs dictate custom code
Abundant existing customizations make a framework impractical
You won’t benefit from switching to a framework
1.5 What will you learn in this book
2 The Spring context: Defining beans
2.1 Creating a Maven project
2.2 Adding new beans to the Spring context
Using the @Bean annotation to add beans into the Spring context
Using stereotype annotations to add beans to the Spring context
Programmatically adding beans to the Spring context
3 The Spring context: Wiring beans
3.1 Implementing relationships among beans defined in the configuration file
Wiring the beans using a direct method call between the @Bean methods
Wiring the beans using the @Bean annotated method’s parameters
3.2 Using the @Autowired annotation to inject beans
Using @Autowired to inject the values through the class fields
Using @Autowired to inject the values through the constructor
Using dependency injection through the setter
3.3 Dealing with circular dependencies
3.4 Choosing from multiple beans in the Spring context
4 The Spring context: Using abstractions
4.1 Using interfaces to define contracts
Using interfaces for decoupling implementations
The requirement of the scenario
Implementing the requirement without using a framework
4.2 Using dependency injection with abstractions
Deciding which objects should be part of the Spring context
Choosing what to auto-wire from multiple implementations of an abstraction
4.3 Focusing on object responsibilities with stereotype annotations
5 The Spring context: Bean scopes and life cycle
5.1 Using the singleton bean scope
How singleton beans work
Singleton beans in real-world scenarios
Using eager and lazy instantiation
5.2 Using the prototype bean scope
How prototype beans work
Prototype beans in real-world scenarios
6 Using aspects with Spring AOP
6.1 How aspects work in Spring
6.2 Implementing aspects with Spring AOP
Implementing a simple aspect
Altering the intercepted method’s parameters and the returned value
Intercepting annotated methods
Other advice annotations you can use
6.3 The aspect execution chain
Part 2 Implementation
7 Understanding Spring Boot and Spring MVC
7.1 What is a web app?
A general overview of a web app
Different fashions of implementing a web app with Spring
Using a servlet container in web app development
7.2 The magic of Spring Boot
Using a project initialization service to create a Spring Boot project
Using dependency starters to simplify the dependency management
Using autoconfiguration by convention based on dependencies
7.3 Implementing a web app with Spring MVC
8 Implementing web apps with Spring Boot and Spring MVC
8.1 Implementing web apps with a dynamic view
Getting data on the HTTP request
Using request parameters to send data from client to server
Using path variables to send data from client to server
8.2 Using the GET and POST HTTP methods
9 Using the Spring web scopes
9.1 Using the request scope in a Spring web app
9.2 Using the session scope in a Spring web app
9.3 Using the application scope in a Spring web app
10 Implementing REST services
10.1 Using REST services to exchange data between apps
10.2 Implementing a REST endpoint
10.3 Managing the HTTP response
Sending objects as a response body
Setting the response status and headers
Managing exceptions at the endpoint level
10.4 Using a request body to get data from the client
11 Consuming REST endpoints
11.1 Calling REST endpoints using Spring Cloud OpenFeign
11.2 Calling REST endpoints using RestTemplate
11.3 Calling REST endpoints using WebClient
12 Using data sources in Spring apps
12.1 What a data source is
12.2 Using JdbcTemplate to work with persisted data
12.3 Customizing the configuration of the data source
Defining the data source in the application properties file
Using a custom DataSource bean
13 Using transactions in Spring apps
13.1 Transactions
13.2 How transactions work in Spring
13.3 Using transactions in Spring apps
14 Implementing data persistence with Spring Data
14.1 What Spring Data is
14.2 How Spring Data works
14.3 Using Spring Data JDBC
15 Testing your Spring app
15.1 Writing correctly implemented tests
15.2 Implementing tests in Spring apps
Implementing unit tests
Implementing integration tests
appendix A Architectural approaches
appendix B Using XML for the context configuration
appendix C A quick introduction to HTTP
appendix D Using JSON formatting
appendix E Installing MySQL and creating a database
appendix F Recommended tools
appendix G Recommended learning materials for further study
index
front matter
foreword
Born as an alternative to EJBs in the early 2000s, the Spring framework quickly overtook its
opponent with the simplicity of its programming model, the variety of its features, and its
third-party library integrations. The Spring ecosystem grew over the years into the
broadest and most mature development framework available in any programming
language. Its main competitor quit the race when Oracle stopped the evolution of Java EE
8, and the community took over its maintenance via Jakarta EE.
According to recent surveys (http://mng.bz/l9VB and http://mng.bz/B1Ar), Spring is the
framework underlying more than half of the Java applications. This fact builds up an
enormous codebase that makes it critical for any Java developer to learn Spring, as it’s
inevitable you’ll encounter this technology in your career. I’ve been developing applications
with Spring for 15 years, and today the teams that I train in hundreds of companies are
almost all using Spring.
The reality is that despite being so popular, it’s pretty hard to find quality introductory
material. The reference documentation is thousands of pages long, describing all the
subtleties and details that could be helpful in very specific scenarios, so it’s not an option
for a newcomer. While online videos and tutorials typically fail to engage the student, very
few books capture the essence of Spring framework, often spending long pages debating
topics that prove to be irrelevant to the problems faced in modern application development.
With this book, however, it’s very hard to find anything to remove; all the concepts covered
are recurring topics in the development of any Spring application.
The reader is gently brought to a level sufficient to become rapidly productive in a project
based on the Spring framework. My own experience training thousands of employees
showed me that the vast majority of developers working with Spring today don’t see the
ideas as clearly as this book paints them. Furthermore, developers are unaware of the
many pitfalls about which this book warns its readers. In my opinion, this book is a must-
read for any developer starting on their first Spring project.
The attention with which Laurenţiu anticipates the typical questions occurring in the
reader’s mind proves his extensive experience teaching Spring in class. This teaching
fluency allows the author to adopt a personal, warm tone that makes this book an effortless
and pleasant read. The book has a clear, sharp structure, and I really loved how complex
topics were progressively revealed and explained and reiterated in subsequent chapters.
This book shines in that the reader is also introduced to fundamental concerns regarding a
legacy project using the Spring framework. In an ecosystem dominated by Spring Boot, I
find it very useful to sneak a peek under the hood. On the other end, the book also gently
introduces the reader to last-generation technologies, like Feign clients and even reactive
programming.
I wish you a pleasant reading, and never hesitate to get your hands dirty with some code
whenever you think things get complicated.
—Victor Rentea
Java champion, trainer, and consultant
preface
Sharing knowledge and creating learning material is a hobby for me. In addition to being a
software developer, I’m also a teacher. As a Java trainer since 2009, I’ve taught Java to
thousands of developers with various levels of experience, from university students to
experienced developers in large corporations. In the past few years, I’ve come to consider
Spring a must-learn for beginners. Apps today are no longer implemented with vanilla
languages—almost everything relies on frameworks. Since Spring is the most popular
application framework in the Java world today, Spring is something a developer needs to
learn in their first software development steps.
In teaching Spring to beginners, I’ve realized that it is still treated as something you learn
only when you already have some experience coding. When I started writing Spring Start
Here, there were already plenty of tutorials, books, and articles on the topic, but my
students continued to tell me they found those materials hard to understand. I realized the
problem was not that the existing learning material wasn’t excellent, but that there was no
dedicated study guide for an absolute beginner, so I decided to write a book that doesn’t
consider Spring something you learn after you have some experience, but instead
something you can learn with minimal foundational knowledge.
Technology changes quickly. But it’s not only the technology changing. We also need to
consider how we can improve the way we teach these technologies. Some years ago, one
would start learning the language fundamentals and get employed as a developer without
even knowing what a framework is. But today, these things are different. Learning all the
details of a language up-front is no longer the way to quickly develop the skills you need to
work in a software development team. Now, I recommend developers start with the
fundamentals and, once they feel comfortable with the basics, start learning an application
framework. Spring is, in my opinion, the best application framework to start learning.
Understanding the Spring basics also opens doors to learning other technologies and
changes the old, linear learning approach into something that looks more like a tree—and
each branch of the tree is a new framework you learn in parallel with others.
I designed Spring Start Here to be the book you want to start learning the Spring
framework with. This book leads you step-by-step, providing you with all the essential
theoretical knowledge, accompanied by examples that practically apply the discussed
topics. I hope this book will bring significant value to you, the reader, and help you quickly
boost your Spring knowledge and open doors for further learning.
acknowledgments
This book wouldn’t be possible without the large number of smart, professional, and
friendly people who helped me throughout its development process.
First, a big thank you to my wife, Daniela, who was always there for me, and whose
valuable opinions, continuous support, and encouragement were a huge help to me.
I’d also like to express my gratitude and send special thanks to all the colleagues and
friends who helped me from the very first table of contents and proposal with their valuable
advice.
A big thank you goes to the entire Manning team for their huge help in making this book a
reality. I especially want to recognize Marina Michaels, Al Scherer, and Jean-François Morin
for always being incredibly supportive and professional. Your advice has brought great
value to this book.
I’d like to thank my friend Ioana Göz for the drawings she created for the book. She turned
my thoughts into the cartoons in the book.
I also want to express my appreciation to all the reviewers who provided such useful
feedback at every step. To Alain Lompo, Aleksandr Karpenko, Andrea Carlo Granata,
Andrea Paciolla, Andres Damian Sacco, Andrew Oswald, Bobby Lin, Bonnie Malec, Christian
Kreutzer-Beck, Daniel Carl, David Lisle Orpen, DeUndre’ Rushon, Harinath Kuntamukkala,
Håvard Wall, Jérôme Baton, Jim Welch, João Miguel Pires Dias, Lucian Enache, Matt D.,
Matthew Greene, Mikael Byström, Mladen Knežic´, Nathan B. Crocker, Pierre-Michel Ansel,
Rajesh Mohanan, Ricardo Di Pasquale, Sunita Chowdhury, Tan Wee, and Zoheb Ainapore,
your input has made this a much better book.
Finally, a special thank you to my friends, Maria Chiţu, Andreea Tudose, Florin Ciuculescu,
and Daniela Ileana for advising me along the way.
about this book
Since you’ve opened this book, I assume you’re a software developer in the Java ecosystem
who found out it’s useful to learn Spring. This book teaches you the Spring foundations,
assuming you know nothing in the first place about frameworks and, of course, about
Spring.
You’ll start with what a framework is and then gradually learn the basics of Spring with
applied examples. You will not only learn to use the framework’s components and
capabilities, but you’ll also learn the essentials of what happens behind the scenes in these
capabilities. Knowing how the framework operates when you use a particular component
helps you design better apps, and solve problems faster.
When you finish this book, you’ll have learned the following skills, which are highly relevant
in implementing apps:
Configuring and using the Spring context and dependency injection with Spring
Designing and using aspects
Implementing web apps
Implementing data exchange between apps
Persisting data
Testing implementations
You’ll find this book is valuable for the following:
Working on an app using Spring for your job
Succeeding in a technical interview for a Java developer role
Obtaining your Spring certification
Even if this book’s first purpose is not to prepare you for a Spring certification, I consider it
a must-read before digging into details a certification exam typically requires.
Who should read this book
This book is for developers who understand basic object-oriented programming and Java
concepts and want to learn Spring or refresh their Spring fundamentals knowledge. You do
not need to have previous experience with any framework, but you need to understand
Java because this is the language we use throughout the book’s examples.
Spring is one of the most encountered technologies in Java apps and will most likely be
used even more in the future. For a Java developer, this makes Spring a must-know today.
Learning what I teach you in this book will help you upskill, provide you with the Spring
foundation knowledge and skills you need to successfully pass a Java interview, and work
on an app using Spring technologies. The book also opens doors to further study Spring
details that are more complex.
How this book is organized: A roadmap
This book is divided into two parts that cover 15 chapters. We’ll start our discussion (in the
first part of the book) with straightforward examples to show you how to make Spring
aware of your application. We’ll then build examples that enable you to understand the core
of any real-world Spring app. Once we finish with Spring Core basics, we’ll discuss Spring
Data and Spring Boot basics.
From chapter 2 to the end of this book, you’ll find that theoretical aspects are accompanied
by projects in which we apply the notions we discuss. I explain the code in these examples
snippet by snippet. My recommendation is you build these examples with me while reading.
Then, you can compare your result with my solution.
As presented in the following figure, I designed the book’s chapters to be read in the given
order. In chapters 2 through 5, where we discuss the Spring context, you might find the
examples predominantly theoretical. For anyone with little or no experience with Spring, it’s
essential to start this way. Don’t worry! I present the foundations in the easiest possible
way, and then our examples and discussions gradually become more sophisticated to reflect
real-world, production-ready code.
Figure 1 If you start with no (or very little) knowledge about Spring, the best way to read the book is to
start with the first chapter and read everything in order.
If you already understand the Spring context and Spring AOP well, you can skip part 1 and
go directly to part 2, “Implementation” (chapters 7-15), as presented in the next figure.
Figure 2 If you already understand the Spring framework’s foundation and know how to use the Spring
context and design aspects, you can start with part 2, where we use Spring capabilities to implement
apps mirroring scenarios you face in real-world systems.
Once you finish reading this book, you’ll have learned plenty of skills to develop apps like a
professional. You’ll learn to connect to databases using the most encountered techniques
today, and you’ll learn how to make apps communicate with each other. We’ll end the book
with teaching a critical topic: testing. I’ll season the text here and there by adding stories of
my experience and notes with valuable pieces of advice.
Remember that Spring is a vast universe, and one book won’t teach you everything about
it. With this book, you get started with the framework and learn the fundamental skills of
using Spring’s valuable components. Throughout the book, I refer, where appropriate, to
other resources and books that detail the topics we discuss. I strongly recommend you read
those additional resources and books to broaden your perspective on the discussed topics.
About the code
The book provides about 70 projects, which we’ll work on in chapters 2 through 14. When
working on a specific example, I mention the project’s name, which implements that
example. My recommendation is to try to write your example from scratch and then use the
provided project only to compare your solution with mine. This approach will help you
better understand the concepts you’re learning.
Each of the projects is built with Maven, making it easy to import into any IDE. I used
IntelliJ IDEA to write the projects, but you can choose to run them in Eclipse, Netbeans, or
any other tool of your choice. Appendix F gives you an overview of the recommended tools.
This book contains many examples of source code, both in numbered listings and in line
with normal text. In both cases, source code is formatted in a fixed-width font like
this to separate it from ordinary text. Sometimes code is also in bold to highlight code
that has changed from previous steps in the chapter, such as when a new feature adds to
an existing line of code. In many cases, the original source code has been reformatted;
we’ve added line breaks and reworked indentation to accommodate the available page
space in the book. In rare cases, even this was not enough, and listings include line-
continuation markers (➥). Additionally, comments in the source code have often been
removed from the listings when the code is described in the text. Code annotations
accompany many of the listings, highlighting important concepts.
liveBook discussion forum
Purchase of Spring Start Here includes free access to a private web forum run by Manning
Publications where you can make comments about the book, ask technical questions, and
receive help from the author and from other users. To access the forum, go to
https://livebook.manning.com/#!/book/spring-start-here/discussion. You can also learn
more about Manning’s forums and the rules of conduct at https://livebook
.manning.com/#!/discussion.
Manning’s commitment to our readers is to provide a venue where a meaningful dialogue
between individual readers and between readers and the author can take place. It is not a
commitment to any specific amount of participation on the part of the author, whose
contribution to the forum remains voluntary (and unpaid). We suggest you try asking the
author some challenging questions lest his interest stray! The forum and the archives of
previous discussions will be accessible from the publisher’s website as long as the book is in
print.
about the author
Laurenţiu Spilcă is a dedicated development lead and trainer at
Endava, where he leads the development of projects in the financial
market with users in Europe, the US, and Asia. He has over 10 years
of experience. Laurenţiu believes it’s important to not only deliver
high-quality software, but also share knowledge and help others to
upskill. These beliefs have driven him to design and teach courses
related to Java technologies and deliver presentations and workshops.
His Twitter handle is @laurspilca.
about the cover illustration
The figure on the cover of Spring Start Here is captioned “Femme d’ajaccio isle de Corse,”
or a woman from Ajaccio on the island of Corsica. The illustration is taken from a collection
of dress costumes from various countries by Jacques Grasset de Saint-Sauveur (1757-
1810), titled Costumes de Différents Pays, published in France in 1797. Each illustration is
finely drawn and colored by hand. The rich variety of Grasset de Saint-Sauveur’s collection
reminds us vividly of how culturally apart the world’s towns and regions were just 200
years ago. Isolated from each other, people spoke different dialects and languages. In the
streets or in the countryside, it was easy to identify where they lived and what their trade
or station in life was just by their dress.
The way we dress has changed since then and the diversity by region, so rich at the time,
has faded away. It is now hard to tell apart the inhabitants of different continents, let alone
different towns, regions, or countries. Perhaps we have traded cultural diversity for a more
varied personal life—certainly for a more varied and fast-paced technological life.
At a time when it is hard to tell one computer book from another, Manning celebrates the
inventiveness and initiative of the computer business with book covers based on the rich
diversity of regional life of two centuries ago, brought back to life by Grasset de Saint-
Sauveur’s pictures.
Part 1 Fundamentals
Any building stands on a foundation. A framework is no different in this regard. In part 1,
you’ll learn to use the basic components that enable the Spring framework. These
components are the Spring context and Spring aspects. Further in the book, you’ll discover
that all Spring capabilities rely on these essential components.
1 Spring in the real world
This chapter covers
What a framework is
When to use and when to avoid using frameworks
What the Spring framework is
Using Spring in real-world scenarios
The Spring framework (shortly, Spring) is an application framework that is part of the Java
ecosystem. An application framework is a set of common software functionalities that
provides a foundation structure for developing an application. An application framework
eases the effort of writing an application by taking out the effort of writing all the program
code from scratch.
We use Spring in the development of many kinds of applications nowadays, from large
backend solutions to automation testing apps. According to many survey reports on Java
technologies (like this one of JRebel from 2020: http:// mng.bz/N4V7; or this one from
JAXEnter: http://mng.bz/DK9a), Spring is the most used Java framework today.
Spring is popular, and developers have started to use it more often with other JVM
languages than Java as well. In the last few years, we observed an impressive growth of
developers using Spring with Kotlin (another appreciated language from the JVM family). In
this book, we’ll focus on the foundations of Spring, and I’ll teach you essential skills for
using Spring in real-world examples. To make the subject more comfortable for you and
allow you to focus on Spring, we’ll use only Java examples. Throughout the book, we’ll
discuss and apply, with examples, essential skills like connecting to a database, establishing
communication between applications, and securing and testing an app.
Before diving into more technical details in the next chapters, let’s talk about the Spring
framework and where you’ll actually use it. Why is Spring so appreciated, and when should
you even use it?
In this chapter, we’ll focus on what a framework is, referring in particular to the Spring
framework. In section 1.1, we discuss the advantages of using a framework. In section 1.2,
we discuss the Spring ecosystem with the components you need to learn to get started with
Spring. Then I’ll take you through possible usages of the Spring framework—in particular,
real-world scenarios in section 1.3. In section 1.4, we’ll discuss when using frameworks
might not be the right approach. You need to understand all these things about the Spring
framework before trying to use it. Otherwise, you might try to use a hammer to dig your
garden.
Depending on your level, you might feel this chapter difficult. I might introduce some
notions that you haven’t heard about, and this aspect might disturb you. But don’t worry;
even if you don’t understand some of the things now, they will be clarified later in the book.
Sometimes, throughout the book, I’ll refer to something said in earlier chapters. I use this
approach because learning a framework like Spring doesn’t always offer us a linear learning
path, and sometimes you need to wait until you get more pieces of the puzzle before you
see the complete picture. But in the end, you’ll get a clear image, and you’ll get the
valuable skills you need to develop apps like a professional.
1.1 Why should we use frameworks?
In this section, we discuss frameworks. What are they? How did this concept appear, and
why? To be motivated to use something, you need to know how that something brings you
value. And that’s also the case with Spring. I’ll teach you these essential details by sharing
the knowledge I gathered from my own experience and by studying and using various
frameworks in real-world scenarios, including Spring.
An application framework is a set of functionalities on top of which we build applications.
The application framework provides us a broad set of tools and functionalities that you can
use to build apps. You don’t need to use all the features the framework offers. Depending
on the requirements of the app you make, you’ll choose the right parts of the framework to
use.
Here’s an analogy I like for application frameworks. Did you ever buy a piece of furniture
from a DIY store like Ikea? Say you buy a wardrobe—you won’t get an assembled
wardrobe, but the right components you need to build it and a manual on how to assemble
your piece of furniture. Now imagine you ordered a wardrobe, but instead of getting only
the right components you need, you get all the possible components you can use to
assemble any piece of furniture: a table, a wardrobe, and so on. If you want a wardrobe,
you have to find the right parts and assemble them. It’s like an application framework. The
application framework offers you various pieces of software you need to build your app. You
need to know what features to choose and how to assemble them to achieve the right
result (figure 1.1).
Figure 1.1 David ordered a wardrobe from the UAssemble store. But the store (framework) doesn’t
deliver to David (the programmer) just the components (software capabilities) he needs to build his new
wardrobe (the app). The store ships him all the possible parts he might need to build the wardrobe. It’s
David’s (the programmer’s) choice on which components (software capabilities) are right and how to
assemble them to get the right result (the application).
The idea of a framework isn’t new. Throughout the history of software development,
programmers observed they could reuse parts of code they’d written in multiple
applications. Initially, when not so many applications were implemented, each application
was unique and developed from scratch using a specific programming language. When the
software development domain extended, and more and more applications started to be
published on the market, it became easier to observe that many of these apps had similar
requirements. Let’s name a few of them:
Logging error, warning, and info messages happen in every app.
Most applications use transactions to process data changes. Transactions represent an
important mechanism that takes care of data consistency. We’ll discuss this subject in
detail in chapter 13.
Most applications use protection mechanisms against the same common vulnerabilities.
Most applications use similar ways to communicate with each other.
Most applications use similar mechanisms to improve their performance, like caching or
data compression.
And the list continues. It turns out that the business logic code implemented in an app is
significantly smaller than the wheels and belts that make the engine of the application (also
often referred to as “the plumbing”).
When I say “business logic code,” I refer to the code that implements the business
requirements of the application. This code is what implements the user’s expectations in an
application. For example, “clicking on a specific link will generate an invoice” is something
users expect to happen. Some code of the application you develop implements this
functionality, and this part of code is what developers call the business logic code. However,
any app takes care of several more aspects: security, logging, data consistency, and so on
(figure 1.2).
Figure 1.2 The user’s perspective is similar to viewing an iceberg. Users mainly observe the results of the
business logic code, but this is only a small part of what builds the app’s complete functionality. Like an
iceberg that is mostly underwater and hidden from view, we don't see most of the code in an enterprise
app because it's provided by dependencies.
Moreover, the business logic code is what makes an application different from another from
the functionality point of view. If you take two different apps, say a ridesharing system and
a social networking app, they have different use cases.
NOTE A use case represents the reason a person uses the app. For example, in a ridesharing app, a use case is “requesting a car.” For an app
managing food delivery, a use case is “ordering a pizza.”
You take different actions, but they both need data storing, data transfer, logging, security
configurations, probably caching, and so on. Various applications can reuse these
nonbusiness implementations. Is it then efficient to rewrite the same functionalities every
time? Of course not:
You spare a lot of time and money by reusing something rather than developing it
yourself.
An existing implementation that many apps already use has fewer chances to introduce
bugs, as others have tested it.
You benefit from the advice of a community because you now have a lot of developers
understanding the same functionality. If you had implemented your own code, only a
few people would know it.
A story of transition
One of the first applications I worked on was a huge system developed in Java. This system was composed of multiple applications
designed around an old-fashioned architecture server, all of them written from scratch using Java SE. The development of this application
started with the language about 25 years ago. This was the main reason for its shape. And almost no one could have imagined how big it
would become. At that time, more advanced concepts of system architectures didn’t exist, and things in general worked differently from
the individual systems due to the slow internet connection.
But time passed, and years later, the app was more like a big ball of mud. For valid reasons I won’t cover here, the team decided they had
to go to a modern architecture. This change implied first cleaning up the code, and one of the main steps was using a framework. We
decided to go with Spring. At that time, we had as an alternative Java EE (now named Jakarta EE), but most members of the team
considered it’s better to go with Spring, which offered a lighter alternative that was easier to implement and that we also considered easier
to maintain.
The transition wasn’t an easy one. Together with a few colleagues, experts in their domain and knowledgeable about the application itself,
we invested a lot of effort into this transformation.
The result was amazing! We removed over 40% of the lines of code. This transition was the first moment I understood how significant the
impact of using a framework could be.
NOTE Choosing and using a framework is linked to the design and architecture of an application. You’ll find it useful to learn more about these
subjects along with learning the Spring framework. In appendix A, you’ll find a discussion about software architectures with excellent resources if
you’d like to go into details.
1.2 The Spring ecosystem
In this section, we will discuss Spring and related projects like Spring Boot or Spring Data.
You’ll learn all about these in this book, and the links among them. In real-world scenarios,
it’s common to use different frameworks together, where each framework is designed to
help you implement a specific part of the app faster.
We refer to Spring as a framework, but it is much more complex. Spring is an ecosystem of
frameworks. Usually, when developers refer to the Spring framework, they refer to a part
of the software capabilities that include the following:
1. Spring Core—One of the fundamental parts of Spring that includes foundational
capabilities. One of these features is the Spring context. As you’ll learn in detail in
chapter 2, the Spring context is a fundamental capability of the Spring framework that
enables Spring to manage instances of your app. Also, as part of Spring Core, you find
the Spring aspects functionality. Aspects help Spring intercept and manipulate methods
you define in your app. We discuss more details of the aspects in chapter 6. The Spring
Expression Language (SpEL) is another capability you’ll find as part of Spring Core,
which enables you to describe configurations for Spring using a specific language. All of
these are new notions, and I don’t expect you to know them yet. But soon you’ll
understand that Spring Core holds the mechanisms Spring uses to integrate into your
app.
2. Spring model-view-controller (MVC)—The part of the Spring framework that enables
you to develop web applications that serve HTTP requests. We’ll use Spring MVC
starting in chapter 7.
3. Spring Data Access—Also one of the fundamental parts of Spring. It provides basic tools
you can use to connect to SQL databases to implement the persistence layer of your
app. We’ll use Spring Data Access starting in chapter 13.
4. Spring testing—The part holding the tools you need to write tests for your Spring
application. We’ll discuss this subject in chapter 15.
You can initially imagine the Spring framework as a solar system, where Spring Core
represents the star in the middle, which holds all the framework together (figure 1.3).
Figure 1.3 You can imagine the Spring framework as a solar system with the Spring Core in the center.
The software capabilities are planets around Spring Core kept close to it by its gravitational field.
1.2.1 Discovering Spring Core: The foundation of Spring
Spring Core is the part of the Spring framework that provides the foundational mechanisms
to integrate into apps. Spring works based on the principle inversion of control (IoC). When
using this principle, instead of allowing the app to control the execution, we give control to
some other piece of software—in our case, the Spring framework. Through configurations,
we instruct the framework on how to manage the code we write, which defines the logic of
the app. Here’s where the “inversion” in IoC comes from: you don’t let the app control the
execution by its own code and use dependencies. Instead, we allow the framework (the
dependency) to control the app and its code (figure 1.4).
Figure 1.4 Inversion of control. Instead of executing its own code, which makes use of several other
dependencies, in case of an IoC scenario, the app execution is controlled by the dependency. The Spring
framework controls an app during its execution. Therefore, it implements an IoC scenario of execution.
NOTE In this context the term “controls” refers to actions like “creating an instance” or “calling a method.” A framework can create objects of
the classes you define in your app. Based on the configurations that you write, Spring intercepts the method to augment it with various features.
For example, Spring can intercept a specific method to log any error that might appear during the method’s execution.
You will start learning Spring with Spring Core by discussing the Spring IoC functionality in
chapters 2 through 5. The IoC container glues Spring components and components of your
application to the framework together. Using the IoC container, to which you often refer as
the Spring context, you make certain objects known to Spring, which enables the
framework to use them in the way you configured.
In chapter 6, we’ll continue our discussion with Spring aspect-oriented programming (AOP).
Spring can control instances added to its IoC container, and one of the things it can do is
intercept methods that represent the behavior of these instances. This capability is called
aspecting the method. Spring AOP is one of the most common ways the framework
interacts with what your app does. This trait makes Spring AOP part of the essentials as
well. Part of the Spring Core, we also find resource management, internationalization
(i18n), type conversion, and SpEL. We’ll encounter aspects of these features in examples
throughout the book.
1.2.2 Using Spring Data Access feature to implement the app’s
persistence
For most applications, it’s critical to persist part of the data they process. Working with
databases is a fundamental subject, and in Spring, it’s the Data Access module that you’ll
use to take care of data persistence in many cases. The Spring Data Access includes using
JDBC, integrating with object-relational mapping (ORM) frameworks like Hibernate (don’t
worry if you don’t yet know what an ORM framework is or haven’t heard about Hibernate;
we’ll discuss these aspects later in the book), and managing transactions. In chapters 12
through 14, we’ll cover everything needed to get you started with Spring Data Access.
1.2.3 The Spring MVC capabilities for developing web apps
The most common applications developed with Spring are web apps, and within the Spring
ecosystem, you’ll find a large set of tools that enables you to write web applications and
web services in different fashions. You can use the Spring MVC to develop apps using a
standard servlet fashion, which is common in a vast number of applications today. In
chapter 7, we’ll go into more detail on using the Spring MVC.
1.2.4 The Spring testing feature
The Spring testing module offers us a large set of tools that we’ll use to write unit and
integration tests. There have been many pages written about the testing topic, but we’ll
discuss everything that is essential to get you started with Spring testing in chapter 15. I’ll
also refer to some valuable resources you need to read to get all the details of this topic.
My rule of thumb is that you’re not a mature developer if you don’t understand testing, so
this topic is one you should care about.
1.2.5 Projects from the Spring ecosystem
The Spring ecosystem is so much more than just the capabilities discussed earlier in this
section. It includes a big collection of other frameworks that integrate well and form a
larger universe. Here we have projects like Spring Data, Spring Security, Spring Cloud,
Spring Batch, Spring Boot, and so on. When you develop an app, you can use more of
these projects together. For example, you can build an app using all of Spring Boot, Spring
Security, and Spring Data. In the next few chapters, we’ll work on smaller projects that
make use of various projects of the Spring ecosystem. When I say project, I refer to a part
of the Spring ecosystem that is independently developed. Each of these projects has a
separate team that works on extending its capabilities. Also, each project is separately
described and has its own reference on the Spring official website:
https://spring.io/projects.
Out of this vast universe created by Spring, we’ll also refer to Spring Data and Spring Boot.
These projects are often encountered in apps, so it’s important to get to know them from
the beginning.
EXTENDING THE PERSISTENCE CAPABILITIES WITH SPRING DATA
The Spring Data project implements a part of the Spring ecosystem that enables you to
easily connect to databases and use the persistence layer with a minimum number of lines
of code written. The project refers to both SQL and NoSQL technologies and creates a high-
level layer, which simplifies the way you work with data persistence.
NOTE We have Spring Data Access, which is a module of Spring Core, and we also have an independent project in the Spring ecosystem named
Spring Data. Spring Data Access contains fundamental data access implementations like the transaction mechanism and JDBC tools. Spring
Data enhances access to databases and offers a broader set of tools, which makes development more accessible and enables your app to
connect to different kinds of data sources. We’ll discuss this subject in chapter 14.
SPRING BOOT
Spring Boot is a project part of the Spring ecosystem that introduces the concept of
“convention over configuration.” The main idea of this concept is that instead of setting up
all the configurations of a framework yourself, Spring Boot offers you a default
configuration that you can customize as needed. The result, in general, is that you write
less code because you follow known conventions and your app differs from others in few or
small ways. So instead of writing all the configurations for each and every app, it’s more
efficient to start with a default configuration and only change what’s different from the
convention. We’ll discuss more about Spring Boot starting in chapter 7.
The Spring ecosystem is vast and contains many projects. Some of them you encounter
more often than others, and some you may not use at all if you’re building an application
without a particular need. In this book, we refer only to the projects that are essential for
you to get started: Spring Core, Spring Data, and Spring Boot. You can find a full list of
projects that are part of the Spring ecosystem on the official Spring website:
https://spring.io/projects/.
Alternatives for using Spring
We can’t really discuss alternatives to Spring because someone could misunderstand them as alternatives to the entire ecosystem. But for
many of the individual components and projects that create the Spring ecosystem, you can find other options like other open source or
commercial frameworks or libraries.
For example, let’s take the Spring IoC container. Years ago, the Java EE specification was a solution very much appreciated by the
developers. With a slightly different philosophy, Java EE (which in 2017 was open sourced and remade in Jakarta EE, https://jakarta.ee/)
offered specifications like Context and Dependency Injection (CDI) or Enterprise Java Beans (EJB). You could use CDI or EJB to manage a
context of object instances and implement aspects (named “interceptors” in the EE terminology). Also, throughout history, Google Guice
(https://github.com/google/guice) was an appreciated framework for the management of object instances in a container.
For some of the projects taken individually, you could find one or more alternatives. For example, you could choose to use Apache Shiro
(https://shiro.apache.org/) instead of Spring Security. Or you could decide to implement your web app using the Play framework
(https://www.playframework.com/) instead of Spring MVC and Spring-related technologies.
A more recent project that looks promising is Red Hat Quarkus. Quarkus is designed for cloud native implementations and becomes more
and more mature with rapid steps. I wouldn’t be surprised to see it as one of the lead projects in developing enterprise apps in the Java
ecosystem in the future (https://quarkus.io/).
My advice for you is to always take into consideration your alternatives. In software development, you need to be open-minded and never
trust one solution as being “the one.” You’ll always find scenarios in which a specific technology works better than another.
1.3 Spring in real-world scenarios
Now that you have an overview of Spring, you’re aware of when and why you should use a
framework. In this section, I’ll give you some application scenarios in which using the
Spring framework might be an excellent fit. Too often, I’ve seen developers only refer to
backend applications for using a framework like Spring. I’ve even seen a trend of
restricting, even more, the scenario to backend web applications. While it’s true that in
plenty of cases we see Spring used in this way, it’s important to remember that the
framework isn’t limited to this scenario. I’ve seen teams successfully using Spring in
different kinds of applications, such as the development of an automation testing app or
even in standalone desktop scenarios.
I’ll further describe to you some common real-world scenarios in which I’ve seen Spring
used successfully. These are not the only possible scenarios, and Spring might not work all
the time in these cases. Remember what we discussed in section 1.2: a framework is not
always a good choice. But these are common cases in which generally Spring is a good fit:
1. The development of a backend app
2. The development of an automation testing framework
3. The development of a desktop app
4. The development of a mobile app
1.3.1 Using Spring in the development of a backend app
A backend application is the part of a system that executes on the server side and has the
responsibility of managing data and serving client applications’ requests. The users access
functionalities by using the client apps directly. Further, the client apps make requests to
the backend app to work with the users’ data. The backend app might use databases to
store data or communicate with other backend apps in different fashions.
You can imagine, in a real-world scenario, that the app would be the backend application
managing the transactions in your bank accounts. Users may access their accounts and
manage them via a web application (online banking) or a mobile app. Both the mobile apps
and the web apps represent clients for the backend application. To manage users’
transactions, the backend application needs to communicate with other backend solutions,
and part of the data it manages needs to be persisted in a database. In figure 1.5, you can
visualize the architecture of such a system.
Figure 1.5 A backend app interacts in several ways with other apps and uses databases to manage data.
Usually, a backend app is complex and may require the use of various technologies. Frameworks
simplify the implementation by providing tools you can use to implement the backend solution faster.
NOTE Don’t worry if you don’t understand all the details of figure 1.5. I don’t expect you to know what a message broker is and not even how to
establish the data exchange among the components. What I want you to see is that such a system can become complex in the real world and
then understand that projects from the Spring ecosystem were built to help you eliminate this complexity as much as possible.
Spring offers an excellent set of tools for implementing backend applications. It makes your
life easier with the different functionalities you generally implement in a backend solution,
from integration with other apps to persistence in various database technologies. It’s no
wonder developers often use Spring for such applications. The framework basically offers
you everything you need in such implementations and is an excellent fit for any kind of
architectural style. Figure 1.6 indicates the possibilities of using Spring for a backend app.
Figure 1.6 The possibilities of using Spring in a backend application are endless, from exposing
functionalities that other applications can call to managing the database access, and from securing the
application to managing integration though third-party message brokers.
1.3.2 Using Spring in a automation test app
Nowadays, we often use automation testing for end-to-end testing of systems we
implement. Automation testing refers to implementing software that development teams
use to make sure an application behaves as expected. A development team can schedule
the automation testing implementation to frequently test the app and notify the developers
if something is wrong. Having such functionality gives developers confidence because they
know they’ll be notified if they break anything in the existing capabilities of the app while
developing new features.
While with small systems you can do the testing manually, it’s always a good idea to
automate the test cases. For more complex systems, manually testing all the flows isn’t
even an option. Because the flows are so numerous, it’d require a massive number of hours
and too much energy to cover it completely.
It turns out that the most efficient solution is to have a separate team implement an app
that has the responsibility of validating all the flows of the tested system. While developers
add new functionalities to the system, this testing app is also enhanced to cover what’s
new, and the teams use it to validate that everything still works as desired. The developers
eventually use an integration tool and schedule the app to run regularly to get feedback as
soon as possible for their changes (figure 1.7).
Figure 1.7 The team deploys the testing app in a test environment. A continuous integration tool like
Jenkins executes the app regularly and sends feedback to the team. This way, the team is always aware
of the system’s status, and they know if they break something during development.
Such an application might become as complex as a backend app. In order to validate the
flows, the app needs to communicate with the components of the system and even connect
to databases. Sometimes the app mocks external dependencies to simulate different
execution scenarios. For writing the test scenarios, developers use frameworks like
Selenium, Cucumber, Gauge, and others. But, together with these frameworks, the app
could still benefit in several ways from Spring’s tools. For example, the app could manage
the object instances to make the code more maintainable using the Spring IoC container. It
could use Spring Data to connect to the databases where it needs to validate the data. It
could send messages to queues or topics of a broker system to simulate specific scenarios
or simply use Spring to call some REST endpoints (figure 1.8). (Remember, it’s okay if this
looks too advanced; meaning will be clarified as you progress through the book).
Figure 1.8 A testing app might need to connect to databases or communicate with other systems or the
tested system. The developers can use components of the Spring ecosystem to simplify the
implementations of these functionalities.
1.3.3 Using Spring for the development of a desktop app
Today, desktop applications are not that frequently developed, as web or mobile apps have
taken the role of interacting with the user. However, there’s still a small number of desktop
applications, and components of the Spring ecosystem could be a good choice in the
development of their features. A desktop app could successfully use the Spring IoC
container to manage the object instances. This way, the app’s implementation is cleaner
and improves its maintainability. Additionally, the app could potentially use Spring’s tools to
implement different features, for example to communicate with a backend or other
components (calling web services or using other techniques for remote calls) or implement
a caching solution.
1.3.4 Using Spring in mobile apps
With its Spring for Android project (https://spring.io/projects/spring-android), the Spring
community tries to help the development of mobile applications. Even though you’ll
probably rarely encounter this situation, it’s worth mentioning that you can use Spring’s
tools to develop Android apps. This Spring project provides a REST client for Android and
authentication support for accessing secured APIs.
1.4 When not to use frameworks
In this section, we discuss why you should sometimes avoid using frameworks. It’s
essential you know when to use a framework and when to avoid using them. Sometimes,
using a tool that’s too much for the job might consume more energy and also obtain a
worse result. Imagine using a chainsaw to cut bread. While you could try to and even
achieve a final result, it’d be more difficult and energy-consuming than using a regular knife
(and you may end up with nothing but breadcrumbs instead of sliced bread). We’ll discuss a
few scenarios in which using a framework isn’t a great idea, and then I’ll tell you a story
about a team I was part of that failed in the implementation of an app because of using a
framework.
It turns out that, like everything else in software development, you shouldn’t apply a
framework in all cases. You’ll find situations in which a framework is not a good fit—or
maybe a framework is a good fit, but not the Spring framework. In which of the following
scenarios should you consider not using a framework?
1. You need to implement a particular functionality with a footprint as small as possible.
By footprint, I mean the storage memory occupied by the app’s files.
2. Specific security requirements force you to implement only custom code in your app
without making use of any open source framework.
3. You’d have to make so many customizations over the framework that you’d write more
code than if you’d simply not used it at all.
4. You already have a functional app, and by changing it to use a framework you don’t
gain any benefit.
Let’s discuss these points in more detail.
1.4.1 You need to have a small footprint
For point one, I refer to situations in which you need to make your application small. In
today’s systems, we find more and more cases in which the services are delivered in
containers. You’ve likely heard about containers, such as Docker, Kubernetes, or other
terms related to this subject (if not, again, that’s okay).
Containers in their entirety is a topic beyond the scope of this book, so for now the only
thing I need you to know is that when you use such a deployment fashion, you want your
application to be as small as possible. A container is like a box in which your application
lives. One crucial principle regarding app deployment in containers is that the containers
should be easily disposable: they can be destroyed and recreated as fast as possible. The
size of the app (footprint) matters a lot here. You can save seconds from the app
initialization by making it smaller. That doesn’t mean you won’t use frameworks for all the
apps deployed in containers.
But for some apps, which are usually also quite small, it makes more sense to improve their
initialization and make their footprint smaller rather than adding dependencies to different
frameworks. Such a case is a kind of application called server-less function. These server-
less functions are tiny applications deployed in containers. Because you don’t have too
much access to the way they’re deployed, it looks like they execute without a server (hence
their name). These apps need to be small, and that’s why, for this specific case of apps,
you’ll want to avoid adding a framework as much as possible. Because of its size, it’s also
possible that you won’t need a framework anyway.
1.4.2 Security needs dictate custom code
I said in point two that in specific situations, apps could not use frameworks because of
security requirements. This scenario usually happens with apps in the field of defense or
governmental organizations. Again, it doesn’t mean all the apps used in governmental
organizations are prohibited from using frameworks, but for some, restrictions are applied.
You may wonder why. Well, say an open source framework like Spring is used. If someone
finds a specific vulnerability, it will become known, and a hacker could use this knowledge
to exploit it. Sometimes, stakeholders of such apps want to make sure the chances of
someone hacking into their system is as close to zero as possible. This could lead to even
rebuilding a functionality instead of using it from a third-party source.
NOTE Wait! Earlier I said that it’s more secure to use an open source framework because if a vulnerability exists, someone will likely discover it.
Well, if you invest enough time and money, you probably can achieve this yourself as well. In general, it’s cheaper to use a framework, of course.
And if you don’t want to be extra cautious, it makes more sense to use a framework. But in some projects, the stakeholders really want to make
sure no information becomes public.
1.4.3 Abundant existing customizations make a framework impractical
Another case (point three) in which you might want to avoid using a framework is when
you’d have to customize its components so much that you end up writing more code than if
it hadn’t been used. As I specified in section 1.1, a framework provides you parts that you
assemble with your business code to obtain an app. These components, provided by the
framework, don’t fit perfectly, and you need to customize them in different ways. It’s
perfectly normal to customize the framework’s components and the style in which they
assemble than if you’d developed the functionality from scratch. If you find yourself in such
a situation, you have probably chosen the wrong framework (search for alternatives) or you
shouldn’t use a framework at all.
1.4.4 You won’t benefit from switching to a framework
In point four, I mentioned that a potential mistake could be trying to use a framework to
replace something that already exists and is working in an app. Sometimes we are tempted
to replace an existing architecture with something new. A new framework appears, and it’s
popular, and everyone uses it, so why shouldn’t we change our app as well to use this
framework? You can, but you need to attentively analyze what you want to achieve by
changing something that works. In some cases, like my story from section 1.1, it could be
helpful to change your app and make it rely on a specific framework. As long as this change
brings a benefit, do it! A reason could be that you want to make the app more
maintainable, more performant, or more secure. But if this change doesn’t bring you a
benefit, and sometimes it might even bring incertitude, then, in the end, you might
discover you invested the time and money for a worse result. Let me tell you a story from
my own experience.
1.5 What will you learn in this book
Since you opened this book, I assume you’re probably a software developer in the Java
ecosystem who found out it’s useful to learn Spring. The purpose of this book is to teach
you the foundations of Spring, assuming you know nothing at all about frameworks and, of
course, about Spring. When I say Spring, I refer to the Spring ecosystem, not just the core
part of the framework.
When you finish the book, you will have learned how to do the following:
Use the Spring context and implement aspects around objects managed by the
framework.
Implement the mechanism of a Spring app to connect to a database and work with the
persisted data.
Establish data exchange between apps using REST APIs implemented with Spring.
Build basic apps that use the convention-over-configuration approach.
Use best practices in the standard class design of a Spring application.
Properly test your Spring implementations.
An avoidable mistake
Using frameworks isn’t always the best choice, and I had to learn that the hard way. Years earlier, we were working on the backend of a
web application. Times influence many things, including software architectures. The app was using JDBC to directly connect to an Oracle
database. The code was quite ugly. Everywhere the app needed to execute a query on the database it opened a statement and then sent a
query that was sometimes written on multiple rows. You might be young enough not to have encountered JDBC direct usage in apps, but
trust me, it’s a long and ugly code.
At that time, some frameworks using another methodology to work with the database were becoming more and more popular. I remember
when I first encountered Hibernate. This is an ORM framework, which allows you to treat the tables and their relationships in a database as
objects and relationships among objects. When used correctly, it enables you to write less code and more intuitive functionality. When
misused, it may slow down your app, make the code less intuitive, and even introduce bugs.
The application we were developing needed a change. We knew we could improve that ugly JDBC code. In my mind, we could at least
minimize the number of lines. This change would have brought great benefits to maintainability. Together with other developers, we
suggested using a tool provided by Spring called JdbcTemplate (you’ll learn this tool in chapter 12). But others strongly pushed the
decision to use Hibernate. It was quite popular, so why not to use it? (Actually it still is one of the most popular frameworks of its kind, and
you’ll learn about integrating it with Spring in chapter 13.) I could see changing that code to a completely new methodology would be a
challenge. Moreover, I could see no benefits. The change also implied a greater risk of introducing bugs.
Fortunately, the change started with a proof of concept. After a couple of months, lots of effort, and stress, the team decided to quit.
After analyzing our options, we finished the implementation using JdbcTemplate. We managed to write cleaner code by eliminating a
large number of lines of code, and we didn’t need to introduce any new framework for this change.
Summary
An application framework is a set of common software functionalities that provides a
foundational structure for developing an application. A framework acts as the skeletal
support to build an application.
A framework helps you build an app more efficiently by providing functionality that you
assemble to your implementation instead of developing it yourself. Using a framework
saves you time and helps ensure there are fewer chances of implementing buggy
features.
Using a widely known framework like Spring opens a door to a large community, which
makes it more likely that others will faces similar problems. You then have an excellent
opportunity to learn about how others solved something similar to an issue you need to
address, which will spare you the time of individual research.
When implementing an application, always think of all possibilities, including not using a
framework. If you decide to use one or more frameworks, take into consideration all
their alternatives. You should think about the purpose of the framework, who else is
using it (how big the community is), and for how long it’s been on the market
(maturity).
Spring is not just a framework. We often refer to Spring as “Spring framework” to
indicate the core functionalities, but Spring offers an entire ecosystem formed of many
projects used in application development. Each project is dedicated to a specific
domain, and when implementing an app, you might use more of these projects to
implement the functionality you desire. The projects of the Spring ecosystem we’ll use
in this book are as follows:
Spring Core, which builds the foundation of Spring and provides features like the
context, aspects, and basic data access.
Spring Data, which provides a high-level, comfortable-to-use set of tools to
implement the persistence layer of your apps. You’ll find how easy it is to use
Spring Data to work with both SQL and NoSQL databases.
Spring Boot, which is a project of the Spring ecosystem that helps you apply a
“convention-over-configuration” approach.
Quite often, learning materials (like books, articles, or video tutorials) offer examples
with Spring only for backend applications. While it’s true that it’s widespread to use
Spring with backend apps, you can use Spring with other kinds of apps as well, even in
desktop applications and automation testing apps.
2 The Spring context: Defining beans
This chapter covers
Understanding the need for Spring context
Adding new object instances to the Spring context
In this chapter, you start learning how to work with a crucial Spring framework element:
the context (also known as the application context in a Spring app). Imagine the context as
a place in the memory of your app in which we add all the object instances that we want
the framework to manage. By default, Spring doesn’t know any of the objects you define in
your application. To enable Spring to see your objects, you need to add them to the
context. Later in this book we discuss using different capabilities provided by Spring in
apps. You’ll learn that plugging in such features is done through the context by adding
object instances and establishing relationships among them. Spring uses the instances in
the context to connect your app to various functionalities it provides. You’ll learn the basics
of the most important features (e.g., transactions, testing, etc.) throughout the book.
Learning what Spring context is and how it works is the first step in learning to use Spring,
because without knowing how to manage the Spring context, almost nothing else you’ll
learn to do with it will be possible. The context is a complex mechanism that enables Spring
to control instances you define. This way, it allows you to use the capabilities the
framework offers.
We start in this chapter by learning how to add object instances to the Spring context. In
chapter 3, you’ll learn how to refer to the instances you added and establish relationships
among them.
We’ll name these object instances “beans.” Of course, for the syntaxes you need to learn
we’ll write code snippets, and you can find all these snippets in the projects provided with
the book (you can download the projects from the “Book resources” section of the live
book). I’ll enhance the code examples with visuals and detailed explanations of the
approaches.
Because I want to make your introduction to Spring progressive and take everything step
by step, in this chapter we focus on the syntaxes you need to know for working with the
Spring context. You’ll find out later that not all the objects of an app need to be managed
by Spring, so you don’t need to add all the object instances of your app to the Spring
context. For the moment, I invite you to focus on learning the approaches for adding an
instance for Spring to manage.
2.1 Creating a Maven project
In this section, we’ll discuss creating a Maven project. Maven is not a subject directly
related to Spring, but it’s a tool you use to easily manage an app’s build process regardless
of the framework you use. You need to know Maven project basics to follow the coding
examples. Maven is also one of the most used building tools for Spring projects in real-
world scenarios (with Gradle, another build tool, taking second place, but we won’t discuss
it in this book). Because Maven’s such a well-known tool, you may already know how to
create a project and add dependencies to it using its configuration. In this case, you can
skip this section and go directly to section 2.2.
A build tool is software we use to build apps more easily. You configure a build tool to do
the tasks that are part of building the app instead of manually doing them. Some examples
of tasks that are often part of building the app are as follows:
Downloading the dependencies needed by your app
Running tests
Validating that the syntax follows rules that you define
Checking for security vulnerabilities
Compiling the app
Packaging the app in an executable archive
So that our examples can easily manage dependencies, we need to use a build tool for the
projects we develop. This section teaches only what you need to know for developing the
examples in this book; we’ll go step by step through the process of creating a Maven
project, and I’ll teach you the essentials regarding its structure. If you’d like to learn more
details about using Maven, I recommend Introducing Maven: A Build Tool for Today’s Java
Developers by Balaji Varanasi (APress, 2019).
Let’s start at the very beginning. First, as with developing any other app, you need an
integrated development environment (IDE). Any professional IDE nowadays offers support
for Maven projects, so you can choose any you’d like: IntelliJ IDEA, Eclipse, Spring STS,
Netbeans, and so on. For this book, I use IntelliJ IDEA, which is the IDE I use most often.
Don’t worry—the structure of the Maven project is the same regardless of which IDE you
choose.
Let’s start by creating a new project. You create a new project in IntelliJ from File > New >
Project. This will get you to a window like the one in figure 2.1.
Figure 2.1 Creating a new Maven project. After going to File > New > Project, you get to this window,
where you need to select the type of the project from the left panel. In our case, we choose Maven. In the
upper part of the window, you select the JDK you wish to use to compile and run the project.
Once you’ve selected the type of your project, in the next window (figure 2.2) you need to
give it a name. In addition to the project name and choosing the location in which to store
it, for a Maven project you can also specify the following:
A group ID, which we use to group multiple related projects
An artifact ID, which is the name of the current application
A version, which is an identifier of the current implementation state
Figure 2.2 Before you finish creating your project, you need to give it a name and specify where you want
your IDE to store the project. Optionally, you can give your project a group ID, an artifact ID, and a
version. You then press the Finish button in the lower right corner to complete creating the project.
In a real-world app, these three attributes are essential details, and it’s important to
provide them. But in our case, because we only work on theoretical examples, you can omit
them and leave your IDE to fill in some default values for these characteristics.
Once you’ve created the project, you’ll find its structure looks like the one presented in
figure 2.3. Again, the Maven project structure does not depend on the IDE you choose for
developing your projects. When you look first at your project, you observe two main things:
The “src” folder (also known as the source folder), where you’ll put everything that
belongs to the app.
The pom.xml file, where you write the configurations of your Maven project, like adding
new dependencies.
Figure 2.3 How a Maven project is organized. Inside the src folder, we add everything that belongs to the
app: the application’s source code goes into the main folder, and the source code for the unit tests goes
into the test folder. In the pom.xml file we write configurations for the Maven project (in our examples
we’ll primarily use it to define the dependencies).
Maven organizes the “src” folder into the following folders:
The “main” folder, where you store the application’s source code. This folder contains
the Java code and the configurations separately into two different subfolders named
“java” and “resources.”
The “test” folder, where you store the unit tests’ source code (we discuss more about
unit tests and how to define them in chapter 15).
Figure 2.4 shows you how to add new source code to the “main/java” folder of the Maven
project. New classes of the app go into this folder.
Figure 2.4 Inside the “java” folder, you create the usual Java packages and classes of your application.
These are the classes that define the whole logic of your app and make use of the dependencies you
provide.
In the projects we create in this book, we use plenty of external dependencies: libraries or
frameworks we use to implement the functionality of the examples. To add these
dependencies to your Maven projects, we need to change the content of the pom.xml file.
In the following listing, you find the default content of the pom.xml file immediately after
creating the Maven project.
Listing 2.1 The default content of the pom.xml file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>sq-ch2-ex1</artifactId>
<version>1.0-SNAPSHOT</version>
</project>
With this pom.xml file, the project doesn’t use any external dependency. If you look in the
project’s external dependencies folder, you should only see the JDK (figure 2.5).
Figure 2.5 With a default pom.xml file, your project only uses the JDK as an external dependency. One of
the reasons you change the pom.xml file (and the one we’ll use in this book) is to add new dependencies
your app needs.
The following listing shows you how to add external dependencies to your project. You write
all the dependencies between the <dependencies> </dependencies> tags. Each
dependency is represented by a <dependency> </dependency> group of tags where
you write the dependency’s attributes: the dependency’s group ID, artifact name, and
version. Maven will search for the dependency by the values you provided for these three
attributes and will download the dependencies from a repository. I won’t go into detail on
how to configure a custom repository. You just need to be aware that Maven will download
the dependencies (usually jar files) by default from a repository named the Maven central.
You can find the downloaded jar files in your project’s external dependencies folder, as
presented in figure 2.6.
Listing 2.2 Adding a new dependency in the pom.xml file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>sq_ch2_ex1</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies> ❶
<dependency> ❷
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
</dependencies>
</project>
❶ You need to write the dependencies for the project between the <dependencies> and </dependecies> tags.
❷ A dependency is represented by a group of <dependency> </dependency> tags.
Once you’ve added the dependency in the pom.xml file, as presented in the previous listing,
the IDE downloads them, and you’ll now find these dependencies in the “External Libraries”
folder (figure 2.6).
Figure 2.6 When you add a new dependency to the pom.xml file, Maven downloads the jar files
representing that dependency. You find these jar files in the External Libraries folder of the project.
Now we can move to the next section, where we discuss the basics of the Spring context.
You’ll create Maven projects, and you’ll learn to use a Spring dependency named spring-
context, to manage the Spring context.
2.2 Adding new beans to the Spring context
In this section, you’ll learn how to add new object instances (i.e., beans) to the Spring
context. You’ll find out that you have multiple ways to add beans in the Spring context such
that Spring can manage them and plug features it provides into your app. Depending on
the action, you’ll choose a specific way to add the bean; we’ll discuss when to select one or
another. You can add beans in the context in the following ways (which we’ll describe later
in this chapter):
Using the @Bean annotation
Using stereotype annotations
Programmatically
Let’s first create a project with a reference to no framework—not even Spring. We’ll then
add the dependencies needed to use the Spring context and create it (figure 2.7). This
example will serve as a prerequisite to adding beans to the Spring context examples that
we’re going to work on in sections 2.2.1 through 2.2.3.
Figure 2.7 To start, we create an object instance and the empty Spring context.
We create a Maven project and define a class. Because it’s funny to imagine, I’ll consider a
class named Parrot with only a String attribute representing the name of the parrot
(listing 2.3). Remember, in this chapter, we only focus on adding beans to the Spring
context, so it’s okay to use any object that helps you better remember the syntaxes. You
find the code for this example in the project “sq-ch2-ex1” (you can download the projects
from the “Resources” section of the live book). For your project, you can use the same
name or choose the one you prefer.
Listing 2.3 The Parrot class
public class Parrot {
private String name;
// Omitted getters and setters
}
You can now define a class containing the main method and create an instance of the class
Parrot, as presented in the following listing. I usually name this class Main.
Listing 2.4 Creating an instance of the Parrot class
public class Main {
public static void main(String[] args) {
Parrot p = new Parrot();
}
}
It’s now time to add the needed dependencies to our project. Because we’re using Maven,
I’ll add the dependencies in the pom.xml file, as presented in the following listing.
Listing 2.5 Adding the dependency for Spring context
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>sq-ch2-ex1</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
</dependencies>
</project>
A critical thing to observe is that Spring is designed to be modular. By modular, I mean that
you don’t need to add the whole Spring to your app when you use something out of the
Spring ecosystem. You just need to add those parts that you use. For this reason, in listing
2.5, you see that I’ve only added the spring-context dependency, which instructs
Maven to pull the needed dependencies for us to use the Spring context. Throughout the
book, we’ll add various dependencies to our projects according to what we implement, but
we’ll always only add what we need.
NOTE You might wonder how I knew which Maven dependency I should add. The truth is that I’ve used them so many times I know them by
heart. However, you don’t need to memorize them. Whenever you work with a new Spring project, you can search for the dependencies you need
to add directly in the Spring reference (https://docs.spring.io/spring-framework/docs/ current/spring-framework-reference/core.html). Generally,
Spring dependencies are part of the org.springframework group ID.
With the dependency added to our project, we can create an instance of the Spring context.
In the next listing, you can see how I’ve changed the main method to create the Spring
context instance.
Listing 2.6 Creating the instance of the Spring context
public class Main {
public static void main(String[] args) {
var context =
new AnnotationConfigApplicationContext(); ❶
Parrot p = new Parrot();
}
}
❶ Creates an instance of the Spring context
NOTE We use the AnnotationConfigApplicationContext class to create the Spring context instance. Spring offers multiple
implementations. Because in most cases you’ll use the AnnotationConfigApplicationContext class (the implementation that uses
the most used today’s approach: annotations), we’ll focus on this one in this book. Also, I only tell you what you need to know for the current
discussion. If you’re just getting started with Spring, my recommendation is to avoid getting into details with context implementations and these
classes’ inheritance chains. Chances are that if you do you’ll get lost with unimportant details instead of focusing on the essential things.
As presented in figure 2.8, you created an instance of Parrot, added the Spring context
dependencies to your project, and created an instance of the Spring context. Your objective
is to add the Parrot object to the context, which is the next step.
Figure 2.8 You created the Spring context instance and a Parrot instance. Now, you want to add the
Parrot instance inside the Spring context to make Spring aware of this instance.
We just finished creating the prerequisite (skeleton) project, which we’ll use in the next
sections to understand how to add beans to the Spring context. In section 2.2.1, we
continue learning how to add the instance to the Spring context using the @Bean
annotation. Further, in sections 2.2.2 and 2.2.3, you’ll also learn the alternatives of adding
the instance using stereotype annotations and doing it programmatically. After discussing
all three approaches, we’ll compare them, and you’ll learn the best circumstances for using
each.
2.2.1 Using the @Bean annotation to add beans into the Spring context
In this section, we’ll discuss adding an object instance to the Spring context using the
@Bean annotation. This makes it possible for you to add the instances of the classes
defined in your project (like Parrot in our case), as well as classes you didn’t create
yourself but you use in your app. I believe this approach is the easiest to understand when
starting out. Remember that the reason you learn to add beans to the Spring context is
that Spring can manage only the objects that are part of it. First, I’ll give you a
straightforward example of how to add a bean to the Spring context using the @Bean
annotation. Then I’ll show you how to add multiple beans of the same or different type.
The steps you need to follow to add a bean to the Spring context using the @Bean
annotation are as follows (figure 2.9):
1. Define a configuration class (annotated with @Configuration) for your project,
which, as we’ll discuss later, we use to configure the context of Spring.
2. Add a method to the configuration class that returns the object instance you want to
add to the context and annotate the method with the @Bean annotation.
3. Make Spring use the configuration class defined in step 1. As you’ll learn later, we use
configuration classes to write different configurations for the framework.
Figure 2.9 Steps for adding the bean to the context using the @Bean annotation. By adding the instance to
the Spring context, you make the framework aware of the object, enabling it to manage the instance.
Let’s follow these steps and apply them in the project named “sq-c2-ex2.” To keep all the
steps we discuss separated, I recommend you create new projects for each example.
NOTE Remember, you can find the book’s projects in the “Resources” section of the live book.
NOTE A configuration class is a special class in Spring applications that we use to instruct Spring to do specific actions. For example, we can
tell Spring to create beans or to enable certain functionalities. You will learn different things you can define in configuration classes throughout
the rest of the book.
STEP 1: DEFINING A CONFIGURATION CLASS IN YOUR PROJECT
The first step is to create a configuration class in the project. A Spring configuration class is
characterized by the fact that it is annotated with the @Configuration annotation. We
use the configuration classes to define various Spring-related configurations for the project.
Throughout the book, you’ll learn different things you can configure using the configuration
classes. For the moment we focus only on adding new instances to the Spring context. The
next listing shows you how to define the configuration class. I named this configuration
class ProjectConfig.
Listing 2.7 Defining a configuration class for the project
@Configuration ❶
public class ProjectConfig {
}
❶ We use the @Configuration annotation to define this class as a Spring configuration class.
NOTE I separate the classes into different packages to make the code easier to understand. For example, I create the configuration classes in a
package named config, and the Main class in a package named main. Organizing the classes into packages is a good practice; I recommend
you follow it in your real-world implementations as well.
STEP 2: CREATE A METHOD THAT RETURNS THE BEAN, AND ANNOTATE THE
METHOD WITH @BEAN
One of the things you can do with a configuration class is add beans to the Spring context.
To do this, we need to define a method that returns the object instance we wish to add to
the context and annotate that method with the @Bean annotation, which lets Spring know
that it needs to call this method when it initializes its context and adds the returned value
to the context. The next listing shows the changes to the configuration class to implement
the current step.
NOTE For the projects in this book, I use Java 11: the latest long-term supported Java version. More and more projects are adopting this version.
Generally, the only specific feature I use in the code snippets that doesn’t work with an earlier version of Java is the var reserved type name. I
use var here and there to make the code shorter and easier to read, but if you’d like to use an earlier version of Java (say Java 8, for example),
you can replace var with the inferred type. This way, you’ll make the projects work with Java 8 as well.
Listing 2.8 Defining the @Bean method
@Configuration
public class ProjectConfig {
@Bean ❶
Parrot parrot() {
var p = new Parrot();
p.setName("Koko"); ❷
return p; ❸
}
}
❶ By adding the @Bean annotation, we instruct Spring to call this method when at context initialization and add the returned value to the
context.
❷ Set a name for the parrot we’ll use later when we test the app.
❸ Spring adds to its context the Parrot instance returned by the method.
Observe that the name I used for the method doesn’t contain a verb. You probably learned
that a Java best practice is to put verbs in method names because the methods generally
represent actions. But for methods we use to add beans in the Spring context, we don’t
follow this convention. Such methods represent the object instances they return and that
will now be part of the Spring context. The method’s name also becomes the bean’s name
(as in listing 2.8, the bean’s name is now “parrot”). By convention, you can use nouns, and
most often they have the same name as the class.
STEP 3: MAKE SPRING INITIALIZE ITS CONTEXT USING THE NEWLY
CREATED CONFIGURATION CLASS
We’ve implemented a configuration class in which we tell Spring the object instance that
needs to become a bean. Now we need to make sure Spring uses this configuration class
when initializing its context. The next listing shows you how to change the instantiation of
the Spring context in the main class to use the configuration class we implemented in the
first two steps.
Listing 2.9 Initializing the Spring context based on the defined configuration class
public class Main {
public static void main(String[] args) {
var context =
new AnnotationConfigApplicationContext(
ProjectConfig.class); ❶
}
}
❶ When creating the Spring context instance, send the configuration class as a parameter to instruct Spring to use it.
To verify the Parrot instance is indeed part of the context now, you can refer to the
instance and print its name in the console, as presented in the following listing.
Listing 2.10 Referring to the Parrot instance from the context
public class Main {
public static void main(String[] args) {
var context =
new AnnotationConfigApplicationContext(
ProjectConfig.class);
Parrot p = context.getBean(Parrot.class); ❶
System.out.println(p.getName());
}
}
❶ Gets a reference of a bean of type Parrot from the Spring context
Now you’ll see the name you gave to the parrot you added in the context in the console, in
my case Koko.
NOTE In real-world scenarios, we use unit and integration tests to validate that our implementations work as desired. The projects in this book
implement unit tests to validate the discussed behavior. Because this is a “getting started” book, you might not yet be aware of unit tests. To
avoid creating confusion and allow you to focus on the discussed subject, we won’t discuss unit tests until chapter 15. However, if you already
know how to write unit tests and reading them helps you better understand the subject, you can find all the unit tests implemented in the test
folder of each of our Maven projects. If you don’t yet know how unit tests work, I recommend focusing only on the discussed subject.
As in the previous example, you can add any kind of object to the Spring context (figure
2.10). Let’s also add a String and an Integer and see that it’s working.
Figure 2.10 You can add any object to the Spring context to make Spring aware of it.
The next listing shows you how I changed the configuration class to also add a bean of type
String and a bean of type Integer.
Listing 2.11 Adding two more beans to the context
@Configuration
public class ProjectConfig {
@Bean
Parrot parrot() {
var p = new Parrot();
p.setName("Koko");
return p;
}
@Bean ❶
String hello() {
return "Hello";
}
@Bean ❷
Integer ten() {
return 10;
}
}
❶ Adds the string “Hello” to the Spring context
❷ Adds the integer 10 to the Spring context
NOTE Remember the Spring context’s purpose: we add the instances we expect Spring needs to manage. (This way, we plug in functionalities
offered by the framework.) In a real-world app, we won’t add every object to the Spring context. Starting with chapter 4, when our examples will
become closer to code in a production-ready app, we’ll also focus more on which objects Spring needs to manage. For the moment, focus on the
approaches you can use to add beans to the Spring context.
You can now refer to these two new beans in the same way we did with the parrot. The
next listing shows you how to change the main method to print the new beans’ values.
Listing 2.12 Printing the two new beans in the console
public class Main {
public static void main(String[] args) {
var context = new AnnotationConfigApplicationContext(
ProjectConfig.class);
Parrot p = context.getBean(Parrot.class); ❶
System.out.println(p.getName());
String s = context.getBean(String.class);
System.out.println(s);
Integer n = context.getBean(Integer.class);
System.out.println(n);
}
}
❶ You don’t need to do any explicit casting. Spring looks for a bean of the type you requested in its context. If such a bean doesn’t exist, Spring
will throw an exception.
Running the app now, the values of the three beans will be printed in the console, as shown
in the next code snippet.
Koko
Hello
10
Thus far we added one or more beans of different types to the Spring context. But could we
add more than one object of the same type (figure 2.11)? If yes, how can we individually
refer to these objects? Let’s create a new project, “sq-ch2-ex3,” to demonstrate how you
can add multiple beans of the same type to the Spring context and how you can refer to
them afterward.
Figure 2.11 You can add more beans of the same type to the Spring context by using multiple methods
annotated with @Bean. Each instance will have a unique identifier. To refer to them afterward, you’ll need
to use the beans’ identifiers.
NOTE Don’t confuse the name of the bean with the name of the parrot. In our example, the beans’ names (or identifiers) in the Spring context
are parrot1, parrot2, and parrot3 (like the name of the @Bean methods defining them). The names I gave to the parrots are Koko,
Miki, and Riki. The parrot name is just an attribute of the Parrot object, and it doesn’t mean anything to Spring.
You can declare as many instances of the same type as you wish by simply declaring more
methods annotated with the @Bean annotation. The following listing shows you how I’ve
declared three beans of type Parrot in the configuration class. You find this example with
the project “sq-ch2-ex3.”
Listing 2.13 Adding multiple beans of the same type to the Spring context
@Configuration
public class ProjectConfig {
@Bean
Parrot parrot1() {
var p = new Parrot();
p.setName("Koko");
return p;
}
@Bean
Parrot parrot2() {
var p = new Parrot();
p.setName("Miki");
return p;
}
@Bean
Parrot parrot3() {
var p = new Parrot();
p.setName("Riki");
return p;
}
}
Of course, you can’t get the beans from the context anymore by only specifying the type. If
you do, you’ll get an exception because Spring cannot guess which instance you’ve declared
you refer to. Look at the following listing. Running such a code throws an exception in
which Spring tells you that you need to be precise, which is the instance you want to use.
Listing 2.14 Referring to a Parrot instance by type
public class Main {
public static void main(String[] args) {
var context = new
AnnotationConfigApplicationContext(ProjectConfig.class);
Parrot p = context.getBean(Parrot.class); ❶
System.out.println(p.getName());
}
}
❶ You’ll get an exception on this line because Spring cannot guess which of the three Parrot instances you refer to.
When running your application, you’ll get an exception similar to the one presented by the
next code snippet.
Exception in thread "main" org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type
'main.Parrot' available: expected single matching bean but found 3:
parrot1,parrot2,parrot3 ❶
at ...
❶ Names of the Parrot beans in the context
To solve this ambiguity problem, you need to refer precisely to one of the instances by
using the bean’s name. By default, Spring uses the names of the methods annotated with
@Bean as the beans’ names themselves. Remember that’s why we don’t name the @Bean
methods using verbs. In our case, the beans have the names parrot1, parrot2, and
parrot3 (remember, the method represents the bean). You can find these names in the
previous code snippet in the message of the exception. Did you spot them? Let’s change
the main method to refer to one of these beans explicitly by using its name. Observe how I
referred to the parrot2 bean in the following listing.
Listing 2.15 Referring to a bean by its identifier
public class Main {
public static void main(String[] args) {
var context = new
AnnotationConfigApplicationContext(ProjectConfig.class);
Parrot p = context.getBean("parrot2", Parrot.class); ❶
System.out.println(p.getName());
Discovering Diverse Content Through
Random Scribd Documents
prisoner—it so impressed his counsel, that they deemed it necessary
and absolutely essential to their defense to attempt to destroy the
credibility of the witness Wiechmann.
I may say here, in passing, that they have not attempted to
impeach his general reputation for truth by the testimony of a single
witness, nor have they impeached his testimony by calling a single
witness to discredit one material fact to which he has testified in this
issue. Failing to find a breath of suspicion against Wiechmann's
character, or to contradict a single fact to which he testified, the
accused had to fly to the last resort, an alibi, and very earnestly did
the learned counsel devote himself to the task.
It is not material whether this meeting in the hotel took place on
the 23d of December or in January. But, says the counsel, it was
after the commencement or close of the Congressional holiday. That
is not material; but the concurrent resolution of Congress shows that
the holiday commenced on the 22d of December, the day before the
accused spent the evening in Washington. The witness is not certain
about the date of this meeting. The material fact is, did this meeting
take place—either on the 23d of December or in January last? Were
the private interviews there held, and was the apology made, as
detailed, by Mudd and Booth, after the secret conference, to the
witness? That the meeting did take place, and that Mudd did explain
that these secret interviews, with Booth first, and with Booth and
Surratt directly afterward, had relation to the sale of his farm, is
confessedly admitted by the endeavor of the prisoner, through his
counsel, to show that negotiations had been going on between
Booth and Mudd for the sale of Mudd's farm. If no such meeting was
held, if no such explanation was made by Mudd to Wiechmann, can
any man for a moment believe that a witness would have been
called here to give any testimony about Booth having negotiated for
Mudd's farm? What conceivable connection has it with this case,
except to show that Mudd's explanation to Wiechmann for his
extraordinary conduct was in exact accordance with the fact? Or was
this testimony about the negotiations for Mudd's farm intended to
show so close an intimacy and intercourse with Booth that Mudd
could not fail to recognize him when he came flying for aid to his
house from the work of assassination? It would be injustice to the
able counsel to suppose that.
I have said that it was wholly immaterial whether this
conversation took place on the 23d of December or in January; it is
in evidence that in both these months Booth was at the National
Hotel; that he occupied a room there; that he arrived there on the
22d and was there on the 23d of December last, and also on the
12th day of January. The testimony of the witness is, that Booth said
he had just come in. Suppose this conversation took place in
December, on the evening of the 23d, the time when it is proved by
J. T. Mudd, the witness for the accused, that he, in company with
Samuel A. Mudd, spent the night in Washington City. Is there
anything in the testimony of that or any other witness to show that
the accused did not have and could not have had an interview with
Booth on that evening? J. T. Mudd testifies that he separated from
the prisoner, Samuel A. Mudd, at the National Hotel early in the
evening of that day, and did not meet him again until the accused
came in for the night at the Pennsylvania House, where he stopped.
Where was Dr. Samuel A. Mudd during this interval? What does his
witness know about him during that time? How can he say that Dr.
Mudd did not go up on Seventh Street in company with Booth, then
at the National; that he did not on Seventh Street meet Surratt and
Wiechmann; that he did not return to the National Hotel; that he did
not have this interview, and afterwards meet him, the witness, as he
testifies, at the Pennsylvania House? Who knows that the
Congressional holiday had not in fact commenced on that day? What
witness has been called to prove that Booth did not on either of
those occasions occupy the room that had formerly been occupied
by a member of Congress, who had temporarily vacated it, leaving
his books there? Wiechmann, I repeat, is not positive as to the date,
he is only positive as to the fact; and he disclosed voluntarily to this
court that the date could probably be fixed by a reference to the
register of the Pennsylvania House; that register cannot, of course,
be conclusive of whether Mudd was there in January or not, for the
very good reason that the proprietor admits that he did not know
Samuel A. Mudd, therefore Mudd might have registered by any other
name. Wiechmann does not pretend to know that Mudd had
registered at all. If Mudd was here in January, as a party to this
conspiracy, it is not at all unlikely that, if he did register at that time
in the presence of a man to whom he was wholly unknown, his
kinsman not then being with him, he would register by a false name.
But if the interview took place in December, the testimony of
Wiechmann bears as strongly against the accused as if it had
happened in January. Wiechmann says he does not know what time
was occupied in this interview at the National Hotel; that it probably
lasted twenty minutes; that, after the private interviews between
Mudd and Surratt and Booth, which were not of very long duration,
had terminated, the parties went to the Pennsylvania House, where
Dr. Mudd had rooms, and after sitting together in the common
sitting-room of the hotel, they left Dr. Mudd there about ten o'clock
P.M., who remained during the night. Wiechmann's testimony leaves
no doubt that this meeting on Seventh Street and interview at the
National took place after dark, and terminated before or about ten
o'clock P.M. His own witness, J. T. Mudd, after stating that he
separated from the accused at the National Hotel, says after he had
got through a conversation with a gentleman of his acquaintance, he
walked down the Avenue, went to several clothing stores, and "after
a while" walked round to the Pennsylvania House, and "very soon
after" he got there Dr. Mudd came in, and they went to bed shortly
afterwards. What time he spent in his "walk alone" on the Avenue,
looking at clothing; what period he embraces in the terms "after a
while," when he returned to the Pennsylvania House, and "soon
after" which Dr. Mudd got there, the witness does not disclose.
Neither does he intimate, much less testify, that he saw Dr. Mudd
when he first entered the Pennsylvania House on that night after
their separation. How does he know that Booth and Surratt and
Wiechmann did not accompany Samuel A. Mudd to that house that
evening? How does he know that the prisoner and those persons did
not converse together some time in the sitting-room of the
Pennsylvania Hotel? Jeremiah Mudd has not testified that he met Dr.
Mudd in that room, or that he was in it himself. He has, however,
sworn to the fact, which is disproved by no one, that the prisoner
was separated from him long enough that evening to have had the
meeting with Booth, Surratt, and Wiechmann, and the interviews in
the National Hotel, and at the Pennsylvania House, to which
Wiechmann has testified? Who is there to disprove it? Of what
importance is it whether it was on the 23d day of December or in
January? How does that affect the credibility of Wiechmann? He is a
man, as I have before said, against whose reputation for truth and
good conduct they have not been able to bring one witness. If this
meeting did by possibility take place that night, is there anything to
render it improbable that Booth and Mudd and Surratt did have the
conversation at the National Hotel to which Wiechmann testifies? Of
what avail, therefore, is the attempt to prove that Mudd was not
here during January, if it was clear that he was here on the 23d of
December, 1864, and had this conversation with Booth? That this
attempt to prove an alibi during January has failed, is quite as clear
as is the proof of the fact that the prisoner was here on the evening
of the 23d of December, and present in the National Hotel, where
Booth stopped. The fact that the prisoner, Samuel A. Mudd, went
with J. T. Mudd on that evening to the National Hotel, and there
separated from him, is proved by his own witness, J. T. Mudd; and
that he did not rejoin him until they retired to bed in the
Pennsylvania House is proved by the same witness and contradicted
by nobody. Does any one suppose there would have been such
assiduous care to prove that the prisoner was with his kinsman all
the time on the 23d of December, in Washington, if they had not
known that Booth was then at the National Hotel, and that a
meeting of the prisoner with Booth, Surratt, and Wiechmann on that
day would corroborate and confirm Wiechmann's testimony in every
material statement he made concerning that meeting?
The accused having signally failed to account for his absence
after he separated from his witness, J. T. Mudd, early in the evening
of the 23d of December, at the National Hotel, until they had again
met at the Pennsylvania House, when they retired to rest, he now
attempts to prove an alibi as to the month of January. In this he has
failed, as he failed in the attempt to show that he could not have
met Booth, Surratt, and Wiechmann on the 23d of December.
For this purpose the accused calls Betty Washington. She had
been at Mudd's house every night since the Monday after Christmas
last, except when here at court, and says that the prisoner, Mudd,
has only been away from home three nights during that time. This
witness forgets that Mudd has not been at home any night or day
since this court assembled. Neither does she account for the three
nights in which she swears to his absence from home. First, she says
he went to Gardner's party; second, he went to Giesboro, then to
Washington. She does not know in what month he was away, the
second time, all night. She only knows where he went from what he
and his wife said, which is not evidence; but she does testify that
when he left home and was absent over night the second time, it
was about two or three weeks after she came to his house, which
would, if it were three weeks, make it just about the 15th of
January, 1865; because she swears she came to his house on the
first Monday after Christmas last, which was the 26th day of
December; so that the 15th of January would be three weeks, less
one day, from that time; and it might have been a week earlier
according to her testimony, as, also, it might have been a week
earlier, or more, by Wiechmann's testimony, for he is not positive as
to the time. What I have said of the register of the Pennsylvania
House, the headquarters of Mudd and Atzerodt, I need not here
repeat. That record proves nothing, save that Dr. Mudd was there on
the 23d of December, which, as we have seen, is a fact, along with
others, to show that the meeting at the National then took place. I
have also called the attention of the court to the fact that if Mudd
was at that house again in January, and did not register his name,
that fact proves nothing; or, if he did, the register only proves that
he registered falsely; either of which facts might have happened
without the knowledge of the witness called by the accused from
that house, who does not know Samuel A. Mudd personally.
The testimony of Henry L. Mudd, his brother, in support of this
alibi, is, that the prisoner was in Washington on the 23d of March,
and on the 10th of April, four days before the murder! But he does
not account for the absent night in January, about which Betty
Washington testifies. Thomas Davis was called for the same
purpose, but stated that he was himself absent one night in January,
after the 9th of that month, and he could not say whether Mudd was
there on that night or not. He does testify to Mudd's absence over
night three times, and fixes one occasion on the night of the 26th of
January. In consequence of his own absence one night in January,
this witness cannot account for the absence of Mudd on the night
referred to by Betty Washington.
This matter is entitled to no further attention. It can satisfy no
one, and the burden of proof is upon the prisoner to prove that he
was not in Washington in January last. How can such testimony
convince any rational man that Mudd was not here in January,
against the evidence of an unimpeached witness, who swears that
Samuel A. Mudd was in Washington in the month of January? Who
that has been examined here as a witness knows that he was not?
The Rev. Mr. Evans swears that he saw him in Washington last
winter, and that at the same time he saw Jarboe, the one coming
out of, and the other going into, a house on H Street, which he was
informed on inquiry was the house of Mrs. Surratt. Jarboe is the only
witness called to contradict Mr. Evans, and he leaves it in extreme
doubt whether he does not corroborate him, as he swears that he
was here himself last winter or fall, but cannot state exactly the
time. Jarboe's silence on questions touching his own credibility
leaves no room for any one to say that his testimony could impeach
Mr. Evans, whatever he might swear.
Miss Anna H. Surratt is also called for the purpose of impeaching
Mr. Evans. It is sufficient to say of her testimony on that point that
she swears negatively only—that she does not see either of the
persons named at her mother's house. This testimony neither
disproves, nor does it even tend to disprove, the fact put in issue by
Mr. Evans. No one will pretend, whatever the form of her expression
in giving her testimony, that she could say more than that she did
not know the fact, as it was impossible that she could know who
was, or who was not, at her mother's house, casually, at a period so
remote. It is not my purpose, neither is it needful here, to question
in any way the integrity of this young woman.
It is further in testimony that Samuel A. Mudd was here on the
3d day of March last, the day preceding the inauguration, when
Booth was to strike the traitorous blow; and it was, doubtless, only
by the interposition of that God who stands within the shadow and
keeps watch above his own, that the victim of this conspiracy was
spared that day from the assassin's hand that he might complete his
work and see the salvation of his country in the fall of Richmond and
the surrender of its great army. Dr. Mudd was here on that day (the
3d of March) to abet, to encourage, to nerve his co-conspirator for
the commission of this great crime. He was carried away by the
awful purpose which possessed him, and rushed into the room of Mr.
Norton, at the National Hotel, in search of Booth, exclaiming
excitedly: "I'm mistaken; I thought this was Mr. Booth's room." He is
told Mr. Booth is above, on the next floor. He is followed by Mr.
Norton, because of his rude and excited behavior, and being
followed, conscious of his guilty errand, he turns away, afraid of
himself and afraid to be found in concert with his fellow confederate.
Mr. Norton identifies the prisoner, and has no doubt that Samuel A.
Mudd is the man.
The Rev. Mr. Evans also swears that, after the 1st and before the
4th day of March last, he is certain that within that time, and on the
2d or 3d of March, he saw Dr. Mudd drive into Washington City. The
endeavor is made by the accused in order to break down this
witness, by proving another alibi. The sister of the accused, Miss
Fanny Mudd, is called. She testifies that she saw the prisoner at
breakfast in her father's house, on the 2d of March, about five
o'clock in the morning, and not again until the 3d of March at noon.
Mrs. Emily Mudd swears substantially to the same statement. Betty
Washington, called for the accused, swears that he was at home all
day at work with her on the 2d of March, and took breakfast at
home. Frank Washington swears that Mudd was at home all day;
that he saw him when he first came out in the morning about
sunrise from his own house, and knows that he was there all day
with them. Which is correct, the testimony of his sisters or the
testimony of his servants? The sisters say that he was at their
father's house for breakfast on the morning of the 2d of March; the
servants say he was at home for breakfast with them on that day. If
this testimony is followed, it proves one alibi too much. It is
impossible, in the nature of things, that the testimony of all these
four witnesses can be true.
Seeing this weakness in the testimony brought to prove this
second alibi, the endeavor is next made to discredit Mr. Norton for
truth; and two witnesses, not more, are called, who testify that his
reputation for truth has suffered by contested litigation between one
of the impeaching witnesses and others. Four witnesses are called,
who testify that Mr. Norton's reputation for truth is very good; that
he is a man of high character for truth, and entitled to be believed
whether he speaks under the obligation of an oath or not. The late
Postmaster General, Hon. Horatio King, not only sustains Mr. Norton
as a man of good reputation for truth, but expressly corroborates his
testimony, by stating that in March last, about the 4th of March, Mr.
Norton told him the same fact to which he swears here: that a man
came into his room under excitement, alarmed his sister, was
followed out by himself, and went down stairs instead of going up;
and that Mr. Norton told him this before the assassination, and about
the time of the inauguration. What motive had Mr. Norton at that
time to fabricate this statement? It detracts nothing from his
testimony that he did not at that time mention the name of this man
to his friend, Mr. King; because it appears from his testimony—and
there is none to question the truthfulness of his statement—that at
that time he did not know his name. Neither does it take from the
force of this testimony, that Mr. Norton did not, in communicating
this matter to Mr. King, make mention of Booth's name; because
there was nothing in the transaction, at the time, he being ignorant
of the name of Mudd, and equally ignorant of the conspiracy
between Mudd and Booth, to give the least occasion for any mention
of Booth or of the transaction further than as he detailed it. With
such corroboration, who can doubt the fact that Mudd did enter the
room of Mr. Norton, and was followed by him, on the 3d of March
last? Can he be mistaken in the man? Whoever looks at the prisoner
carefully once will be sure to recognize him again.
For the present I pass from the consideration of the testimony
showing Dr. Mudd's connection with Booth in this conspiracy, with
the remark that it is in evidence, and I think established, both by the
testimony adduced by the prosecution and that by the prisoner, that
since the commencement of this rebellion, John H. Surratt visited
the prisoner's house; that he concealed Surratt and other rebels and
traitors in the woods near his house, where for several days he
furnished them with food and bedding; that the shelter of the woods
by night and by day was the only shelter that the prisoner dare
furnish these friends of his; that in November, Booth visited him and
remained over night; that he accompanied Booth at that time to
Gardner's, from whom he purchased one of the horses used on the
night of the assassination to aid the escape of one of his
confederates; that the prisoner had secret interviews with Booth and
Surratt, as sworn to by the witness Wiechmann, in the National
Hotel, whether on the 23d of December or in January is a matter of
entire indifference; that he rushed into Mr. Norton's room on the 3d
of March in search of Booth; and that he was here again on the 10th
of April, four days before the murder of the President. Of his conduct
after the assassination of the President, which is confirmatory of all
this—his conspiring with Booth and his sheltering, concealing, and
aiding the flight of his co-conspirator, this felon assassin—I shall
speak hereafter, leaving him for the present with the remark that the
attempt to prove his character has resulted in showing him in
sympathy with the rebellion, so cruel that he shot one of his slaves
and declared his purpose to send several of them to work on the
rebel batteries in Richmond.
What others, besides Samuel A. Mudd and John H. Surratt and
Lewis Payne, did Booth, after his return from Canada, induce to join
him in this conspiracy to murder the President, the Vice-President,
the Secretary of State, and the Lieutenant General, with the intent
thereby to aid the rebellion and overthrow the government and laws
of the United States?
On the 10th of February the prisoners Arnold and O'Laughlin
came to Washington and took rooms in the house of Mrs. Vantyne;
were armed; were then visited frequently by John Wilkes Booth, and
alone; were occasionally absent when Booth called, who seemed
anxious for their return—would sometimes leave notes for them, and
sometimes a request that when they came in they should be told to
come to the stable. On the 18th of March last, when Booth played in
"The Apostate," the witness, Mrs. Vantyne, received from O'Laughlin
complimentary tickets. These persons remained there until the 20th
of March. They were visited, so far as the witness knows, during
their stay at her house only by Booth, save that on a single occasion
an unknown man came to see them, and remained with them over
night. They told the witness they were in the "oil business." With
Mudd, the guilty purpose was sought to be concealed by declaring
that he was in the "land business"; with O'Laughlin and Arnold it was
attempted to be concealed by the pretence that they were in the "oil
business." Booth, it is proved, had closed up all connection with oil
business last September. There is not a word of testimony to show
that the accused, O'Laughlin and Arnold, ever invested or sought to
invest, in any way or to any amount, in the oil business; their silly
words betray them; they forgot when they uttered that false
statement that truth is strong, next to the Almighty, and that their
crime must find them out was the irrevocable and irresistible law of
nature and of nature's God.
One of their co-conspirators, known as yet only to the guilty
parties to this damnable plot and to the Infinite, who will unmask
and avenge all blood-guiltiness, comes to bear witness, unwittingly,
against them. This unknown conspirator, who dates his letter at
South Branch Bridge, April 6, 1865, mailed and postmarked
Cumberland, Md., and addressed to John Wilkes Booth, by his
initials, "J. W. B., National Hotel, Washington, D.C.," was also in the
"oil speculation." In that letter he says:—
"Friend Wilkes:—I received yours of March 12th, and reply
as soon as practicable. I saw French, Brady, and others about
the oil speculation. The subscription to the stock amounts to
eight thousand dollars, and I add one thousand myself, which
is about all I can stand. Now, when you sink your well, go
deep enough; don't fail; everything depends upon you and
your helpers. If you cannot get through on your trip after you
strike oil, strike through Thornton gap and across by Capon,
Romney, and down the Branch. I can keep you safe from all
hardships for a year. I am clear of all surveillance now that
infernal Purdy is beat....
"I send this by Tom, and if he don't get drunk you will get
it the 9th. At all events, it cannot be understood if lost....
"No more, only Jake will be at Green's with the funds.
(Signed)
"Lon."
That this letter is not a fabrication is made apparent by the
testimony of Purdy, whose name occurs in the letter. He testified
that he had been a detective in the government service, and that he
had been falsely accused, as the letter recites, and put under arrest;
that there was a noted rebel, by the name of Green, living at
Thornton gap; that there was a servant, who drank, known as
"Tom," in the neighborhood of South Branch Bridge; that there is an
obscure route through the gap, and as described in the letter; and
that a man commonly called "Lon" lives at South Branch Bridge. If
the court are satisfied—and it is for them to judge—that this letter
was written before the assassination, as it purports to have been,
and on the day of its date, there can be no question with any one
who reads it that the writer was in the conspiracy, and knew that the
time of its execution drew nigh. If a conspirator, every word of its
contents is evidence against every other party to this conspiracy.
Who can fail to understand this letter? His words, "go deep
enough," "don't fail," "everything depends on you and your helpers,"
"if you can't get through on your trip after you strike oil, strike
through Thornton gap," etc., and "I can keep you safe from all
hardships for a year," necessarily imply that when he "strikes oil"
there will be an occasion for a flight; that a trip, or route, has
already been determined upon; that he may not be able to go
through by that route; in which event he is to strike for Thornton
gap, and across by Capon and Romney, and down the branch, for
the shelter which his co-conspirator offers him. "I am clear of all
surveillance now"—does any one doubt that the man who wrote
those words wished to assure Booth that he was no longer watched,
and that Booth could safely hide with him from his pursuers? Does
any one doubt, from the further expression in this letter, "Jake will
be at Green's with the funds," that this was a part of the price of
blood, or that the eight thousand dollars subscribed by others, and
the one thousand additional, subscribed by the writer, were also a
part of the price to be paid?
"The oil business," which was the declared business of
O'Laughlin and Arnold, was the declared business of the infamous
writer of this letter; was the declared business of John H. Surratt;
was the declared business of Booth himself, as explained to Chester
and Payne; was "the business" referred to in his telegrams to
O'Laughlin, and meant the murder of the President, of his cabinet,
and of General Grant. The first of these telegrams is dated
Washington, 13th March, and is addressed to M. O'Laughlin, No. 57
North Exeter Street, Baltimore, Md., and is as follows: "Don't you
fear to neglect your business; you had better come on at once. J.
Booth." The telegraphic operator, Hoffman, who sent this despatch
from Washington, swears that John Wilkes Booth delivered it to him
in person on the day of its date; and the handwriting of the original
telegram is established beyond question to be that of Booth. The
other telegram is dated Washington, March 27, addressed, "M.
O'Laughlin, Esq., 57 North Exeter Street, Baltimore, Md.," and is as
follows: "Get word to Sam. Come on with or without him on
Wednesday morning. We sell that day sure; don't fail. J. Wilkes
Booth." The original of this telegram is also proved to be in the
handwriting of Booth. The sale referred to in this last telegram was
doubtless the murder of the President and others—the "oil
speculation," in which the writer of the letter from South Branch
Bridge, dated April 6, had taken a thousand dollars, and in which
Booth said there was money, and Sanders said there was money,
and Atzerodt said there was money. The words of this telegram, "get
word to Sam," mean Samuel Arnold, his co-conspirator, who had
been with him during all his stay in Washington, at Mrs. Vantyne's.
These parties to this conspiracy, after they had gone to Baltimore,
had additional correspondence with Booth, which the court must
infer had relation to carrying out the purposes of their confederation
and agreement. The colored witness, Williams, testifies that John
Wilkes Booth handed him a letter for Michael O'Laughlin, and
another for Samuel Arnold, in Baltimore, some time in March last;
one of which he delivered to O'Laughlin at the theatre in Baltimore,
and the other to a lady at the door where Arnold boarded in
Baltimore.
Their agreement and co-operation in the common object having
been thus established, the letter written to Booth by the prisoner
Arnold, dated March 27, 1865, the handwriting of which is proved
before the court, and which was found in Booth's possession after
the assassination, becomes testimony against O'Laughlin, as well as
against the writer Arnold, because it is an act done in furtherance of
their combination. That letter is as follows:—
"Dear John:—Was business so important that you could
not remain in Baltimore till I saw you? I came in as soon as I
could, but found you had gone to Washington. I called also,
to see Mike, but learned from his mother he had gone out
with you and had not returned. I concluded, therefore, he
had gone with you. How inconsiderate you have been! When
I left you, you stated that we would not meet in a month or
so, and therefore I made application for employment, an
answer to which I shall receive during the week. I told my
parents I had ceased with you. Can I, then, under existing
circumstances, act as you request? You know full well that the
government suspicions something is going on there, therefore
the undertaking is becoming more complicated. Why not, for
the present, desist?—for various reasons, which, if you look
into, you can readily see without my making any mention
thereof. You, nor any one, can censure me for my present
course. You have been its cause, for how can I now come
after telling them I had left you? Suspicion rests upon me
now from my whole family, and even parties in the country. I
will be compelled to leave home any how, and how soon I
care not. None, no, not one, were more in favor of the
enterprise than myself, and to-day would be there had you
not done as you have. By this I mean manner of proceeding.
I am, as you well know, in need. I am, you may say, in rags,
whereas, to-day, I ought to be well clothed. I do not feel right
stalking about with means, and more from appearances a
beggar. I feel my dependence. But even all this would have
been, and was, forgotten, for I was one with you. Time more
propitious will arrive yet. Do not act rashly or in haste. I
would prefer your first query, 'Go and see how it will be taken
in Richmond,' and ere long I shall be better prepared to again
be with you. I dislike writing. Would sooner verbally make
known my views. Yet your now waiting causes me thus to
proceed. Do not in anger peruse this. Weigh all I have said,
and, as a rational man and a friend, you cannot censure or
upbraid my conduct. I sincerely trust this, nor aught else that
shall or may occur, will ever be an obstacle to obliterate our
former friendship and attachment. Write me to Baltimore, as I
expect to be in about Wednesday or Thursday; or, if you can
possibly come on, I will Tuesday meet you at Baltimore at B.
"Ever I subscribe myself, your friend,
"Sam."
Here is the confession of the prisoner Arnold, that he was one
with Booth in this conspiracy; the further confession that they are
suspected by the government of their country, and the
acknowledgment that since they parted Booth had communicated,
among other things, a suggestion which leads to the remark in this
letter, "I would prefer your first query, 'Go and see how it will be
taken at Richmond,' and ere long I shall be better prepared to again
be with you." This is a declaration that affects Arnold, Booth, and
O'Laughlin alike, if the court are satisfied, and it is difficult to see
how they can have doubt on the subject, that the matter to be
referred to Richmond is the matter of the assassination of the
President and others, to effect which these parties had previously
agreed and conspired together. It is a matter in testimony, by the
declaration of John H. Surratt, who is as clearly proved to have been
in this conspiracy and murder as Booth himself, that about the very
date of this letter, the 27th of March, upon the suggestion of Booth,
and with his knowledge and consent, he went to Richmond, not only
to see "how it would be taken there," but to get funds with which to
carry out the enterprise, as Booth had already declared to Chester in
one of his last interviews, when he said that he or "some one of the
party" would be constrained to go to Richmond for funds to carry
out the conspiracy. Surratt returned from Richmond, bringing with
him some part of the money for which he went, and was then going
to Canada, and, as the testimony discloses, bringing with him the
despatches from Jefferson Davis to his chief agents in Canada,
which, as Thompson declared to Conover, made the proposed
assassination "all right." Surratt, after seeing the parties here, left
immediately for Canada and delivered his despatches to Jacob
Thompson, the agent of Jefferson Davis. This was done by Surratt
upon the suggestion, or in exact accordance with the suggestion, of
Arnold, made on the 27th of March in his letter to Booth just read,
and yet you are gravely told that four weeks before the 27th of
March Arnold had abandoned the conspiracy.
Surratt reached Canada with these despatches, as we have
seen, about the 6th or 7th of April last, when the witness Conover
saw them delivered to Jacob Thompson and heard their contents
stated by Thompson, and the declaration from him that these
despatches made it "all right." That Surratt was at that time in
Canada is not only established by the testimony of Conover, but it is
also in evidence that he told Wiechmann on the 3d of April that he
was going to Canada, and on that day left for Canada, and
afterwards, two letters addressed by Surratt over the fictitious
signature of John Harrison, to his mother and to Miss Ward; dated at
Montreal, were received by them on the 14th of April, as testified by
Wiechmann and by Miss Ward, a witness called for the defense.
Thus it appears that the condition named by Arnold in his letter had
been complied with. Booth had "gone to Richmond," in the person of
Surratt, "to see how it would be taken." The rebel authorities at
Richmond had approved it, the agent had returned; and Arnold was,
in his own words, thereby the better prepared to rejoin Booth in the
prosecution of this conspiracy.
To this end Arnold went to Fortress Monroe. As his letter
expressly declares, Booth said when they parted, "we would not
meet in a month or so, and therefore I made application for
employment—an answer to which I shall receive during the week."
He did receive the answer that week from Fortress Monroe, and
went there to await the "more propitious time," bearing with him the
weapon of death which Booth had provided, and ready to obey his
call, as the act had been approved at Richmond and been made "all
right." Acting upon the same fact that the conspiracy had been
approved in Richmond and the funds provided, O'Laughlin came to
Washington to identify General Grant, the person who was to
become the victim of his violence in the final consummation of this
crime—General Grant, whom, as is averred in the specification, it
had become the part of O'Laughlin by his agreement in this
conspiracy to kill and murder. On the evening preceding the
assassination—the 13th of April—by the testimony of three reputable
witnesses, against whose truthfulness not one word is uttered here
or elsewhere, O'Laughlin went into the house of the Secretary of
War, where General Grant then was, and placed himself in position in
the hall where he could see him, having declared before he reached
that point, to one of these witnesses, that he wished to see General
Grant. The house was brilliantly illuminated at the time; two, at
least, of the witnesses conversed with the accused and the other
stood very near to him, took special notice of his conduct, called
attention to it, and suggested that he be put out of the house, and
he was accordingly put out by one of the witnesses. These witnesses
are confident, and have no doubt, and so swear upon their oaths,
that Michael O'Laughlin is the man who was present on that
occasion. There is no denial on the part of the accused that he was
in Washington during the day and during the night of April 13, and
also during the day and during the night of the 14th; and yet, to get
rid of this testimony, recourse is had to that common device—an
alibi; a device never, I may say, more frequently resorted to than in
this trial. But what an alibi! Nobody is called to prove it, save some
men who, by their own testimony, were engaged in a drunken
debauch through the evening. A reasonable man who reads their
evidence can hardly be expected to allow it to outweigh the united
testimony of three unimpeached and unimpeachable witnesses who
were clear in their statements, who entertain no doubt of the truth
of what they say, whose opportunities to know were full and
complete, and who were constrained to take special notice of the
prisoner by means of his extraordinary conduct.
These witnesses describe accurately the appearance, stature,
and complexion of the accused, but because they describe his
clothing as dark or black, it is urged that as part of his clothing,
although dark, was not black, the witnesses are mistaken.
O'Laughlin and his drunken companions (one of whom swears that
he drank ten times that evening) were strolling in the streets and in
the direction of the house of the Secretary of War, up the Avenue;
but you are asked to believe that these witnesses could not be
mistaken in saying they were not off the Avenue above Seventh
Street, or on K Street. I venture to say that no man who reads their
testimony can determine satisfactorily all the places that were visited
by O'Laughlin and his drunken associates that evening from seven to
eleven o'clock P.M. All this time, from seven to eleven o'clock P.M.,
must be accounted for satisfactorily before the alibi can be
established. O'Laughlin does not account for all the time, for he left
O'Laughlin after seven o'clock, and rejoined him, as he says, "I
suppose about eight o'clock." Grillet did not meet him until half-past
ten, and then only casually saw him in passing the hotel. May not
Grillet have been mistaken as to the fact, although he did meet
O'Laughlin after eleven o'clock the same evening, as he swears?
Purdy swears to seeing him in the bar with Grillet about half-past
ten, but, as we have seen by Grillet's testimony, it must have been
after eleven o'clock. Murphy contradicts as to time both Grillet and
Purdy, for he says it was half-past eleven or twelve o'clock when he
and O'Laughlin returned to Rullman's from Platz's, and Early swears
the accused went from Rullman's to Second Street to a dance about
a quarter-past eleven o'clock, when O'Laughlin took the lead in the
dance and stayed about one hour. I follow these witnesses no
further. They contradict each other, and do not account for
O'Laughlin all the time from seven to eleven o'clock. I repeat that no
man can read their testimony without finding contradictions most
material as to time, and coming to the conviction that they utterly
fail to account for O'Laughlin's whereabouts on that evening. To
establish an alibi the witnesses must know the fact and testify to it.
Laughlan, Grillet, Purdy, Murphy, and Early utterly fail to prove it,
and only succeed in showing that they did not know where
O'Laughlin was all this time, and that some of them were grossly
mistaken in what they testified, both as to time and place. The
testimony of James B. Henderson is equally unsatisfactory. He is
contradicted by other testimony of the accused as to place. He says
O'Laughlin went up the Avenue above Seventh Street, but that he
did not go to Ninth Street. The other witnesses swear he went to
Ninth Street. He swears he went to Canterbury about nine o'clock,
after going back from Seventh Street to Rullman's. Laughlan swears
that O'Laughlin was with him at the corner of the Avenue and Ninth
Street at nine o'clock, and went from there to Canterbury, while
Early swears that O'Laughlin went up as far as Eleventh Street and
returned with him and took supper at Welcker's about eight o'clock.
If these witnesses prove an alibi, it is really against each other. It is
folly to pretend that they prove facts which make it impossible that
O'Laughlin could have been at the house of Secretary Stanton, as
three witnesses swear he was, on the evening of the 13th of April,
looking for General Grant.
Has it not, by the testimony thus reviewed, been established
prima facie that in the months of February, March, and April,
O'Laughlin had combined, confederated, and agreed with John
Wilkes Booth and Samuel Arnold to kill and murder Abraham Lincoln,
William H. Seward, Andrew Johnson, and Ulysses S. Grant? It is not
established, beyond a shadow of doubt, that Booth had so conspired
with the rebel agents in Canada as early as October last; that he
was in search of agents to do the work on pay, in the interests of
the rebellion, and that in this speculation Arnold and O'Laughlin had
joined as early as February; that then, and after, with Booth and
Surratt, they were in the "oil business," which was the business of
assassination by contract as a speculation? If this conspiracy on the
part of O'Laughlin with Arnold is established even prima facie, the
declarations and acts of Arnold and Booth, the other conspirators, in
furtherance of the common design, is evidence against O'Laughlin as
well as against Arnold himself or the other parties. The rule of law is,
that the act or declaration of one conspirator, done in pursuance or
furtherance of the common design, is the act or declaration of all the
conspirators.—1 Wharton, 706.
The letter, therefore, of his co-conspirator, Arnold, is evidence
against O'Laughlin, because it is an act in the prosecution of the
common conspiracy, suggesting what should be done in order to
make it effective, and which suggestion, as has been stated, was
followed out. The defense has attempted to avoid the force of this
letter by reciting the statement of Arnold, made to Homer at the
time he was arrested, in which he declared, among other things,
that the purpose was to abduct President Lincoln and take him
South; that it was to be done at the theatre by throwing the
President out of the box upon the floor of the stage, when the
accused was to catch him. The very announcement of this testimony
excited derision that such a tragedy meant only to take the President
and carry him gently away! This pigmy to catch the giant as the
assassins hurled him to the floor from an elevation of twelve feet!
The court has viewed the theatre, and must be satisfied that Booth,
in leaping from the President's box, broke his limb. The court cannot
fail to conclude that this statement of Arnold was but another silly
device, like that of the "oil business," which, for the time being, he
employed to hide from the knowledge of his captor the fact that the
purpose was to murder the President. No man can, for a moment,
believe that any one of these conspirators hoped or desired, by such
a proceeding as that stated by this prisoner, to take the President
alive in the presence of thousands assembled in the theatre after he
had been thus thrown upon the floor of the stage, much less to
carry him through the city, through the lines of your army, and
deliver him into the hands of the rebels. No such purpose was
expressed or hinted by the conspirators in Canada, who
commissioned Booth to let these assassinations on contract. I shall
waste not a moment more in combatting such an absurdity.
Arnold does confess that he was a conspirator with Booth in this
purposed, murder; that Booth had a letter of introduction to Dr.
Mudd; that Booth, O'Laughlin, Atzerodt, Surratt, a man with an alias
"Mosby," and another whom he does not know, and himself, were
parties to this conspiracy, and that Booth had furnished them all with
arms. He concludes this remarkable statement to Horner with the
declaration that at that time, to wit, the first week of March, or four
weeks before he went to Fortress Monroe, he left the conspiracy,
and that Booth told him to sell his arms if he chose. This is
sufficiently answered by the fact that, four weeks afterwards, he
wrote his letter to Booth, which was found in Booth's possession
after the assassination, suggesting to him what to do in order to
make the conspiracy a success, and by the further fact that at the
very moment he uttered these declarations part of his arms were
found upon his person, and the rest not disposed of, but at his
father's house.
A party to a treasonable and murderous conspiracy against the
government of his country cannot be held to have abandoned it
because he makes such a declaration as this, when he is in the
hands of the officer of the law, arrested for his crime, and especially
when his declaration is in conflict with and expressly contradicted by
his written acts, and unsupported by any conduct of his which
becomes a citizen and a man.
If he abandoned the conspiracy, why did he not make known the
fact to Abraham Lincoln and his constitutional advisers that these
men, armed with the weapons of assassination, were daily lying in
wait for their lives? To pretend that a man who thus conducts
himself for weeks after the pretended abandonment, volunteering
advice for the successful prosecution of the conspiracy, the evidence
of which is in writing, and about which there can be no mistake, has,
in fact, abandoned it, is to insult the common understanding of men.
O'Laughlin having conspired with Arnold to do this murder, is,
therefore, as much concluded by the letter of Arnold of the 27th of
March as is Arnold himself. The further testimony touching
O'Laughlin, that of Streett, establishes the fact that about the 1st of
April he saw him in confidential conversation with J. Wilkes Booth, in
this city, on the Avenue. Another man, whom the witness does not
know, was in conversation. O'Laughlin called Streett to one side, and
told him Booth was busily engaged with his friend—was talking
privately to his friend. This remark of O'Laughlin is attempted to be
accounted for, but the attempt failed; his counsel taking the pains to
ask what induced O'Laughlin to make the remark, received the fit
reply: "I did not see the interior of Mr. O'Laughlin's mind; I cannot
tell." It is the province of this court to infer why that remark was
made and what it signified.
That John H. Surratt, George A. Atzerodt, Mary E. Surratt, David
E. Herold, and Louis Payne entered into this conspiracy with Booth,
is so very clear upon the testimony that little time need be occupied
in bringing again before the court the evidence which establishes it.
By the testimony of Wiechmann, we find Atzerodt in February at the
house of the prisoner, Mrs. Surratt. He inquired for her or for John
when he came and remained over night. After this and before the
assassination he visited there frequently, and at that house bore the
name of "Port Tobacco," the name by which he was known in
Canada among the conspirators there. The same witness testifies
that he met him on the street, when he said he was going to visit
Payne at the Herndon House, and also accompanied him, along with
Herold and John H. Surratt, to the theatre in March to hear Booth
play in "The Apostate." At the Pennsylvania House, one or two
weeks previous to the assassination, Atzerodt made the statement to
Lieutenant Keim, when asking for his knife which he had left in his
room, a knife corresponding in size with the one exhibited in court,
"I want that; if one fails I want the other," wearing at the same time
his revolver at his belt. He also stated to Greenawalt, of the
Pennsylvania House, in March, that he was nearly broke, but had
friends enough to give him as much money as would see him
through, adding, "I am going away some of these days, but will
return with as much gold as will keep me all my lifetime." Mr.
Greenawalt also says that Booth had frequent interviews with
Atzerodt, sometimes in the room, and at other times Booth would
walk in and immediately go out, Atzerodt following.
John M. Lloyd testifies that some six weeks before the
assassination, Herold, Atzerodt, and John H. Surratt came to his
house at Surrattsville, bringing with them two Spencer carbines with
ammunition, also a rope and wrench. Surratt asked the witness to
take care of them and to conceal the carbines. Surratt took him into
a room in the house, it being his mother's house, and showed the
witness where to put the carbines, between the joists on the second
floor. The carbines were put there, according to his directions, and
concealed. Marcus P. Norton saw Atzerodt in conversation with Booth
at the National Hotel about the 2d or 3d of March; the conversation
was confidential, and the witness accidentally heard them talking in
regard to President Johnson, and say that "the class of witnesses
would be of that character that there could be little proven by
them." This conversation may throw some light on the fact that
Atzerodt was found in possession of Booth's bank book!
Colonel Nevens testifies that on the 12th of April last he saw
Atzerodt at the Kirkwood House; that Atzerodt there asked him, a
stranger, if he knew where Vice-President Johnson was, and where
Mr. Johnson's room was. Colonel Nevens showed him where the
room of the Vice-President was, and told him that the Vice-President
was then at dinner. Atzerodt then looked into the dining-room where
Vice-President Johnson was dining alone. Robert R. Jones, the clerk
at the Kirkwood House, states that on the 14th, the day of the
murder, two days after this, Atzerodt registered his name at the
hotel, G. A. Atzerodt, and took No. 126, retaining the room that day,
and carrying away the key. In this room, after the assassination,
were found the knife and revolver with which he intended to murder
the Vice-President.
The testimony of all these witnesses leaves no doubt that the
prisoner, George A. Atzerodt, entered into this conspiracy with
Booth; that he expected to receive a large compensation for the
service that he would render in its execution; that he had
undertaken the assassination of the Vice-President for a price; that
he, with Surratt and Herold, rendered the important service of
depositing the arms and ammunition to be used by Booth and his
confederates as a protection in their flight after the conspiracy had
been executed; and that he was careful to have his intended victim
pointed out to him, and the room he occupied in the hotel, so that
when he came to perform his horrid work he would know precisely
where to go and whom to strike.
I take no further notice now of the preparation which this
prisoner made for the successful execution of this part of the
traitorous and murderous design. The question is, did he enter into
this conspiracy? His language overheard by Mr. Norton excludes
every other conclusion. Vice-President Johnson's name was
mentioned in that secret conversation with Booth, and the very
suggestive expression was made between them that "little could be
proved by the witnesses." His confession in his defense is conclusive
of his guilt.
That Payne was in this conspiracy is confessed in the defense
made by his counsel, and is also evident, from the facts proved, that
when the conspiracy was being organized in Canada by Thompson,
Sanders, Tucker, Cleary, and Clay, this man Payne stood at the door
of Thompson, was recommended and indorsed by Clay with the
words, "We trust him"; that after coming hither he first reported
himself at the house of Mrs. Mary E. Surratt, inquired for her and for
John H. Surratt, remained there for four days, having conversation
with both of them; having provided himself with means of disguise,
was also supplied with pistols and a knife, such as he afterwards
used, and spurs, preparatory to his flight; was seen with John H.
Surratt, practicing with knives such as those employed in this deed
of assassination and now before the court; was afterwards provided
with lodging at the Herndon House, at the instance of Surratt; was
visited there by Atzerodt, and attended Booth and Surratt to Ford's
Theatre, occupying with those parties the box, as I believe and
which we may readily infer, in which the President was afterwards
murdered.
If further testimony be wanting that he had entered into the
conspiracy, it may be found in the fact sworn to by Wiechmann,
whose testimony no candid man will discredit, that about the 20th of
March, Mrs. Surratt, in great excitement and weeping, said that her
son John had gone away not to return, when, about three hours
subsequently, in the afternoon of the same day, John H. Surratt
reappeared, came rushing in a state of frenzy into the room, in his
mother's house, armed, declaring he would shoot whoever came
into the room, and proclaiming that his prospects were blasted and
his hopes gone; that soon Payne came into the same room, also
armed and under great excitement, and was immediately followed
by Booth, with his riding-whip in his hand, who walked rapidly across
the floor from side to side, so much excited that for some time he
did not notice the presence of the witness. Observing Wiechmann,
the parties then withdrew, upon a suggestion from Booth, to an
upper room, and there had a private interview. From all that
transpired on that occasion, it is apparent that when these parties
left the house that day it was with the full purpose of completing
some act essential to the final execution of the work of
assassination, in conformity with their previous confederation and
agreement. They returned foiled—from what cause is unknown—
dejected, angry, and covered with confusion.
It is almost imposing upon the patience of the court to consume
time in demonstrating the fact which none conversant with the
testimony of this case can for a moment doubt, that John H. Surratt
and Mary E. Surratt were as surely in the conspiracy to murder the
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

More Related Content

PDF
Spring Essentials 1st Edition Kunjumohamed Shameer Sattari Hamidreza
PDF
Cloud Native Spring In Action With Spring Boot And Kubernetes 1st Edition Tho...
PDF
Spring in Action - Sixth Edition (MEAP V04) Craig Walls
PDF
ASP.NET Core Razor Pages in Action 1st Edition Mike Brind
PDF
Azure Infrastructure as Code: With ARM templates and Bicep 1st Edition Henry ...
PDF
Download full ebook of Learning Spring Boot Greg L Turnquist instant download...
PDF
Ionic in Action Hybrid Mobile Apps with Ionic and AngularJS 1st Edition Jerem...
PDF
PDF Spring in Action - Sixth Edition (MEAP V04) Craig Walls download
Spring Essentials 1st Edition Kunjumohamed Shameer Sattari Hamidreza
Cloud Native Spring In Action With Spring Boot And Kubernetes 1st Edition Tho...
Spring in Action - Sixth Edition (MEAP V04) Craig Walls
ASP.NET Core Razor Pages in Action 1st Edition Mike Brind
Azure Infrastructure as Code: With ARM templates and Bicep 1st Edition Henry ...
Download full ebook of Learning Spring Boot Greg L Turnquist instant download...
Ionic in Action Hybrid Mobile Apps with Ionic and AngularJS 1st Edition Jerem...
PDF Spring in Action - Sixth Edition (MEAP V04) Craig Walls download

Similar to Spring Start Here Learn What You Need And Learn It Well 1st Edition Laurentiu Spilc (20)

PDF
ASP.NET Core Razor Pages in Action 1st Edition Mike Brind All Chapters Instan...
PDF
ASP.NET Core Razor Pages in Action 1st Edition Mike Brind
PDF
Cloud Native Spring in Action 1st Edition Thomas Vitale
PDF
Cloud Native Java Designing Resilient Systems with Spring Boot Spring Cloud a...
PDF
Functional Programming in C#: How to write better C# code 1st Edition Enrico ...
PDF
Blazor in Action 1st Edition Chris Sainty
PDF
Azure Infrastructure as Code: With ARM templates and Bicep 1st Edition Henry ...
PDF
Getting Started With Spring Framework J Sharma Ashish Sarin
PDF
Learning Aspnet Core Mvc Programming Mugilan T S Ragupathi
PDF
Cloud Native Java Designing Resilient Systems with Spring Boot Spring Cloud a...
PDF
Tiny C Projects 1st Edition Daniel Gookin
PDF
Rust Web Development With warp tokio and reqwest 1st Edition Bastian Gruber
PDF
(Ebook) JavaScript Application Design: A Build First Approach by Nicolas Be...
PDF
Testing Web APIs 1st Edition Mark Winteringham
PDF
Cloud Native Java Designing Resilient Systems With Spring Boot Spring Cloud A...
PDF
Spring Persistence With Hibernate Ahmad Seddighi
PDF
Build An Orchestrator In Go From Scratch 1 Converted Tim Boring
PDF
Data Pipelines with Apache Airflow 1st Edition Bas P Harenslak Julian Rutger ...
PDF
Managing Kubernetes operating Kubernetes clusters in the real world First Edi...
PDF
Download full Managing Kubernetes operating Kubernetes clusters in the real w...
ASP.NET Core Razor Pages in Action 1st Edition Mike Brind All Chapters Instan...
ASP.NET Core Razor Pages in Action 1st Edition Mike Brind
Cloud Native Spring in Action 1st Edition Thomas Vitale
Cloud Native Java Designing Resilient Systems with Spring Boot Spring Cloud a...
Functional Programming in C#: How to write better C# code 1st Edition Enrico ...
Blazor in Action 1st Edition Chris Sainty
Azure Infrastructure as Code: With ARM templates and Bicep 1st Edition Henry ...
Getting Started With Spring Framework J Sharma Ashish Sarin
Learning Aspnet Core Mvc Programming Mugilan T S Ragupathi
Cloud Native Java Designing Resilient Systems with Spring Boot Spring Cloud a...
Tiny C Projects 1st Edition Daniel Gookin
Rust Web Development With warp tokio and reqwest 1st Edition Bastian Gruber
(Ebook) JavaScript Application Design: A Build First Approach by Nicolas Be...
Testing Web APIs 1st Edition Mark Winteringham
Cloud Native Java Designing Resilient Systems With Spring Boot Spring Cloud A...
Spring Persistence With Hibernate Ahmad Seddighi
Build An Orchestrator In Go From Scratch 1 Converted Tim Boring
Data Pipelines with Apache Airflow 1st Edition Bas P Harenslak Julian Rutger ...
Managing Kubernetes operating Kubernetes clusters in the real world First Edi...
Download full Managing Kubernetes operating Kubernetes clusters in the real w...
Ad

Recently uploaded (20)

PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Sports Quiz easy sports quiz sports quiz
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Basic Mud Logging Guide for educational purpose
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Institutional Correction lecture only . . .
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
Pre independence Education in Inndia.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
01-Introduction-to-Information-Management.pdf
PPTX
Lesson notes of climatology university.
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Insiders guide to clinical Medicine.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Sports Quiz easy sports quiz sports quiz
Final Presentation General Medicine 03-08-2024.pptx
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Basic Mud Logging Guide for educational purpose
Module 4: Burden of Disease Tutorial Slides S2 2025
Anesthesia in Laparoscopic Surgery in India
Institutional Correction lecture only . . .
Microbial disease of the cardiovascular and lymphatic systems
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
Pre independence Education in Inndia.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
human mycosis Human fungal infections are called human mycosis..pptx
01-Introduction-to-Information-Management.pdf
Lesson notes of climatology university.
Pharmacology of Heart Failure /Pharmacotherapy of CHF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Insiders guide to clinical Medicine.pdf
Ad

Spring Start Here Learn What You Need And Learn It Well 1st Edition Laurentiu Spilc

  • 1. Spring Start Here Learn What You Need And Learn It Well 1st Edition Laurentiu Spilc download https://ebookbell.com/product/spring-start-here-learn-what-you- need-and-learn-it-well-1st-edition-laurentiu-spilc-34883312 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Spring Persistence A Running Start 1st Edition Paul Tepper Fisher https://ebookbell.com/product/spring-persistence-a-running-start-1st- edition-paul-tepper-fisher-4201510 Naruto Vol 69 The Start Of A Crimson Spring Masashi Kishimoto https://ebookbell.com/product/naruto-vol-69-the-start-of-a-crimson- spring-masashi-kishimoto-11518468 How To Start A Business Analyst Career 2nd Edition 2nd Edition Laura Brandenburg https://ebookbell.com/product/how-to-start-a-business-analyst- career-2nd-edition-2nd-edition-laura-brandenburg-43232362 Star Spring https://ebookbell.com/product/star-spring-35553234
  • 3. Star Spring Bischoff David https://ebookbell.com/product/star-spring-bischoff-david-8359318 A Maze Of Stars And Spring Water Bing Xin https://ebookbell.com/product/a-maze-of-stars-and-spring-water-bing- xin-48992526 Storm In The Desert Britains Intervention In Libya And The Arab Spring Mark Muller Stuart https://ebookbell.com/product/storm-in-the-desert-britains- intervention-in-libya-and-the-arab-spring-mark-muller-stuart-42885888 Blazing Hot Spring A Blaze Family Romance Collection Fiona Starr Flirt Club https://ebookbell.com/product/blazing-hot-spring-a-blaze-family- romance-collection-fiona-starr-flirt-club-44761374 The Star Harbor Series 4book Bundle Deep Autumn Heat Blaze Of Winter Long Simmering Spring Slow Summer Burn Elisabeth Barrett https://ebookbell.com/product/the-star-harbor-series-4book-bundle- deep-autumn-heat-blaze-of-winter-long-simmering-spring-slow-summer- burn-elisabeth-barrett-47048340
  • 7. Spring Start Here LEARN WHAT YOU NEED AND LEARN IT WELL LAURENŢIU SPILCĂ To comment go to liveBook Manning Shelter Island For more information on this and other Manning titles go to www.manning.com
  • 8. Copyright For online information and ordering of these and other Manning books, please visit www.manning.com. The publisher offers discounts on these books when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: orders@manning.com ©2021 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. ♾ Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Manning Publications Co. 20 Baldwin Road Technical PO Box 761 Shelter Island, NY 11964 Development editor: Marina Michaels Technical development editor: Al Scherer Review editor: Mihaela Batinić Production editor: Andy Marinkovich Copy editor: Michele Mitchell Proofreader: Keri Hales Technical proofreader: Jean-François Morin Typesetter: Gordan Salinović Cover designer: Marija Tudor
  • 10. contents foreword preface acknowledgments about this book about the author about the cover illustration Part 1 Fundamentals 1 Spring in the real world 1.1 Why should we use frameworks? 1.2 The Spring ecosystem Discovering Spring Core: The foundation of Spring Using Spring Data Access feature to implement the app’s persistence The Spring MVC capabilities for developing web apps The Spring testing feature Projects from the Spring ecosystem 1.3 Spring in real-world scenarios Using Spring in the development of a backend app Using Spring in a test automation app Using Spring for the development of a desktop app Using Spring in mobile apps 1.4 When not to use frameworks You need to have a small footprint Security needs dictate custom code Abundant existing customizations make a framework impractical You won’t benefit from switching to a framework 1.5 What will you learn in this book 2 The Spring context: Defining beans 2.1 Creating a Maven project 2.2 Adding new beans to the Spring context Using the @Bean annotation to add beans into the Spring context Using stereotype annotations to add beans to the Spring context Programmatically adding beans to the Spring context 3 The Spring context: Wiring beans 3.1 Implementing relationships among beans defined in the configuration file Wiring the beans using a direct method call between the @Bean methods Wiring the beans using the @Bean annotated method’s parameters 3.2 Using the @Autowired annotation to inject beans Using @Autowired to inject the values through the class fields Using @Autowired to inject the values through the constructor Using dependency injection through the setter 3.3 Dealing with circular dependencies 3.4 Choosing from multiple beans in the Spring context
  • 11. 4 The Spring context: Using abstractions 4.1 Using interfaces to define contracts Using interfaces for decoupling implementations The requirement of the scenario Implementing the requirement without using a framework 4.2 Using dependency injection with abstractions Deciding which objects should be part of the Spring context Choosing what to auto-wire from multiple implementations of an abstraction 4.3 Focusing on object responsibilities with stereotype annotations 5 The Spring context: Bean scopes and life cycle 5.1 Using the singleton bean scope How singleton beans work Singleton beans in real-world scenarios Using eager and lazy instantiation 5.2 Using the prototype bean scope How prototype beans work Prototype beans in real-world scenarios 6 Using aspects with Spring AOP 6.1 How aspects work in Spring 6.2 Implementing aspects with Spring AOP Implementing a simple aspect Altering the intercepted method’s parameters and the returned value Intercepting annotated methods Other advice annotations you can use 6.3 The aspect execution chain Part 2 Implementation 7 Understanding Spring Boot and Spring MVC 7.1 What is a web app? A general overview of a web app Different fashions of implementing a web app with Spring Using a servlet container in web app development 7.2 The magic of Spring Boot Using a project initialization service to create a Spring Boot project Using dependency starters to simplify the dependency management Using autoconfiguration by convention based on dependencies 7.3 Implementing a web app with Spring MVC 8 Implementing web apps with Spring Boot and Spring MVC 8.1 Implementing web apps with a dynamic view Getting data on the HTTP request Using request parameters to send data from client to server Using path variables to send data from client to server 8.2 Using the GET and POST HTTP methods 9 Using the Spring web scopes 9.1 Using the request scope in a Spring web app 9.2 Using the session scope in a Spring web app 9.3 Using the application scope in a Spring web app
  • 12. 10 Implementing REST services 10.1 Using REST services to exchange data between apps 10.2 Implementing a REST endpoint 10.3 Managing the HTTP response Sending objects as a response body Setting the response status and headers Managing exceptions at the endpoint level 10.4 Using a request body to get data from the client 11 Consuming REST endpoints 11.1 Calling REST endpoints using Spring Cloud OpenFeign 11.2 Calling REST endpoints using RestTemplate 11.3 Calling REST endpoints using WebClient 12 Using data sources in Spring apps 12.1 What a data source is 12.2 Using JdbcTemplate to work with persisted data 12.3 Customizing the configuration of the data source Defining the data source in the application properties file Using a custom DataSource bean 13 Using transactions in Spring apps 13.1 Transactions 13.2 How transactions work in Spring 13.3 Using transactions in Spring apps 14 Implementing data persistence with Spring Data 14.1 What Spring Data is 14.2 How Spring Data works 14.3 Using Spring Data JDBC 15 Testing your Spring app 15.1 Writing correctly implemented tests 15.2 Implementing tests in Spring apps Implementing unit tests Implementing integration tests appendix A Architectural approaches appendix B Using XML for the context configuration appendix C A quick introduction to HTTP appendix D Using JSON formatting appendix E Installing MySQL and creating a database appendix F Recommended tools appendix G Recommended learning materials for further study index
  • 13. front matter foreword Born as an alternative to EJBs in the early 2000s, the Spring framework quickly overtook its opponent with the simplicity of its programming model, the variety of its features, and its third-party library integrations. The Spring ecosystem grew over the years into the broadest and most mature development framework available in any programming language. Its main competitor quit the race when Oracle stopped the evolution of Java EE 8, and the community took over its maintenance via Jakarta EE. According to recent surveys (http://mng.bz/l9VB and http://mng.bz/B1Ar), Spring is the framework underlying more than half of the Java applications. This fact builds up an enormous codebase that makes it critical for any Java developer to learn Spring, as it’s inevitable you’ll encounter this technology in your career. I’ve been developing applications with Spring for 15 years, and today the teams that I train in hundreds of companies are almost all using Spring. The reality is that despite being so popular, it’s pretty hard to find quality introductory material. The reference documentation is thousands of pages long, describing all the subtleties and details that could be helpful in very specific scenarios, so it’s not an option for a newcomer. While online videos and tutorials typically fail to engage the student, very few books capture the essence of Spring framework, often spending long pages debating topics that prove to be irrelevant to the problems faced in modern application development. With this book, however, it’s very hard to find anything to remove; all the concepts covered are recurring topics in the development of any Spring application. The reader is gently brought to a level sufficient to become rapidly productive in a project based on the Spring framework. My own experience training thousands of employees showed me that the vast majority of developers working with Spring today don’t see the ideas as clearly as this book paints them. Furthermore, developers are unaware of the many pitfalls about which this book warns its readers. In my opinion, this book is a must- read for any developer starting on their first Spring project. The attention with which Laurenţiu anticipates the typical questions occurring in the reader’s mind proves his extensive experience teaching Spring in class. This teaching fluency allows the author to adopt a personal, warm tone that makes this book an effortless and pleasant read. The book has a clear, sharp structure, and I really loved how complex topics were progressively revealed and explained and reiterated in subsequent chapters. This book shines in that the reader is also introduced to fundamental concerns regarding a legacy project using the Spring framework. In an ecosystem dominated by Spring Boot, I find it very useful to sneak a peek under the hood. On the other end, the book also gently introduces the reader to last-generation technologies, like Feign clients and even reactive programming. I wish you a pleasant reading, and never hesitate to get your hands dirty with some code whenever you think things get complicated.
  • 14. —Victor Rentea Java champion, trainer, and consultant preface Sharing knowledge and creating learning material is a hobby for me. In addition to being a software developer, I’m also a teacher. As a Java trainer since 2009, I’ve taught Java to thousands of developers with various levels of experience, from university students to experienced developers in large corporations. In the past few years, I’ve come to consider Spring a must-learn for beginners. Apps today are no longer implemented with vanilla languages—almost everything relies on frameworks. Since Spring is the most popular application framework in the Java world today, Spring is something a developer needs to learn in their first software development steps. In teaching Spring to beginners, I’ve realized that it is still treated as something you learn only when you already have some experience coding. When I started writing Spring Start Here, there were already plenty of tutorials, books, and articles on the topic, but my students continued to tell me they found those materials hard to understand. I realized the problem was not that the existing learning material wasn’t excellent, but that there was no dedicated study guide for an absolute beginner, so I decided to write a book that doesn’t consider Spring something you learn after you have some experience, but instead something you can learn with minimal foundational knowledge. Technology changes quickly. But it’s not only the technology changing. We also need to consider how we can improve the way we teach these technologies. Some years ago, one would start learning the language fundamentals and get employed as a developer without even knowing what a framework is. But today, these things are different. Learning all the details of a language up-front is no longer the way to quickly develop the skills you need to work in a software development team. Now, I recommend developers start with the fundamentals and, once they feel comfortable with the basics, start learning an application framework. Spring is, in my opinion, the best application framework to start learning. Understanding the Spring basics also opens doors to learning other technologies and changes the old, linear learning approach into something that looks more like a tree—and each branch of the tree is a new framework you learn in parallel with others. I designed Spring Start Here to be the book you want to start learning the Spring framework with. This book leads you step-by-step, providing you with all the essential theoretical knowledge, accompanied by examples that practically apply the discussed topics. I hope this book will bring significant value to you, the reader, and help you quickly boost your Spring knowledge and open doors for further learning. acknowledgments This book wouldn’t be possible without the large number of smart, professional, and friendly people who helped me throughout its development process. First, a big thank you to my wife, Daniela, who was always there for me, and whose valuable opinions, continuous support, and encouragement were a huge help to me.
  • 15. I’d also like to express my gratitude and send special thanks to all the colleagues and friends who helped me from the very first table of contents and proposal with their valuable advice. A big thank you goes to the entire Manning team for their huge help in making this book a reality. I especially want to recognize Marina Michaels, Al Scherer, and Jean-François Morin for always being incredibly supportive and professional. Your advice has brought great value to this book. I’d like to thank my friend Ioana Göz for the drawings she created for the book. She turned my thoughts into the cartoons in the book. I also want to express my appreciation to all the reviewers who provided such useful feedback at every step. To Alain Lompo, Aleksandr Karpenko, Andrea Carlo Granata, Andrea Paciolla, Andres Damian Sacco, Andrew Oswald, Bobby Lin, Bonnie Malec, Christian Kreutzer-Beck, Daniel Carl, David Lisle Orpen, DeUndre’ Rushon, Harinath Kuntamukkala, Håvard Wall, Jérôme Baton, Jim Welch, João Miguel Pires Dias, Lucian Enache, Matt D., Matthew Greene, Mikael Byström, Mladen Knežic´, Nathan B. Crocker, Pierre-Michel Ansel, Rajesh Mohanan, Ricardo Di Pasquale, Sunita Chowdhury, Tan Wee, and Zoheb Ainapore, your input has made this a much better book. Finally, a special thank you to my friends, Maria Chiţu, Andreea Tudose, Florin Ciuculescu, and Daniela Ileana for advising me along the way. about this book Since you’ve opened this book, I assume you’re a software developer in the Java ecosystem who found out it’s useful to learn Spring. This book teaches you the Spring foundations, assuming you know nothing in the first place about frameworks and, of course, about Spring. You’ll start with what a framework is and then gradually learn the basics of Spring with applied examples. You will not only learn to use the framework’s components and capabilities, but you’ll also learn the essentials of what happens behind the scenes in these capabilities. Knowing how the framework operates when you use a particular component helps you design better apps, and solve problems faster. When you finish this book, you’ll have learned the following skills, which are highly relevant in implementing apps: Configuring and using the Spring context and dependency injection with Spring Designing and using aspects Implementing web apps Implementing data exchange between apps Persisting data Testing implementations You’ll find this book is valuable for the following: Working on an app using Spring for your job
  • 16. Succeeding in a technical interview for a Java developer role Obtaining your Spring certification Even if this book’s first purpose is not to prepare you for a Spring certification, I consider it a must-read before digging into details a certification exam typically requires. Who should read this book This book is for developers who understand basic object-oriented programming and Java concepts and want to learn Spring or refresh their Spring fundamentals knowledge. You do not need to have previous experience with any framework, but you need to understand Java because this is the language we use throughout the book’s examples. Spring is one of the most encountered technologies in Java apps and will most likely be used even more in the future. For a Java developer, this makes Spring a must-know today. Learning what I teach you in this book will help you upskill, provide you with the Spring foundation knowledge and skills you need to successfully pass a Java interview, and work on an app using Spring technologies. The book also opens doors to further study Spring details that are more complex. How this book is organized: A roadmap This book is divided into two parts that cover 15 chapters. We’ll start our discussion (in the first part of the book) with straightforward examples to show you how to make Spring aware of your application. We’ll then build examples that enable you to understand the core of any real-world Spring app. Once we finish with Spring Core basics, we’ll discuss Spring Data and Spring Boot basics. From chapter 2 to the end of this book, you’ll find that theoretical aspects are accompanied by projects in which we apply the notions we discuss. I explain the code in these examples snippet by snippet. My recommendation is you build these examples with me while reading. Then, you can compare your result with my solution. As presented in the following figure, I designed the book’s chapters to be read in the given order. In chapters 2 through 5, where we discuss the Spring context, you might find the examples predominantly theoretical. For anyone with little or no experience with Spring, it’s essential to start this way. Don’t worry! I present the foundations in the easiest possible way, and then our examples and discussions gradually become more sophisticated to reflect real-world, production-ready code.
  • 17. Figure 1 If you start with no (or very little) knowledge about Spring, the best way to read the book is to start with the first chapter and read everything in order. If you already understand the Spring context and Spring AOP well, you can skip part 1 and go directly to part 2, “Implementation” (chapters 7-15), as presented in the next figure. Figure 2 If you already understand the Spring framework’s foundation and know how to use the Spring context and design aspects, you can start with part 2, where we use Spring capabilities to implement apps mirroring scenarios you face in real-world systems. Once you finish reading this book, you’ll have learned plenty of skills to develop apps like a professional. You’ll learn to connect to databases using the most encountered techniques today, and you’ll learn how to make apps communicate with each other. We’ll end the book with teaching a critical topic: testing. I’ll season the text here and there by adding stories of my experience and notes with valuable pieces of advice. Remember that Spring is a vast universe, and one book won’t teach you everything about it. With this book, you get started with the framework and learn the fundamental skills of using Spring’s valuable components. Throughout the book, I refer, where appropriate, to other resources and books that detail the topics we discuss. I strongly recommend you read those additional resources and books to broaden your perspective on the discussed topics. About the code The book provides about 70 projects, which we’ll work on in chapters 2 through 14. When
  • 18. working on a specific example, I mention the project’s name, which implements that example. My recommendation is to try to write your example from scratch and then use the provided project only to compare your solution with mine. This approach will help you better understand the concepts you’re learning. Each of the projects is built with Maven, making it easy to import into any IDE. I used IntelliJ IDEA to write the projects, but you can choose to run them in Eclipse, Netbeans, or any other tool of your choice. Appendix F gives you an overview of the recommended tools. This book contains many examples of source code, both in numbered listings and in line with normal text. In both cases, source code is formatted in a fixed-width font like this to separate it from ordinary text. Sometimes code is also in bold to highlight code that has changed from previous steps in the chapter, such as when a new feature adds to an existing line of code. In many cases, the original source code has been reformatted; we’ve added line breaks and reworked indentation to accommodate the available page space in the book. In rare cases, even this was not enough, and listings include line- continuation markers (➥). Additionally, comments in the source code have often been removed from the listings when the code is described in the text. Code annotations accompany many of the listings, highlighting important concepts. liveBook discussion forum Purchase of Spring Start Here includes free access to a private web forum run by Manning Publications where you can make comments about the book, ask technical questions, and receive help from the author and from other users. To access the forum, go to https://livebook.manning.com/#!/book/spring-start-here/discussion. You can also learn more about Manning’s forums and the rules of conduct at https://livebook .manning.com/#!/discussion. Manning’s commitment to our readers is to provide a venue where a meaningful dialogue between individual readers and between readers and the author can take place. It is not a commitment to any specific amount of participation on the part of the author, whose contribution to the forum remains voluntary (and unpaid). We suggest you try asking the author some challenging questions lest his interest stray! The forum and the archives of previous discussions will be accessible from the publisher’s website as long as the book is in print. about the author Laurenţiu Spilcă is a dedicated development lead and trainer at Endava, where he leads the development of projects in the financial market with users in Europe, the US, and Asia. He has over 10 years of experience. Laurenţiu believes it’s important to not only deliver high-quality software, but also share knowledge and help others to upskill. These beliefs have driven him to design and teach courses related to Java technologies and deliver presentations and workshops. His Twitter handle is @laurspilca.
  • 19. about the cover illustration The figure on the cover of Spring Start Here is captioned “Femme d’ajaccio isle de Corse,” or a woman from Ajaccio on the island of Corsica. The illustration is taken from a collection of dress costumes from various countries by Jacques Grasset de Saint-Sauveur (1757- 1810), titled Costumes de Différents Pays, published in France in 1797. Each illustration is finely drawn and colored by hand. The rich variety of Grasset de Saint-Sauveur’s collection reminds us vividly of how culturally apart the world’s towns and regions were just 200 years ago. Isolated from each other, people spoke different dialects and languages. In the streets or in the countryside, it was easy to identify where they lived and what their trade or station in life was just by their dress. The way we dress has changed since then and the diversity by region, so rich at the time, has faded away. It is now hard to tell apart the inhabitants of different continents, let alone different towns, regions, or countries. Perhaps we have traded cultural diversity for a more varied personal life—certainly for a more varied and fast-paced technological life. At a time when it is hard to tell one computer book from another, Manning celebrates the inventiveness and initiative of the computer business with book covers based on the rich diversity of regional life of two centuries ago, brought back to life by Grasset de Saint- Sauveur’s pictures.
  • 20. Part 1 Fundamentals Any building stands on a foundation. A framework is no different in this regard. In part 1, you’ll learn to use the basic components that enable the Spring framework. These components are the Spring context and Spring aspects. Further in the book, you’ll discover that all Spring capabilities rely on these essential components.
  • 21. 1 Spring in the real world This chapter covers What a framework is When to use and when to avoid using frameworks What the Spring framework is Using Spring in real-world scenarios The Spring framework (shortly, Spring) is an application framework that is part of the Java ecosystem. An application framework is a set of common software functionalities that provides a foundation structure for developing an application. An application framework eases the effort of writing an application by taking out the effort of writing all the program code from scratch. We use Spring in the development of many kinds of applications nowadays, from large backend solutions to automation testing apps. According to many survey reports on Java technologies (like this one of JRebel from 2020: http:// mng.bz/N4V7; or this one from JAXEnter: http://mng.bz/DK9a), Spring is the most used Java framework today. Spring is popular, and developers have started to use it more often with other JVM languages than Java as well. In the last few years, we observed an impressive growth of developers using Spring with Kotlin (another appreciated language from the JVM family). In this book, we’ll focus on the foundations of Spring, and I’ll teach you essential skills for using Spring in real-world examples. To make the subject more comfortable for you and allow you to focus on Spring, we’ll use only Java examples. Throughout the book, we’ll discuss and apply, with examples, essential skills like connecting to a database, establishing communication between applications, and securing and testing an app. Before diving into more technical details in the next chapters, let’s talk about the Spring framework and where you’ll actually use it. Why is Spring so appreciated, and when should you even use it? In this chapter, we’ll focus on what a framework is, referring in particular to the Spring framework. In section 1.1, we discuss the advantages of using a framework. In section 1.2, we discuss the Spring ecosystem with the components you need to learn to get started with Spring. Then I’ll take you through possible usages of the Spring framework—in particular, real-world scenarios in section 1.3. In section 1.4, we’ll discuss when using frameworks might not be the right approach. You need to understand all these things about the Spring framework before trying to use it. Otherwise, you might try to use a hammer to dig your garden. Depending on your level, you might feel this chapter difficult. I might introduce some notions that you haven’t heard about, and this aspect might disturb you. But don’t worry; even if you don’t understand some of the things now, they will be clarified later in the book. Sometimes, throughout the book, I’ll refer to something said in earlier chapters. I use this approach because learning a framework like Spring doesn’t always offer us a linear learning path, and sometimes you need to wait until you get more pieces of the puzzle before you
  • 22. see the complete picture. But in the end, you’ll get a clear image, and you’ll get the valuable skills you need to develop apps like a professional. 1.1 Why should we use frameworks? In this section, we discuss frameworks. What are they? How did this concept appear, and why? To be motivated to use something, you need to know how that something brings you value. And that’s also the case with Spring. I’ll teach you these essential details by sharing the knowledge I gathered from my own experience and by studying and using various frameworks in real-world scenarios, including Spring. An application framework is a set of functionalities on top of which we build applications. The application framework provides us a broad set of tools and functionalities that you can use to build apps. You don’t need to use all the features the framework offers. Depending on the requirements of the app you make, you’ll choose the right parts of the framework to use. Here’s an analogy I like for application frameworks. Did you ever buy a piece of furniture from a DIY store like Ikea? Say you buy a wardrobe—you won’t get an assembled wardrobe, but the right components you need to build it and a manual on how to assemble your piece of furniture. Now imagine you ordered a wardrobe, but instead of getting only the right components you need, you get all the possible components you can use to assemble any piece of furniture: a table, a wardrobe, and so on. If you want a wardrobe, you have to find the right parts and assemble them. It’s like an application framework. The application framework offers you various pieces of software you need to build your app. You need to know what features to choose and how to assemble them to achieve the right result (figure 1.1).
  • 23. Figure 1.1 David ordered a wardrobe from the UAssemble store. But the store (framework) doesn’t deliver to David (the programmer) just the components (software capabilities) he needs to build his new wardrobe (the app). The store ships him all the possible parts he might need to build the wardrobe. It’s David’s (the programmer’s) choice on which components (software capabilities) are right and how to assemble them to get the right result (the application). The idea of a framework isn’t new. Throughout the history of software development, programmers observed they could reuse parts of code they’d written in multiple applications. Initially, when not so many applications were implemented, each application was unique and developed from scratch using a specific programming language. When the software development domain extended, and more and more applications started to be published on the market, it became easier to observe that many of these apps had similar requirements. Let’s name a few of them: Logging error, warning, and info messages happen in every app. Most applications use transactions to process data changes. Transactions represent an important mechanism that takes care of data consistency. We’ll discuss this subject in detail in chapter 13. Most applications use protection mechanisms against the same common vulnerabilities. Most applications use similar ways to communicate with each other. Most applications use similar mechanisms to improve their performance, like caching or data compression. And the list continues. It turns out that the business logic code implemented in an app is significantly smaller than the wheels and belts that make the engine of the application (also often referred to as “the plumbing”).
  • 24. When I say “business logic code,” I refer to the code that implements the business requirements of the application. This code is what implements the user’s expectations in an application. For example, “clicking on a specific link will generate an invoice” is something users expect to happen. Some code of the application you develop implements this functionality, and this part of code is what developers call the business logic code. However, any app takes care of several more aspects: security, logging, data consistency, and so on (figure 1.2). Figure 1.2 The user’s perspective is similar to viewing an iceberg. Users mainly observe the results of the business logic code, but this is only a small part of what builds the app’s complete functionality. Like an iceberg that is mostly underwater and hidden from view, we don't see most of the code in an enterprise app because it's provided by dependencies. Moreover, the business logic code is what makes an application different from another from the functionality point of view. If you take two different apps, say a ridesharing system and a social networking app, they have different use cases. NOTE A use case represents the reason a person uses the app. For example, in a ridesharing app, a use case is “requesting a car.” For an app managing food delivery, a use case is “ordering a pizza.” You take different actions, but they both need data storing, data transfer, logging, security configurations, probably caching, and so on. Various applications can reuse these nonbusiness implementations. Is it then efficient to rewrite the same functionalities every time? Of course not: You spare a lot of time and money by reusing something rather than developing it yourself. An existing implementation that many apps already use has fewer chances to introduce bugs, as others have tested it. You benefit from the advice of a community because you now have a lot of developers understanding the same functionality. If you had implemented your own code, only a few people would know it. A story of transition One of the first applications I worked on was a huge system developed in Java. This system was composed of multiple applications
  • 25. designed around an old-fashioned architecture server, all of them written from scratch using Java SE. The development of this application started with the language about 25 years ago. This was the main reason for its shape. And almost no one could have imagined how big it would become. At that time, more advanced concepts of system architectures didn’t exist, and things in general worked differently from the individual systems due to the slow internet connection. But time passed, and years later, the app was more like a big ball of mud. For valid reasons I won’t cover here, the team decided they had to go to a modern architecture. This change implied first cleaning up the code, and one of the main steps was using a framework. We decided to go with Spring. At that time, we had as an alternative Java EE (now named Jakarta EE), but most members of the team considered it’s better to go with Spring, which offered a lighter alternative that was easier to implement and that we also considered easier to maintain. The transition wasn’t an easy one. Together with a few colleagues, experts in their domain and knowledgeable about the application itself, we invested a lot of effort into this transformation. The result was amazing! We removed over 40% of the lines of code. This transition was the first moment I understood how significant the impact of using a framework could be. NOTE Choosing and using a framework is linked to the design and architecture of an application. You’ll find it useful to learn more about these subjects along with learning the Spring framework. In appendix A, you’ll find a discussion about software architectures with excellent resources if you’d like to go into details. 1.2 The Spring ecosystem In this section, we will discuss Spring and related projects like Spring Boot or Spring Data. You’ll learn all about these in this book, and the links among them. In real-world scenarios, it’s common to use different frameworks together, where each framework is designed to help you implement a specific part of the app faster. We refer to Spring as a framework, but it is much more complex. Spring is an ecosystem of frameworks. Usually, when developers refer to the Spring framework, they refer to a part of the software capabilities that include the following: 1. Spring Core—One of the fundamental parts of Spring that includes foundational capabilities. One of these features is the Spring context. As you’ll learn in detail in chapter 2, the Spring context is a fundamental capability of the Spring framework that enables Spring to manage instances of your app. Also, as part of Spring Core, you find the Spring aspects functionality. Aspects help Spring intercept and manipulate methods you define in your app. We discuss more details of the aspects in chapter 6. The Spring Expression Language (SpEL) is another capability you’ll find as part of Spring Core, which enables you to describe configurations for Spring using a specific language. All of these are new notions, and I don’t expect you to know them yet. But soon you’ll understand that Spring Core holds the mechanisms Spring uses to integrate into your app. 2. Spring model-view-controller (MVC)—The part of the Spring framework that enables you to develop web applications that serve HTTP requests. We’ll use Spring MVC starting in chapter 7. 3. Spring Data Access—Also one of the fundamental parts of Spring. It provides basic tools you can use to connect to SQL databases to implement the persistence layer of your app. We’ll use Spring Data Access starting in chapter 13. 4. Spring testing—The part holding the tools you need to write tests for your Spring application. We’ll discuss this subject in chapter 15. You can initially imagine the Spring framework as a solar system, where Spring Core
  • 26. represents the star in the middle, which holds all the framework together (figure 1.3). Figure 1.3 You can imagine the Spring framework as a solar system with the Spring Core in the center. The software capabilities are planets around Spring Core kept close to it by its gravitational field. 1.2.1 Discovering Spring Core: The foundation of Spring Spring Core is the part of the Spring framework that provides the foundational mechanisms to integrate into apps. Spring works based on the principle inversion of control (IoC). When using this principle, instead of allowing the app to control the execution, we give control to some other piece of software—in our case, the Spring framework. Through configurations, we instruct the framework on how to manage the code we write, which defines the logic of the app. Here’s where the “inversion” in IoC comes from: you don’t let the app control the execution by its own code and use dependencies. Instead, we allow the framework (the dependency) to control the app and its code (figure 1.4).
  • 27. Figure 1.4 Inversion of control. Instead of executing its own code, which makes use of several other dependencies, in case of an IoC scenario, the app execution is controlled by the dependency. The Spring framework controls an app during its execution. Therefore, it implements an IoC scenario of execution. NOTE In this context the term “controls” refers to actions like “creating an instance” or “calling a method.” A framework can create objects of the classes you define in your app. Based on the configurations that you write, Spring intercepts the method to augment it with various features. For example, Spring can intercept a specific method to log any error that might appear during the method’s execution. You will start learning Spring with Spring Core by discussing the Spring IoC functionality in chapters 2 through 5. The IoC container glues Spring components and components of your application to the framework together. Using the IoC container, to which you often refer as the Spring context, you make certain objects known to Spring, which enables the framework to use them in the way you configured. In chapter 6, we’ll continue our discussion with Spring aspect-oriented programming (AOP). Spring can control instances added to its IoC container, and one of the things it can do is intercept methods that represent the behavior of these instances. This capability is called aspecting the method. Spring AOP is one of the most common ways the framework interacts with what your app does. This trait makes Spring AOP part of the essentials as well. Part of the Spring Core, we also find resource management, internationalization (i18n), type conversion, and SpEL. We’ll encounter aspects of these features in examples throughout the book. 1.2.2 Using Spring Data Access feature to implement the app’s persistence For most applications, it’s critical to persist part of the data they process. Working with databases is a fundamental subject, and in Spring, it’s the Data Access module that you’ll use to take care of data persistence in many cases. The Spring Data Access includes using JDBC, integrating with object-relational mapping (ORM) frameworks like Hibernate (don’t worry if you don’t yet know what an ORM framework is or haven’t heard about Hibernate; we’ll discuss these aspects later in the book), and managing transactions. In chapters 12 through 14, we’ll cover everything needed to get you started with Spring Data Access. 1.2.3 The Spring MVC capabilities for developing web apps The most common applications developed with Spring are web apps, and within the Spring ecosystem, you’ll find a large set of tools that enables you to write web applications and web services in different fashions. You can use the Spring MVC to develop apps using a standard servlet fashion, which is common in a vast number of applications today. In chapter 7, we’ll go into more detail on using the Spring MVC. 1.2.4 The Spring testing feature The Spring testing module offers us a large set of tools that we’ll use to write unit and integration tests. There have been many pages written about the testing topic, but we’ll discuss everything that is essential to get you started with Spring testing in chapter 15. I’ll also refer to some valuable resources you need to read to get all the details of this topic. My rule of thumb is that you’re not a mature developer if you don’t understand testing, so this topic is one you should care about.
  • 28. 1.2.5 Projects from the Spring ecosystem The Spring ecosystem is so much more than just the capabilities discussed earlier in this section. It includes a big collection of other frameworks that integrate well and form a larger universe. Here we have projects like Spring Data, Spring Security, Spring Cloud, Spring Batch, Spring Boot, and so on. When you develop an app, you can use more of these projects together. For example, you can build an app using all of Spring Boot, Spring Security, and Spring Data. In the next few chapters, we’ll work on smaller projects that make use of various projects of the Spring ecosystem. When I say project, I refer to a part of the Spring ecosystem that is independently developed. Each of these projects has a separate team that works on extending its capabilities. Also, each project is separately described and has its own reference on the Spring official website: https://spring.io/projects. Out of this vast universe created by Spring, we’ll also refer to Spring Data and Spring Boot. These projects are often encountered in apps, so it’s important to get to know them from the beginning. EXTENDING THE PERSISTENCE CAPABILITIES WITH SPRING DATA The Spring Data project implements a part of the Spring ecosystem that enables you to easily connect to databases and use the persistence layer with a minimum number of lines of code written. The project refers to both SQL and NoSQL technologies and creates a high- level layer, which simplifies the way you work with data persistence. NOTE We have Spring Data Access, which is a module of Spring Core, and we also have an independent project in the Spring ecosystem named Spring Data. Spring Data Access contains fundamental data access implementations like the transaction mechanism and JDBC tools. Spring Data enhances access to databases and offers a broader set of tools, which makes development more accessible and enables your app to connect to different kinds of data sources. We’ll discuss this subject in chapter 14. SPRING BOOT Spring Boot is a project part of the Spring ecosystem that introduces the concept of “convention over configuration.” The main idea of this concept is that instead of setting up all the configurations of a framework yourself, Spring Boot offers you a default configuration that you can customize as needed. The result, in general, is that you write less code because you follow known conventions and your app differs from others in few or small ways. So instead of writing all the configurations for each and every app, it’s more efficient to start with a default configuration and only change what’s different from the convention. We’ll discuss more about Spring Boot starting in chapter 7. The Spring ecosystem is vast and contains many projects. Some of them you encounter more often than others, and some you may not use at all if you’re building an application without a particular need. In this book, we refer only to the projects that are essential for you to get started: Spring Core, Spring Data, and Spring Boot. You can find a full list of projects that are part of the Spring ecosystem on the official Spring website: https://spring.io/projects/. Alternatives for using Spring
  • 29. We can’t really discuss alternatives to Spring because someone could misunderstand them as alternatives to the entire ecosystem. But for many of the individual components and projects that create the Spring ecosystem, you can find other options like other open source or commercial frameworks or libraries. For example, let’s take the Spring IoC container. Years ago, the Java EE specification was a solution very much appreciated by the developers. With a slightly different philosophy, Java EE (which in 2017 was open sourced and remade in Jakarta EE, https://jakarta.ee/) offered specifications like Context and Dependency Injection (CDI) or Enterprise Java Beans (EJB). You could use CDI or EJB to manage a context of object instances and implement aspects (named “interceptors” in the EE terminology). Also, throughout history, Google Guice (https://github.com/google/guice) was an appreciated framework for the management of object instances in a container. For some of the projects taken individually, you could find one or more alternatives. For example, you could choose to use Apache Shiro (https://shiro.apache.org/) instead of Spring Security. Or you could decide to implement your web app using the Play framework (https://www.playframework.com/) instead of Spring MVC and Spring-related technologies. A more recent project that looks promising is Red Hat Quarkus. Quarkus is designed for cloud native implementations and becomes more and more mature with rapid steps. I wouldn’t be surprised to see it as one of the lead projects in developing enterprise apps in the Java ecosystem in the future (https://quarkus.io/). My advice for you is to always take into consideration your alternatives. In software development, you need to be open-minded and never trust one solution as being “the one.” You’ll always find scenarios in which a specific technology works better than another. 1.3 Spring in real-world scenarios Now that you have an overview of Spring, you’re aware of when and why you should use a framework. In this section, I’ll give you some application scenarios in which using the Spring framework might be an excellent fit. Too often, I’ve seen developers only refer to backend applications for using a framework like Spring. I’ve even seen a trend of restricting, even more, the scenario to backend web applications. While it’s true that in plenty of cases we see Spring used in this way, it’s important to remember that the framework isn’t limited to this scenario. I’ve seen teams successfully using Spring in different kinds of applications, such as the development of an automation testing app or even in standalone desktop scenarios. I’ll further describe to you some common real-world scenarios in which I’ve seen Spring used successfully. These are not the only possible scenarios, and Spring might not work all the time in these cases. Remember what we discussed in section 1.2: a framework is not always a good choice. But these are common cases in which generally Spring is a good fit: 1. The development of a backend app 2. The development of an automation testing framework 3. The development of a desktop app 4. The development of a mobile app 1.3.1 Using Spring in the development of a backend app A backend application is the part of a system that executes on the server side and has the responsibility of managing data and serving client applications’ requests. The users access functionalities by using the client apps directly. Further, the client apps make requests to the backend app to work with the users’ data. The backend app might use databases to store data or communicate with other backend apps in different fashions. You can imagine, in a real-world scenario, that the app would be the backend application managing the transactions in your bank accounts. Users may access their accounts and
  • 30. manage them via a web application (online banking) or a mobile app. Both the mobile apps and the web apps represent clients for the backend application. To manage users’ transactions, the backend application needs to communicate with other backend solutions, and part of the data it manages needs to be persisted in a database. In figure 1.5, you can visualize the architecture of such a system. Figure 1.5 A backend app interacts in several ways with other apps and uses databases to manage data. Usually, a backend app is complex and may require the use of various technologies. Frameworks simplify the implementation by providing tools you can use to implement the backend solution faster. NOTE Don’t worry if you don’t understand all the details of figure 1.5. I don’t expect you to know what a message broker is and not even how to establish the data exchange among the components. What I want you to see is that such a system can become complex in the real world and then understand that projects from the Spring ecosystem were built to help you eliminate this complexity as much as possible. Spring offers an excellent set of tools for implementing backend applications. It makes your life easier with the different functionalities you generally implement in a backend solution, from integration with other apps to persistence in various database technologies. It’s no wonder developers often use Spring for such applications. The framework basically offers you everything you need in such implementations and is an excellent fit for any kind of architectural style. Figure 1.6 indicates the possibilities of using Spring for a backend app.
  • 31. Figure 1.6 The possibilities of using Spring in a backend application are endless, from exposing functionalities that other applications can call to managing the database access, and from securing the application to managing integration though third-party message brokers. 1.3.2 Using Spring in a automation test app Nowadays, we often use automation testing for end-to-end testing of systems we implement. Automation testing refers to implementing software that development teams use to make sure an application behaves as expected. A development team can schedule the automation testing implementation to frequently test the app and notify the developers if something is wrong. Having such functionality gives developers confidence because they know they’ll be notified if they break anything in the existing capabilities of the app while developing new features. While with small systems you can do the testing manually, it’s always a good idea to automate the test cases. For more complex systems, manually testing all the flows isn’t even an option. Because the flows are so numerous, it’d require a massive number of hours and too much energy to cover it completely. It turns out that the most efficient solution is to have a separate team implement an app that has the responsibility of validating all the flows of the tested system. While developers add new functionalities to the system, this testing app is also enhanced to cover what’s new, and the teams use it to validate that everything still works as desired. The developers eventually use an integration tool and schedule the app to run regularly to get feedback as soon as possible for their changes (figure 1.7).
  • 32. Figure 1.7 The team deploys the testing app in a test environment. A continuous integration tool like Jenkins executes the app regularly and sends feedback to the team. This way, the team is always aware of the system’s status, and they know if they break something during development. Such an application might become as complex as a backend app. In order to validate the flows, the app needs to communicate with the components of the system and even connect to databases. Sometimes the app mocks external dependencies to simulate different execution scenarios. For writing the test scenarios, developers use frameworks like Selenium, Cucumber, Gauge, and others. But, together with these frameworks, the app could still benefit in several ways from Spring’s tools. For example, the app could manage the object instances to make the code more maintainable using the Spring IoC container. It could use Spring Data to connect to the databases where it needs to validate the data. It could send messages to queues or topics of a broker system to simulate specific scenarios or simply use Spring to call some REST endpoints (figure 1.8). (Remember, it’s okay if this looks too advanced; meaning will be clarified as you progress through the book).
  • 33. Figure 1.8 A testing app might need to connect to databases or communicate with other systems or the tested system. The developers can use components of the Spring ecosystem to simplify the implementations of these functionalities. 1.3.3 Using Spring for the development of a desktop app Today, desktop applications are not that frequently developed, as web or mobile apps have taken the role of interacting with the user. However, there’s still a small number of desktop applications, and components of the Spring ecosystem could be a good choice in the development of their features. A desktop app could successfully use the Spring IoC container to manage the object instances. This way, the app’s implementation is cleaner and improves its maintainability. Additionally, the app could potentially use Spring’s tools to implement different features, for example to communicate with a backend or other components (calling web services or using other techniques for remote calls) or implement a caching solution. 1.3.4 Using Spring in mobile apps With its Spring for Android project (https://spring.io/projects/spring-android), the Spring community tries to help the development of mobile applications. Even though you’ll probably rarely encounter this situation, it’s worth mentioning that you can use Spring’s tools to develop Android apps. This Spring project provides a REST client for Android and authentication support for accessing secured APIs.
  • 34. 1.4 When not to use frameworks In this section, we discuss why you should sometimes avoid using frameworks. It’s essential you know when to use a framework and when to avoid using them. Sometimes, using a tool that’s too much for the job might consume more energy and also obtain a worse result. Imagine using a chainsaw to cut bread. While you could try to and even achieve a final result, it’d be more difficult and energy-consuming than using a regular knife (and you may end up with nothing but breadcrumbs instead of sliced bread). We’ll discuss a few scenarios in which using a framework isn’t a great idea, and then I’ll tell you a story about a team I was part of that failed in the implementation of an app because of using a framework. It turns out that, like everything else in software development, you shouldn’t apply a framework in all cases. You’ll find situations in which a framework is not a good fit—or maybe a framework is a good fit, but not the Spring framework. In which of the following scenarios should you consider not using a framework? 1. You need to implement a particular functionality with a footprint as small as possible. By footprint, I mean the storage memory occupied by the app’s files. 2. Specific security requirements force you to implement only custom code in your app without making use of any open source framework. 3. You’d have to make so many customizations over the framework that you’d write more code than if you’d simply not used it at all. 4. You already have a functional app, and by changing it to use a framework you don’t gain any benefit. Let’s discuss these points in more detail. 1.4.1 You need to have a small footprint For point one, I refer to situations in which you need to make your application small. In today’s systems, we find more and more cases in which the services are delivered in containers. You’ve likely heard about containers, such as Docker, Kubernetes, or other terms related to this subject (if not, again, that’s okay). Containers in their entirety is a topic beyond the scope of this book, so for now the only thing I need you to know is that when you use such a deployment fashion, you want your application to be as small as possible. A container is like a box in which your application lives. One crucial principle regarding app deployment in containers is that the containers should be easily disposable: they can be destroyed and recreated as fast as possible. The size of the app (footprint) matters a lot here. You can save seconds from the app initialization by making it smaller. That doesn’t mean you won’t use frameworks for all the apps deployed in containers. But for some apps, which are usually also quite small, it makes more sense to improve their initialization and make their footprint smaller rather than adding dependencies to different frameworks. Such a case is a kind of application called server-less function. These server- less functions are tiny applications deployed in containers. Because you don’t have too much access to the way they’re deployed, it looks like they execute without a server (hence their name). These apps need to be small, and that’s why, for this specific case of apps,
  • 35. you’ll want to avoid adding a framework as much as possible. Because of its size, it’s also possible that you won’t need a framework anyway. 1.4.2 Security needs dictate custom code I said in point two that in specific situations, apps could not use frameworks because of security requirements. This scenario usually happens with apps in the field of defense or governmental organizations. Again, it doesn’t mean all the apps used in governmental organizations are prohibited from using frameworks, but for some, restrictions are applied. You may wonder why. Well, say an open source framework like Spring is used. If someone finds a specific vulnerability, it will become known, and a hacker could use this knowledge to exploit it. Sometimes, stakeholders of such apps want to make sure the chances of someone hacking into their system is as close to zero as possible. This could lead to even rebuilding a functionality instead of using it from a third-party source. NOTE Wait! Earlier I said that it’s more secure to use an open source framework because if a vulnerability exists, someone will likely discover it. Well, if you invest enough time and money, you probably can achieve this yourself as well. In general, it’s cheaper to use a framework, of course. And if you don’t want to be extra cautious, it makes more sense to use a framework. But in some projects, the stakeholders really want to make sure no information becomes public. 1.4.3 Abundant existing customizations make a framework impractical Another case (point three) in which you might want to avoid using a framework is when you’d have to customize its components so much that you end up writing more code than if it hadn’t been used. As I specified in section 1.1, a framework provides you parts that you assemble with your business code to obtain an app. These components, provided by the framework, don’t fit perfectly, and you need to customize them in different ways. It’s perfectly normal to customize the framework’s components and the style in which they assemble than if you’d developed the functionality from scratch. If you find yourself in such a situation, you have probably chosen the wrong framework (search for alternatives) or you shouldn’t use a framework at all. 1.4.4 You won’t benefit from switching to a framework In point four, I mentioned that a potential mistake could be trying to use a framework to replace something that already exists and is working in an app. Sometimes we are tempted to replace an existing architecture with something new. A new framework appears, and it’s popular, and everyone uses it, so why shouldn’t we change our app as well to use this framework? You can, but you need to attentively analyze what you want to achieve by changing something that works. In some cases, like my story from section 1.1, it could be helpful to change your app and make it rely on a specific framework. As long as this change brings a benefit, do it! A reason could be that you want to make the app more maintainable, more performant, or more secure. But if this change doesn’t bring you a benefit, and sometimes it might even bring incertitude, then, in the end, you might discover you invested the time and money for a worse result. Let me tell you a story from my own experience. 1.5 What will you learn in this book
  • 36. Since you opened this book, I assume you’re probably a software developer in the Java ecosystem who found out it’s useful to learn Spring. The purpose of this book is to teach you the foundations of Spring, assuming you know nothing at all about frameworks and, of course, about Spring. When I say Spring, I refer to the Spring ecosystem, not just the core part of the framework. When you finish the book, you will have learned how to do the following: Use the Spring context and implement aspects around objects managed by the framework. Implement the mechanism of a Spring app to connect to a database and work with the persisted data. Establish data exchange between apps using REST APIs implemented with Spring. Build basic apps that use the convention-over-configuration approach. Use best practices in the standard class design of a Spring application. Properly test your Spring implementations. An avoidable mistake Using frameworks isn’t always the best choice, and I had to learn that the hard way. Years earlier, we were working on the backend of a web application. Times influence many things, including software architectures. The app was using JDBC to directly connect to an Oracle database. The code was quite ugly. Everywhere the app needed to execute a query on the database it opened a statement and then sent a query that was sometimes written on multiple rows. You might be young enough not to have encountered JDBC direct usage in apps, but trust me, it’s a long and ugly code. At that time, some frameworks using another methodology to work with the database were becoming more and more popular. I remember when I first encountered Hibernate. This is an ORM framework, which allows you to treat the tables and their relationships in a database as objects and relationships among objects. When used correctly, it enables you to write less code and more intuitive functionality. When misused, it may slow down your app, make the code less intuitive, and even introduce bugs. The application we were developing needed a change. We knew we could improve that ugly JDBC code. In my mind, we could at least minimize the number of lines. This change would have brought great benefits to maintainability. Together with other developers, we suggested using a tool provided by Spring called JdbcTemplate (you’ll learn this tool in chapter 12). But others strongly pushed the decision to use Hibernate. It was quite popular, so why not to use it? (Actually it still is one of the most popular frameworks of its kind, and you’ll learn about integrating it with Spring in chapter 13.) I could see changing that code to a completely new methodology would be a challenge. Moreover, I could see no benefits. The change also implied a greater risk of introducing bugs. Fortunately, the change started with a proof of concept. After a couple of months, lots of effort, and stress, the team decided to quit. After analyzing our options, we finished the implementation using JdbcTemplate. We managed to write cleaner code by eliminating a large number of lines of code, and we didn’t need to introduce any new framework for this change. Summary An application framework is a set of common software functionalities that provides a foundational structure for developing an application. A framework acts as the skeletal support to build an application. A framework helps you build an app more efficiently by providing functionality that you assemble to your implementation instead of developing it yourself. Using a framework saves you time and helps ensure there are fewer chances of implementing buggy features.
  • 37. Using a widely known framework like Spring opens a door to a large community, which makes it more likely that others will faces similar problems. You then have an excellent opportunity to learn about how others solved something similar to an issue you need to address, which will spare you the time of individual research. When implementing an application, always think of all possibilities, including not using a framework. If you decide to use one or more frameworks, take into consideration all their alternatives. You should think about the purpose of the framework, who else is using it (how big the community is), and for how long it’s been on the market (maturity). Spring is not just a framework. We often refer to Spring as “Spring framework” to indicate the core functionalities, but Spring offers an entire ecosystem formed of many projects used in application development. Each project is dedicated to a specific domain, and when implementing an app, you might use more of these projects to implement the functionality you desire. The projects of the Spring ecosystem we’ll use in this book are as follows: Spring Core, which builds the foundation of Spring and provides features like the context, aspects, and basic data access. Spring Data, which provides a high-level, comfortable-to-use set of tools to implement the persistence layer of your apps. You’ll find how easy it is to use Spring Data to work with both SQL and NoSQL databases. Spring Boot, which is a project of the Spring ecosystem that helps you apply a “convention-over-configuration” approach. Quite often, learning materials (like books, articles, or video tutorials) offer examples with Spring only for backend applications. While it’s true that it’s widespread to use Spring with backend apps, you can use Spring with other kinds of apps as well, even in desktop applications and automation testing apps.
  • 38. 2 The Spring context: Defining beans This chapter covers Understanding the need for Spring context Adding new object instances to the Spring context In this chapter, you start learning how to work with a crucial Spring framework element: the context (also known as the application context in a Spring app). Imagine the context as a place in the memory of your app in which we add all the object instances that we want the framework to manage. By default, Spring doesn’t know any of the objects you define in your application. To enable Spring to see your objects, you need to add them to the context. Later in this book we discuss using different capabilities provided by Spring in apps. You’ll learn that plugging in such features is done through the context by adding object instances and establishing relationships among them. Spring uses the instances in the context to connect your app to various functionalities it provides. You’ll learn the basics of the most important features (e.g., transactions, testing, etc.) throughout the book. Learning what Spring context is and how it works is the first step in learning to use Spring, because without knowing how to manage the Spring context, almost nothing else you’ll learn to do with it will be possible. The context is a complex mechanism that enables Spring to control instances you define. This way, it allows you to use the capabilities the framework offers. We start in this chapter by learning how to add object instances to the Spring context. In chapter 3, you’ll learn how to refer to the instances you added and establish relationships among them. We’ll name these object instances “beans.” Of course, for the syntaxes you need to learn we’ll write code snippets, and you can find all these snippets in the projects provided with the book (you can download the projects from the “Book resources” section of the live book). I’ll enhance the code examples with visuals and detailed explanations of the approaches. Because I want to make your introduction to Spring progressive and take everything step by step, in this chapter we focus on the syntaxes you need to know for working with the Spring context. You’ll find out later that not all the objects of an app need to be managed by Spring, so you don’t need to add all the object instances of your app to the Spring context. For the moment, I invite you to focus on learning the approaches for adding an instance for Spring to manage. 2.1 Creating a Maven project In this section, we’ll discuss creating a Maven project. Maven is not a subject directly related to Spring, but it’s a tool you use to easily manage an app’s build process regardless of the framework you use. You need to know Maven project basics to follow the coding examples. Maven is also one of the most used building tools for Spring projects in real-
  • 39. world scenarios (with Gradle, another build tool, taking second place, but we won’t discuss it in this book). Because Maven’s such a well-known tool, you may already know how to create a project and add dependencies to it using its configuration. In this case, you can skip this section and go directly to section 2.2. A build tool is software we use to build apps more easily. You configure a build tool to do the tasks that are part of building the app instead of manually doing them. Some examples of tasks that are often part of building the app are as follows: Downloading the dependencies needed by your app Running tests Validating that the syntax follows rules that you define Checking for security vulnerabilities Compiling the app Packaging the app in an executable archive So that our examples can easily manage dependencies, we need to use a build tool for the projects we develop. This section teaches only what you need to know for developing the examples in this book; we’ll go step by step through the process of creating a Maven project, and I’ll teach you the essentials regarding its structure. If you’d like to learn more details about using Maven, I recommend Introducing Maven: A Build Tool for Today’s Java Developers by Balaji Varanasi (APress, 2019). Let’s start at the very beginning. First, as with developing any other app, you need an integrated development environment (IDE). Any professional IDE nowadays offers support for Maven projects, so you can choose any you’d like: IntelliJ IDEA, Eclipse, Spring STS, Netbeans, and so on. For this book, I use IntelliJ IDEA, which is the IDE I use most often. Don’t worry—the structure of the Maven project is the same regardless of which IDE you choose. Let’s start by creating a new project. You create a new project in IntelliJ from File > New > Project. This will get you to a window like the one in figure 2.1.
  • 40. Figure 2.1 Creating a new Maven project. After going to File > New > Project, you get to this window, where you need to select the type of the project from the left panel. In our case, we choose Maven. In the upper part of the window, you select the JDK you wish to use to compile and run the project. Once you’ve selected the type of your project, in the next window (figure 2.2) you need to give it a name. In addition to the project name and choosing the location in which to store it, for a Maven project you can also specify the following: A group ID, which we use to group multiple related projects An artifact ID, which is the name of the current application A version, which is an identifier of the current implementation state
  • 41. Figure 2.2 Before you finish creating your project, you need to give it a name and specify where you want your IDE to store the project. Optionally, you can give your project a group ID, an artifact ID, and a version. You then press the Finish button in the lower right corner to complete creating the project. In a real-world app, these three attributes are essential details, and it’s important to provide them. But in our case, because we only work on theoretical examples, you can omit them and leave your IDE to fill in some default values for these characteristics. Once you’ve created the project, you’ll find its structure looks like the one presented in figure 2.3. Again, the Maven project structure does not depend on the IDE you choose for developing your projects. When you look first at your project, you observe two main things: The “src” folder (also known as the source folder), where you’ll put everything that belongs to the app. The pom.xml file, where you write the configurations of your Maven project, like adding new dependencies.
  • 42. Figure 2.3 How a Maven project is organized. Inside the src folder, we add everything that belongs to the app: the application’s source code goes into the main folder, and the source code for the unit tests goes into the test folder. In the pom.xml file we write configurations for the Maven project (in our examples we’ll primarily use it to define the dependencies). Maven organizes the “src” folder into the following folders: The “main” folder, where you store the application’s source code. This folder contains the Java code and the configurations separately into two different subfolders named “java” and “resources.” The “test” folder, where you store the unit tests’ source code (we discuss more about unit tests and how to define them in chapter 15). Figure 2.4 shows you how to add new source code to the “main/java” folder of the Maven project. New classes of the app go into this folder.
  • 43. Figure 2.4 Inside the “java” folder, you create the usual Java packages and classes of your application. These are the classes that define the whole logic of your app and make use of the dependencies you provide. In the projects we create in this book, we use plenty of external dependencies: libraries or frameworks we use to implement the functionality of the examples. To add these dependencies to your Maven projects, we need to change the content of the pom.xml file. In the following listing, you find the default content of the pom.xml file immediately after creating the Maven project. Listing 2.1 The default content of the pom.xml file <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>sq-ch2-ex1</artifactId> <version>1.0-SNAPSHOT</version> </project> With this pom.xml file, the project doesn’t use any external dependency. If you look in the project’s external dependencies folder, you should only see the JDK (figure 2.5).
  • 44. Figure 2.5 With a default pom.xml file, your project only uses the JDK as an external dependency. One of the reasons you change the pom.xml file (and the one we’ll use in this book) is to add new dependencies your app needs. The following listing shows you how to add external dependencies to your project. You write all the dependencies between the <dependencies> </dependencies> tags. Each dependency is represented by a <dependency> </dependency> group of tags where you write the dependency’s attributes: the dependency’s group ID, artifact name, and version. Maven will search for the dependency by the values you provided for these three attributes and will download the dependencies from a repository. I won’t go into detail on how to configure a custom repository. You just need to be aware that Maven will download the dependencies (usually jar files) by default from a repository named the Maven central. You can find the downloaded jar files in your project’s external dependencies folder, as presented in figure 2.6. Listing 2.2 Adding a new dependency in the pom.xml file <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>sq_ch2_ex1</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> ❶ <dependency> ❷ <groupId>org.springframework</groupId>
  • 45. <artifactId>spring-jdbc</artifactId> <version>5.2.6.RELEASE</version> </dependency> </dependencies> </project> ❶ You need to write the dependencies for the project between the <dependencies> and </dependecies> tags. ❷ A dependency is represented by a group of <dependency> </dependency> tags. Once you’ve added the dependency in the pom.xml file, as presented in the previous listing, the IDE downloads them, and you’ll now find these dependencies in the “External Libraries” folder (figure 2.6). Figure 2.6 When you add a new dependency to the pom.xml file, Maven downloads the jar files representing that dependency. You find these jar files in the External Libraries folder of the project. Now we can move to the next section, where we discuss the basics of the Spring context. You’ll create Maven projects, and you’ll learn to use a Spring dependency named spring- context, to manage the Spring context. 2.2 Adding new beans to the Spring context In this section, you’ll learn how to add new object instances (i.e., beans) to the Spring context. You’ll find out that you have multiple ways to add beans in the Spring context such that Spring can manage them and plug features it provides into your app. Depending on
  • 46. the action, you’ll choose a specific way to add the bean; we’ll discuss when to select one or another. You can add beans in the context in the following ways (which we’ll describe later in this chapter): Using the @Bean annotation Using stereotype annotations Programmatically Let’s first create a project with a reference to no framework—not even Spring. We’ll then add the dependencies needed to use the Spring context and create it (figure 2.7). This example will serve as a prerequisite to adding beans to the Spring context examples that we’re going to work on in sections 2.2.1 through 2.2.3. Figure 2.7 To start, we create an object instance and the empty Spring context. We create a Maven project and define a class. Because it’s funny to imagine, I’ll consider a class named Parrot with only a String attribute representing the name of the parrot (listing 2.3). Remember, in this chapter, we only focus on adding beans to the Spring context, so it’s okay to use any object that helps you better remember the syntaxes. You find the code for this example in the project “sq-ch2-ex1” (you can download the projects from the “Resources” section of the live book). For your project, you can use the same name or choose the one you prefer. Listing 2.3 The Parrot class public class Parrot { private String name; // Omitted getters and setters } You can now define a class containing the main method and create an instance of the class Parrot, as presented in the following listing. I usually name this class Main.
  • 47. Listing 2.4 Creating an instance of the Parrot class public class Main { public static void main(String[] args) { Parrot p = new Parrot(); } } It’s now time to add the needed dependencies to our project. Because we’re using Maven, I’ll add the dependencies in the pom.xml file, as presented in the following listing. Listing 2.5 Adding the dependency for Spring context <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.example</groupId> <artifactId>sq-ch2-ex1</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>5.2.6.RELEASE</version> </dependency> </dependencies> </project> A critical thing to observe is that Spring is designed to be modular. By modular, I mean that you don’t need to add the whole Spring to your app when you use something out of the Spring ecosystem. You just need to add those parts that you use. For this reason, in listing 2.5, you see that I’ve only added the spring-context dependency, which instructs Maven to pull the needed dependencies for us to use the Spring context. Throughout the book, we’ll add various dependencies to our projects according to what we implement, but we’ll always only add what we need. NOTE You might wonder how I knew which Maven dependency I should add. The truth is that I’ve used them so many times I know them by heart. However, you don’t need to memorize them. Whenever you work with a new Spring project, you can search for the dependencies you need to add directly in the Spring reference (https://docs.spring.io/spring-framework/docs/ current/spring-framework-reference/core.html). Generally, Spring dependencies are part of the org.springframework group ID. With the dependency added to our project, we can create an instance of the Spring context. In the next listing, you can see how I’ve changed the main method to create the Spring context instance. Listing 2.6 Creating the instance of the Spring context public class Main { public static void main(String[] args) { var context = new AnnotationConfigApplicationContext(); ❶ Parrot p = new Parrot(); } } ❶ Creates an instance of the Spring context NOTE We use the AnnotationConfigApplicationContext class to create the Spring context instance. Spring offers multiple
  • 48. implementations. Because in most cases you’ll use the AnnotationConfigApplicationContext class (the implementation that uses the most used today’s approach: annotations), we’ll focus on this one in this book. Also, I only tell you what you need to know for the current discussion. If you’re just getting started with Spring, my recommendation is to avoid getting into details with context implementations and these classes’ inheritance chains. Chances are that if you do you’ll get lost with unimportant details instead of focusing on the essential things. As presented in figure 2.8, you created an instance of Parrot, added the Spring context dependencies to your project, and created an instance of the Spring context. Your objective is to add the Parrot object to the context, which is the next step. Figure 2.8 You created the Spring context instance and a Parrot instance. Now, you want to add the Parrot instance inside the Spring context to make Spring aware of this instance. We just finished creating the prerequisite (skeleton) project, which we’ll use in the next sections to understand how to add beans to the Spring context. In section 2.2.1, we continue learning how to add the instance to the Spring context using the @Bean annotation. Further, in sections 2.2.2 and 2.2.3, you’ll also learn the alternatives of adding the instance using stereotype annotations and doing it programmatically. After discussing all three approaches, we’ll compare them, and you’ll learn the best circumstances for using each. 2.2.1 Using the @Bean annotation to add beans into the Spring context In this section, we’ll discuss adding an object instance to the Spring context using the @Bean annotation. This makes it possible for you to add the instances of the classes defined in your project (like Parrot in our case), as well as classes you didn’t create yourself but you use in your app. I believe this approach is the easiest to understand when starting out. Remember that the reason you learn to add beans to the Spring context is that Spring can manage only the objects that are part of it. First, I’ll give you a
  • 49. straightforward example of how to add a bean to the Spring context using the @Bean annotation. Then I’ll show you how to add multiple beans of the same or different type. The steps you need to follow to add a bean to the Spring context using the @Bean annotation are as follows (figure 2.9): 1. Define a configuration class (annotated with @Configuration) for your project, which, as we’ll discuss later, we use to configure the context of Spring. 2. Add a method to the configuration class that returns the object instance you want to add to the context and annotate the method with the @Bean annotation. 3. Make Spring use the configuration class defined in step 1. As you’ll learn later, we use configuration classes to write different configurations for the framework. Figure 2.9 Steps for adding the bean to the context using the @Bean annotation. By adding the instance to the Spring context, you make the framework aware of the object, enabling it to manage the instance. Let’s follow these steps and apply them in the project named “sq-c2-ex2.” To keep all the steps we discuss separated, I recommend you create new projects for each example. NOTE Remember, you can find the book’s projects in the “Resources” section of the live book. NOTE A configuration class is a special class in Spring applications that we use to instruct Spring to do specific actions. For example, we can tell Spring to create beans or to enable certain functionalities. You will learn different things you can define in configuration classes throughout the rest of the book. STEP 1: DEFINING A CONFIGURATION CLASS IN YOUR PROJECT The first step is to create a configuration class in the project. A Spring configuration class is characterized by the fact that it is annotated with the @Configuration annotation. We use the configuration classes to define various Spring-related configurations for the project.
  • 50. Throughout the book, you’ll learn different things you can configure using the configuration classes. For the moment we focus only on adding new instances to the Spring context. The next listing shows you how to define the configuration class. I named this configuration class ProjectConfig. Listing 2.7 Defining a configuration class for the project @Configuration ❶ public class ProjectConfig { } ❶ We use the @Configuration annotation to define this class as a Spring configuration class. NOTE I separate the classes into different packages to make the code easier to understand. For example, I create the configuration classes in a package named config, and the Main class in a package named main. Organizing the classes into packages is a good practice; I recommend you follow it in your real-world implementations as well. STEP 2: CREATE A METHOD THAT RETURNS THE BEAN, AND ANNOTATE THE METHOD WITH @BEAN One of the things you can do with a configuration class is add beans to the Spring context. To do this, we need to define a method that returns the object instance we wish to add to the context and annotate that method with the @Bean annotation, which lets Spring know that it needs to call this method when it initializes its context and adds the returned value to the context. The next listing shows the changes to the configuration class to implement the current step. NOTE For the projects in this book, I use Java 11: the latest long-term supported Java version. More and more projects are adopting this version. Generally, the only specific feature I use in the code snippets that doesn’t work with an earlier version of Java is the var reserved type name. I use var here and there to make the code shorter and easier to read, but if you’d like to use an earlier version of Java (say Java 8, for example), you can replace var with the inferred type. This way, you’ll make the projects work with Java 8 as well. Listing 2.8 Defining the @Bean method @Configuration public class ProjectConfig { @Bean ❶ Parrot parrot() { var p = new Parrot(); p.setName("Koko"); ❷ return p; ❸ } } ❶ By adding the @Bean annotation, we instruct Spring to call this method when at context initialization and add the returned value to the context. ❷ Set a name for the parrot we’ll use later when we test the app. ❸ Spring adds to its context the Parrot instance returned by the method. Observe that the name I used for the method doesn’t contain a verb. You probably learned that a Java best practice is to put verbs in method names because the methods generally represent actions. But for methods we use to add beans in the Spring context, we don’t follow this convention. Such methods represent the object instances they return and that will now be part of the Spring context. The method’s name also becomes the bean’s name (as in listing 2.8, the bean’s name is now “parrot”). By convention, you can use nouns, and most often they have the same name as the class.
  • 51. STEP 3: MAKE SPRING INITIALIZE ITS CONTEXT USING THE NEWLY CREATED CONFIGURATION CLASS We’ve implemented a configuration class in which we tell Spring the object instance that needs to become a bean. Now we need to make sure Spring uses this configuration class when initializing its context. The next listing shows you how to change the instantiation of the Spring context in the main class to use the configuration class we implemented in the first two steps. Listing 2.9 Initializing the Spring context based on the defined configuration class public class Main { public static void main(String[] args) { var context = new AnnotationConfigApplicationContext( ProjectConfig.class); ❶ } } ❶ When creating the Spring context instance, send the configuration class as a parameter to instruct Spring to use it. To verify the Parrot instance is indeed part of the context now, you can refer to the instance and print its name in the console, as presented in the following listing. Listing 2.10 Referring to the Parrot instance from the context public class Main { public static void main(String[] args) { var context = new AnnotationConfigApplicationContext( ProjectConfig.class); Parrot p = context.getBean(Parrot.class); ❶ System.out.println(p.getName()); } } ❶ Gets a reference of a bean of type Parrot from the Spring context Now you’ll see the name you gave to the parrot you added in the context in the console, in my case Koko. NOTE In real-world scenarios, we use unit and integration tests to validate that our implementations work as desired. The projects in this book implement unit tests to validate the discussed behavior. Because this is a “getting started” book, you might not yet be aware of unit tests. To avoid creating confusion and allow you to focus on the discussed subject, we won’t discuss unit tests until chapter 15. However, if you already know how to write unit tests and reading them helps you better understand the subject, you can find all the unit tests implemented in the test folder of each of our Maven projects. If you don’t yet know how unit tests work, I recommend focusing only on the discussed subject. As in the previous example, you can add any kind of object to the Spring context (figure 2.10). Let’s also add a String and an Integer and see that it’s working.
  • 52. Figure 2.10 You can add any object to the Spring context to make Spring aware of it. The next listing shows you how I changed the configuration class to also add a bean of type String and a bean of type Integer. Listing 2.11 Adding two more beans to the context @Configuration public class ProjectConfig { @Bean Parrot parrot() { var p = new Parrot(); p.setName("Koko"); return p; } @Bean ❶ String hello() { return "Hello"; } @Bean ❷ Integer ten() { return 10; } } ❶ Adds the string “Hello” to the Spring context ❷ Adds the integer 10 to the Spring context NOTE Remember the Spring context’s purpose: we add the instances we expect Spring needs to manage. (This way, we plug in functionalities offered by the framework.) In a real-world app, we won’t add every object to the Spring context. Starting with chapter 4, when our examples will become closer to code in a production-ready app, we’ll also focus more on which objects Spring needs to manage. For the moment, focus on the approaches you can use to add beans to the Spring context. You can now refer to these two new beans in the same way we did with the parrot. The next listing shows you how to change the main method to print the new beans’ values. Listing 2.12 Printing the two new beans in the console public class Main { public static void main(String[] args) { var context = new AnnotationConfigApplicationContext( ProjectConfig.class); Parrot p = context.getBean(Parrot.class); ❶ System.out.println(p.getName()); String s = context.getBean(String.class); System.out.println(s); Integer n = context.getBean(Integer.class);
  • 53. System.out.println(n); } } ❶ You don’t need to do any explicit casting. Spring looks for a bean of the type you requested in its context. If such a bean doesn’t exist, Spring will throw an exception. Running the app now, the values of the three beans will be printed in the console, as shown in the next code snippet. Koko Hello 10 Thus far we added one or more beans of different types to the Spring context. But could we add more than one object of the same type (figure 2.11)? If yes, how can we individually refer to these objects? Let’s create a new project, “sq-ch2-ex3,” to demonstrate how you can add multiple beans of the same type to the Spring context and how you can refer to them afterward. Figure 2.11 You can add more beans of the same type to the Spring context by using multiple methods annotated with @Bean. Each instance will have a unique identifier. To refer to them afterward, you’ll need to use the beans’ identifiers. NOTE Don’t confuse the name of the bean with the name of the parrot. In our example, the beans’ names (or identifiers) in the Spring context are parrot1, parrot2, and parrot3 (like the name of the @Bean methods defining them). The names I gave to the parrots are Koko, Miki, and Riki. The parrot name is just an attribute of the Parrot object, and it doesn’t mean anything to Spring. You can declare as many instances of the same type as you wish by simply declaring more methods annotated with the @Bean annotation. The following listing shows you how I’ve declared three beans of type Parrot in the configuration class. You find this example with the project “sq-ch2-ex3.” Listing 2.13 Adding multiple beans of the same type to the Spring context @Configuration public class ProjectConfig { @Bean Parrot parrot1() { var p = new Parrot(); p.setName("Koko"); return p; }
  • 54. @Bean Parrot parrot2() { var p = new Parrot(); p.setName("Miki"); return p; } @Bean Parrot parrot3() { var p = new Parrot(); p.setName("Riki"); return p; } } Of course, you can’t get the beans from the context anymore by only specifying the type. If you do, you’ll get an exception because Spring cannot guess which instance you’ve declared you refer to. Look at the following listing. Running such a code throws an exception in which Spring tells you that you need to be precise, which is the instance you want to use. Listing 2.14 Referring to a Parrot instance by type public class Main { public static void main(String[] args) { var context = new AnnotationConfigApplicationContext(ProjectConfig.class); Parrot p = context.getBean(Parrot.class); ❶ System.out.println(p.getName()); } } ❶ You’ll get an exception on this line because Spring cannot guess which of the three Parrot instances you refer to. When running your application, you’ll get an exception similar to the one presented by the next code snippet. Exception in thread "main" org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type 'main.Parrot' available: expected single matching bean but found 3: parrot1,parrot2,parrot3 ❶ at ... ❶ Names of the Parrot beans in the context To solve this ambiguity problem, you need to refer precisely to one of the instances by using the bean’s name. By default, Spring uses the names of the methods annotated with @Bean as the beans’ names themselves. Remember that’s why we don’t name the @Bean methods using verbs. In our case, the beans have the names parrot1, parrot2, and parrot3 (remember, the method represents the bean). You can find these names in the previous code snippet in the message of the exception. Did you spot them? Let’s change the main method to refer to one of these beans explicitly by using its name. Observe how I referred to the parrot2 bean in the following listing. Listing 2.15 Referring to a bean by its identifier public class Main { public static void main(String[] args) { var context = new AnnotationConfigApplicationContext(ProjectConfig.class); Parrot p = context.getBean("parrot2", Parrot.class); ❶ System.out.println(p.getName());
  • 55. Discovering Diverse Content Through Random Scribd Documents
  • 56. prisoner—it so impressed his counsel, that they deemed it necessary and absolutely essential to their defense to attempt to destroy the credibility of the witness Wiechmann. I may say here, in passing, that they have not attempted to impeach his general reputation for truth by the testimony of a single witness, nor have they impeached his testimony by calling a single witness to discredit one material fact to which he has testified in this issue. Failing to find a breath of suspicion against Wiechmann's character, or to contradict a single fact to which he testified, the accused had to fly to the last resort, an alibi, and very earnestly did the learned counsel devote himself to the task. It is not material whether this meeting in the hotel took place on the 23d of December or in January. But, says the counsel, it was after the commencement or close of the Congressional holiday. That is not material; but the concurrent resolution of Congress shows that the holiday commenced on the 22d of December, the day before the accused spent the evening in Washington. The witness is not certain about the date of this meeting. The material fact is, did this meeting take place—either on the 23d of December or in January last? Were the private interviews there held, and was the apology made, as detailed, by Mudd and Booth, after the secret conference, to the witness? That the meeting did take place, and that Mudd did explain that these secret interviews, with Booth first, and with Booth and Surratt directly afterward, had relation to the sale of his farm, is confessedly admitted by the endeavor of the prisoner, through his counsel, to show that negotiations had been going on between Booth and Mudd for the sale of Mudd's farm. If no such meeting was held, if no such explanation was made by Mudd to Wiechmann, can any man for a moment believe that a witness would have been called here to give any testimony about Booth having negotiated for Mudd's farm? What conceivable connection has it with this case, except to show that Mudd's explanation to Wiechmann for his extraordinary conduct was in exact accordance with the fact? Or was this testimony about the negotiations for Mudd's farm intended to show so close an intimacy and intercourse with Booth that Mudd
  • 57. could not fail to recognize him when he came flying for aid to his house from the work of assassination? It would be injustice to the able counsel to suppose that. I have said that it was wholly immaterial whether this conversation took place on the 23d of December or in January; it is in evidence that in both these months Booth was at the National Hotel; that he occupied a room there; that he arrived there on the 22d and was there on the 23d of December last, and also on the 12th day of January. The testimony of the witness is, that Booth said he had just come in. Suppose this conversation took place in December, on the evening of the 23d, the time when it is proved by J. T. Mudd, the witness for the accused, that he, in company with Samuel A. Mudd, spent the night in Washington City. Is there anything in the testimony of that or any other witness to show that the accused did not have and could not have had an interview with Booth on that evening? J. T. Mudd testifies that he separated from the prisoner, Samuel A. Mudd, at the National Hotel early in the evening of that day, and did not meet him again until the accused came in for the night at the Pennsylvania House, where he stopped. Where was Dr. Samuel A. Mudd during this interval? What does his witness know about him during that time? How can he say that Dr. Mudd did not go up on Seventh Street in company with Booth, then at the National; that he did not on Seventh Street meet Surratt and Wiechmann; that he did not return to the National Hotel; that he did not have this interview, and afterwards meet him, the witness, as he testifies, at the Pennsylvania House? Who knows that the Congressional holiday had not in fact commenced on that day? What witness has been called to prove that Booth did not on either of those occasions occupy the room that had formerly been occupied by a member of Congress, who had temporarily vacated it, leaving his books there? Wiechmann, I repeat, is not positive as to the date, he is only positive as to the fact; and he disclosed voluntarily to this court that the date could probably be fixed by a reference to the register of the Pennsylvania House; that register cannot, of course, be conclusive of whether Mudd was there in January or not, for the
  • 58. very good reason that the proprietor admits that he did not know Samuel A. Mudd, therefore Mudd might have registered by any other name. Wiechmann does not pretend to know that Mudd had registered at all. If Mudd was here in January, as a party to this conspiracy, it is not at all unlikely that, if he did register at that time in the presence of a man to whom he was wholly unknown, his kinsman not then being with him, he would register by a false name. But if the interview took place in December, the testimony of Wiechmann bears as strongly against the accused as if it had happened in January. Wiechmann says he does not know what time was occupied in this interview at the National Hotel; that it probably lasted twenty minutes; that, after the private interviews between Mudd and Surratt and Booth, which were not of very long duration, had terminated, the parties went to the Pennsylvania House, where Dr. Mudd had rooms, and after sitting together in the common sitting-room of the hotel, they left Dr. Mudd there about ten o'clock P.M., who remained during the night. Wiechmann's testimony leaves no doubt that this meeting on Seventh Street and interview at the National took place after dark, and terminated before or about ten o'clock P.M. His own witness, J. T. Mudd, after stating that he separated from the accused at the National Hotel, says after he had got through a conversation with a gentleman of his acquaintance, he walked down the Avenue, went to several clothing stores, and "after a while" walked round to the Pennsylvania House, and "very soon after" he got there Dr. Mudd came in, and they went to bed shortly afterwards. What time he spent in his "walk alone" on the Avenue, looking at clothing; what period he embraces in the terms "after a while," when he returned to the Pennsylvania House, and "soon after" which Dr. Mudd got there, the witness does not disclose. Neither does he intimate, much less testify, that he saw Dr. Mudd when he first entered the Pennsylvania House on that night after their separation. How does he know that Booth and Surratt and Wiechmann did not accompany Samuel A. Mudd to that house that evening? How does he know that the prisoner and those persons did not converse together some time in the sitting-room of the Pennsylvania Hotel? Jeremiah Mudd has not testified that he met Dr.
  • 59. Mudd in that room, or that he was in it himself. He has, however, sworn to the fact, which is disproved by no one, that the prisoner was separated from him long enough that evening to have had the meeting with Booth, Surratt, and Wiechmann, and the interviews in the National Hotel, and at the Pennsylvania House, to which Wiechmann has testified? Who is there to disprove it? Of what importance is it whether it was on the 23d day of December or in January? How does that affect the credibility of Wiechmann? He is a man, as I have before said, against whose reputation for truth and good conduct they have not been able to bring one witness. If this meeting did by possibility take place that night, is there anything to render it improbable that Booth and Mudd and Surratt did have the conversation at the National Hotel to which Wiechmann testifies? Of what avail, therefore, is the attempt to prove that Mudd was not here during January, if it was clear that he was here on the 23d of December, 1864, and had this conversation with Booth? That this attempt to prove an alibi during January has failed, is quite as clear as is the proof of the fact that the prisoner was here on the evening of the 23d of December, and present in the National Hotel, where Booth stopped. The fact that the prisoner, Samuel A. Mudd, went with J. T. Mudd on that evening to the National Hotel, and there separated from him, is proved by his own witness, J. T. Mudd; and that he did not rejoin him until they retired to bed in the Pennsylvania House is proved by the same witness and contradicted by nobody. Does any one suppose there would have been such assiduous care to prove that the prisoner was with his kinsman all the time on the 23d of December, in Washington, if they had not known that Booth was then at the National Hotel, and that a meeting of the prisoner with Booth, Surratt, and Wiechmann on that day would corroborate and confirm Wiechmann's testimony in every material statement he made concerning that meeting? The accused having signally failed to account for his absence after he separated from his witness, J. T. Mudd, early in the evening of the 23d of December, at the National Hotel, until they had again met at the Pennsylvania House, when they retired to rest, he now
  • 60. attempts to prove an alibi as to the month of January. In this he has failed, as he failed in the attempt to show that he could not have met Booth, Surratt, and Wiechmann on the 23d of December. For this purpose the accused calls Betty Washington. She had been at Mudd's house every night since the Monday after Christmas last, except when here at court, and says that the prisoner, Mudd, has only been away from home three nights during that time. This witness forgets that Mudd has not been at home any night or day since this court assembled. Neither does she account for the three nights in which she swears to his absence from home. First, she says he went to Gardner's party; second, he went to Giesboro, then to Washington. She does not know in what month he was away, the second time, all night. She only knows where he went from what he and his wife said, which is not evidence; but she does testify that when he left home and was absent over night the second time, it was about two or three weeks after she came to his house, which would, if it were three weeks, make it just about the 15th of January, 1865; because she swears she came to his house on the first Monday after Christmas last, which was the 26th day of December; so that the 15th of January would be three weeks, less one day, from that time; and it might have been a week earlier according to her testimony, as, also, it might have been a week earlier, or more, by Wiechmann's testimony, for he is not positive as to the time. What I have said of the register of the Pennsylvania House, the headquarters of Mudd and Atzerodt, I need not here repeat. That record proves nothing, save that Dr. Mudd was there on the 23d of December, which, as we have seen, is a fact, along with others, to show that the meeting at the National then took place. I have also called the attention of the court to the fact that if Mudd was at that house again in January, and did not register his name, that fact proves nothing; or, if he did, the register only proves that he registered falsely; either of which facts might have happened without the knowledge of the witness called by the accused from that house, who does not know Samuel A. Mudd personally.
  • 61. The testimony of Henry L. Mudd, his brother, in support of this alibi, is, that the prisoner was in Washington on the 23d of March, and on the 10th of April, four days before the murder! But he does not account for the absent night in January, about which Betty Washington testifies. Thomas Davis was called for the same purpose, but stated that he was himself absent one night in January, after the 9th of that month, and he could not say whether Mudd was there on that night or not. He does testify to Mudd's absence over night three times, and fixes one occasion on the night of the 26th of January. In consequence of his own absence one night in January, this witness cannot account for the absence of Mudd on the night referred to by Betty Washington. This matter is entitled to no further attention. It can satisfy no one, and the burden of proof is upon the prisoner to prove that he was not in Washington in January last. How can such testimony convince any rational man that Mudd was not here in January, against the evidence of an unimpeached witness, who swears that Samuel A. Mudd was in Washington in the month of January? Who that has been examined here as a witness knows that he was not? The Rev. Mr. Evans swears that he saw him in Washington last winter, and that at the same time he saw Jarboe, the one coming out of, and the other going into, a house on H Street, which he was informed on inquiry was the house of Mrs. Surratt. Jarboe is the only witness called to contradict Mr. Evans, and he leaves it in extreme doubt whether he does not corroborate him, as he swears that he was here himself last winter or fall, but cannot state exactly the time. Jarboe's silence on questions touching his own credibility leaves no room for any one to say that his testimony could impeach Mr. Evans, whatever he might swear. Miss Anna H. Surratt is also called for the purpose of impeaching Mr. Evans. It is sufficient to say of her testimony on that point that she swears negatively only—that she does not see either of the persons named at her mother's house. This testimony neither disproves, nor does it even tend to disprove, the fact put in issue by
  • 62. Mr. Evans. No one will pretend, whatever the form of her expression in giving her testimony, that she could say more than that she did not know the fact, as it was impossible that she could know who was, or who was not, at her mother's house, casually, at a period so remote. It is not my purpose, neither is it needful here, to question in any way the integrity of this young woman. It is further in testimony that Samuel A. Mudd was here on the 3d day of March last, the day preceding the inauguration, when Booth was to strike the traitorous blow; and it was, doubtless, only by the interposition of that God who stands within the shadow and keeps watch above his own, that the victim of this conspiracy was spared that day from the assassin's hand that he might complete his work and see the salvation of his country in the fall of Richmond and the surrender of its great army. Dr. Mudd was here on that day (the 3d of March) to abet, to encourage, to nerve his co-conspirator for the commission of this great crime. He was carried away by the awful purpose which possessed him, and rushed into the room of Mr. Norton, at the National Hotel, in search of Booth, exclaiming excitedly: "I'm mistaken; I thought this was Mr. Booth's room." He is told Mr. Booth is above, on the next floor. He is followed by Mr. Norton, because of his rude and excited behavior, and being followed, conscious of his guilty errand, he turns away, afraid of himself and afraid to be found in concert with his fellow confederate. Mr. Norton identifies the prisoner, and has no doubt that Samuel A. Mudd is the man. The Rev. Mr. Evans also swears that, after the 1st and before the 4th day of March last, he is certain that within that time, and on the 2d or 3d of March, he saw Dr. Mudd drive into Washington City. The endeavor is made by the accused in order to break down this witness, by proving another alibi. The sister of the accused, Miss Fanny Mudd, is called. She testifies that she saw the prisoner at breakfast in her father's house, on the 2d of March, about five o'clock in the morning, and not again until the 3d of March at noon. Mrs. Emily Mudd swears substantially to the same statement. Betty Washington, called for the accused, swears that he was at home all
  • 63. day at work with her on the 2d of March, and took breakfast at home. Frank Washington swears that Mudd was at home all day; that he saw him when he first came out in the morning about sunrise from his own house, and knows that he was there all day with them. Which is correct, the testimony of his sisters or the testimony of his servants? The sisters say that he was at their father's house for breakfast on the morning of the 2d of March; the servants say he was at home for breakfast with them on that day. If this testimony is followed, it proves one alibi too much. It is impossible, in the nature of things, that the testimony of all these four witnesses can be true.
  • 64. Seeing this weakness in the testimony brought to prove this second alibi, the endeavor is next made to discredit Mr. Norton for truth; and two witnesses, not more, are called, who testify that his reputation for truth has suffered by contested litigation between one of the impeaching witnesses and others. Four witnesses are called, who testify that Mr. Norton's reputation for truth is very good; that he is a man of high character for truth, and entitled to be believed whether he speaks under the obligation of an oath or not. The late Postmaster General, Hon. Horatio King, not only sustains Mr. Norton as a man of good reputation for truth, but expressly corroborates his testimony, by stating that in March last, about the 4th of March, Mr. Norton told him the same fact to which he swears here: that a man came into his room under excitement, alarmed his sister, was followed out by himself, and went down stairs instead of going up; and that Mr. Norton told him this before the assassination, and about the time of the inauguration. What motive had Mr. Norton at that time to fabricate this statement? It detracts nothing from his testimony that he did not at that time mention the name of this man to his friend, Mr. King; because it appears from his testimony—and there is none to question the truthfulness of his statement—that at that time he did not know his name. Neither does it take from the force of this testimony, that Mr. Norton did not, in communicating this matter to Mr. King, make mention of Booth's name; because there was nothing in the transaction, at the time, he being ignorant of the name of Mudd, and equally ignorant of the conspiracy between Mudd and Booth, to give the least occasion for any mention of Booth or of the transaction further than as he detailed it. With such corroboration, who can doubt the fact that Mudd did enter the room of Mr. Norton, and was followed by him, on the 3d of March last? Can he be mistaken in the man? Whoever looks at the prisoner carefully once will be sure to recognize him again. For the present I pass from the consideration of the testimony showing Dr. Mudd's connection with Booth in this conspiracy, with the remark that it is in evidence, and I think established, both by the testimony adduced by the prosecution and that by the prisoner, that
  • 65. since the commencement of this rebellion, John H. Surratt visited the prisoner's house; that he concealed Surratt and other rebels and traitors in the woods near his house, where for several days he furnished them with food and bedding; that the shelter of the woods by night and by day was the only shelter that the prisoner dare furnish these friends of his; that in November, Booth visited him and remained over night; that he accompanied Booth at that time to Gardner's, from whom he purchased one of the horses used on the night of the assassination to aid the escape of one of his confederates; that the prisoner had secret interviews with Booth and Surratt, as sworn to by the witness Wiechmann, in the National Hotel, whether on the 23d of December or in January is a matter of entire indifference; that he rushed into Mr. Norton's room on the 3d of March in search of Booth; and that he was here again on the 10th of April, four days before the murder of the President. Of his conduct after the assassination of the President, which is confirmatory of all this—his conspiring with Booth and his sheltering, concealing, and aiding the flight of his co-conspirator, this felon assassin—I shall speak hereafter, leaving him for the present with the remark that the attempt to prove his character has resulted in showing him in sympathy with the rebellion, so cruel that he shot one of his slaves and declared his purpose to send several of them to work on the rebel batteries in Richmond. What others, besides Samuel A. Mudd and John H. Surratt and Lewis Payne, did Booth, after his return from Canada, induce to join him in this conspiracy to murder the President, the Vice-President, the Secretary of State, and the Lieutenant General, with the intent thereby to aid the rebellion and overthrow the government and laws of the United States? On the 10th of February the prisoners Arnold and O'Laughlin came to Washington and took rooms in the house of Mrs. Vantyne; were armed; were then visited frequently by John Wilkes Booth, and alone; were occasionally absent when Booth called, who seemed anxious for their return—would sometimes leave notes for them, and sometimes a request that when they came in they should be told to
  • 66. come to the stable. On the 18th of March last, when Booth played in "The Apostate," the witness, Mrs. Vantyne, received from O'Laughlin complimentary tickets. These persons remained there until the 20th of March. They were visited, so far as the witness knows, during their stay at her house only by Booth, save that on a single occasion an unknown man came to see them, and remained with them over night. They told the witness they were in the "oil business." With Mudd, the guilty purpose was sought to be concealed by declaring that he was in the "land business"; with O'Laughlin and Arnold it was attempted to be concealed by the pretence that they were in the "oil business." Booth, it is proved, had closed up all connection with oil business last September. There is not a word of testimony to show that the accused, O'Laughlin and Arnold, ever invested or sought to invest, in any way or to any amount, in the oil business; their silly words betray them; they forgot when they uttered that false statement that truth is strong, next to the Almighty, and that their crime must find them out was the irrevocable and irresistible law of nature and of nature's God. One of their co-conspirators, known as yet only to the guilty parties to this damnable plot and to the Infinite, who will unmask and avenge all blood-guiltiness, comes to bear witness, unwittingly, against them. This unknown conspirator, who dates his letter at South Branch Bridge, April 6, 1865, mailed and postmarked Cumberland, Md., and addressed to John Wilkes Booth, by his initials, "J. W. B., National Hotel, Washington, D.C.," was also in the "oil speculation." In that letter he says:— "Friend Wilkes:—I received yours of March 12th, and reply as soon as practicable. I saw French, Brady, and others about the oil speculation. The subscription to the stock amounts to eight thousand dollars, and I add one thousand myself, which is about all I can stand. Now, when you sink your well, go deep enough; don't fail; everything depends upon you and your helpers. If you cannot get through on your trip after you strike oil, strike through Thornton gap and across by Capon,
  • 67. Romney, and down the Branch. I can keep you safe from all hardships for a year. I am clear of all surveillance now that infernal Purdy is beat.... "I send this by Tom, and if he don't get drunk you will get it the 9th. At all events, it cannot be understood if lost.... "No more, only Jake will be at Green's with the funds. (Signed) "Lon." That this letter is not a fabrication is made apparent by the testimony of Purdy, whose name occurs in the letter. He testified that he had been a detective in the government service, and that he had been falsely accused, as the letter recites, and put under arrest; that there was a noted rebel, by the name of Green, living at Thornton gap; that there was a servant, who drank, known as "Tom," in the neighborhood of South Branch Bridge; that there is an obscure route through the gap, and as described in the letter; and that a man commonly called "Lon" lives at South Branch Bridge. If the court are satisfied—and it is for them to judge—that this letter was written before the assassination, as it purports to have been, and on the day of its date, there can be no question with any one who reads it that the writer was in the conspiracy, and knew that the time of its execution drew nigh. If a conspirator, every word of its contents is evidence against every other party to this conspiracy. Who can fail to understand this letter? His words, "go deep enough," "don't fail," "everything depends on you and your helpers," "if you can't get through on your trip after you strike oil, strike through Thornton gap," etc., and "I can keep you safe from all hardships for a year," necessarily imply that when he "strikes oil" there will be an occasion for a flight; that a trip, or route, has already been determined upon; that he may not be able to go through by that route; in which event he is to strike for Thornton gap, and across by Capon and Romney, and down the branch, for the shelter which his co-conspirator offers him. "I am clear of all
  • 68. surveillance now"—does any one doubt that the man who wrote those words wished to assure Booth that he was no longer watched, and that Booth could safely hide with him from his pursuers? Does any one doubt, from the further expression in this letter, "Jake will be at Green's with the funds," that this was a part of the price of blood, or that the eight thousand dollars subscribed by others, and the one thousand additional, subscribed by the writer, were also a part of the price to be paid? "The oil business," which was the declared business of O'Laughlin and Arnold, was the declared business of the infamous writer of this letter; was the declared business of John H. Surratt; was the declared business of Booth himself, as explained to Chester and Payne; was "the business" referred to in his telegrams to O'Laughlin, and meant the murder of the President, of his cabinet, and of General Grant. The first of these telegrams is dated Washington, 13th March, and is addressed to M. O'Laughlin, No. 57 North Exeter Street, Baltimore, Md., and is as follows: "Don't you fear to neglect your business; you had better come on at once. J. Booth." The telegraphic operator, Hoffman, who sent this despatch from Washington, swears that John Wilkes Booth delivered it to him in person on the day of its date; and the handwriting of the original telegram is established beyond question to be that of Booth. The other telegram is dated Washington, March 27, addressed, "M. O'Laughlin, Esq., 57 North Exeter Street, Baltimore, Md.," and is as follows: "Get word to Sam. Come on with or without him on Wednesday morning. We sell that day sure; don't fail. J. Wilkes Booth." The original of this telegram is also proved to be in the handwriting of Booth. The sale referred to in this last telegram was doubtless the murder of the President and others—the "oil speculation," in which the writer of the letter from South Branch Bridge, dated April 6, had taken a thousand dollars, and in which Booth said there was money, and Sanders said there was money, and Atzerodt said there was money. The words of this telegram, "get word to Sam," mean Samuel Arnold, his co-conspirator, who had been with him during all his stay in Washington, at Mrs. Vantyne's.
  • 69. These parties to this conspiracy, after they had gone to Baltimore, had additional correspondence with Booth, which the court must infer had relation to carrying out the purposes of their confederation and agreement. The colored witness, Williams, testifies that John Wilkes Booth handed him a letter for Michael O'Laughlin, and another for Samuel Arnold, in Baltimore, some time in March last; one of which he delivered to O'Laughlin at the theatre in Baltimore, and the other to a lady at the door where Arnold boarded in Baltimore. Their agreement and co-operation in the common object having been thus established, the letter written to Booth by the prisoner Arnold, dated March 27, 1865, the handwriting of which is proved before the court, and which was found in Booth's possession after the assassination, becomes testimony against O'Laughlin, as well as against the writer Arnold, because it is an act done in furtherance of their combination. That letter is as follows:— "Dear John:—Was business so important that you could not remain in Baltimore till I saw you? I came in as soon as I could, but found you had gone to Washington. I called also, to see Mike, but learned from his mother he had gone out with you and had not returned. I concluded, therefore, he had gone with you. How inconsiderate you have been! When I left you, you stated that we would not meet in a month or so, and therefore I made application for employment, an answer to which I shall receive during the week. I told my parents I had ceased with you. Can I, then, under existing circumstances, act as you request? You know full well that the government suspicions something is going on there, therefore the undertaking is becoming more complicated. Why not, for the present, desist?—for various reasons, which, if you look into, you can readily see without my making any mention thereof. You, nor any one, can censure me for my present course. You have been its cause, for how can I now come after telling them I had left you? Suspicion rests upon me
  • 70. now from my whole family, and even parties in the country. I will be compelled to leave home any how, and how soon I care not. None, no, not one, were more in favor of the enterprise than myself, and to-day would be there had you not done as you have. By this I mean manner of proceeding. I am, as you well know, in need. I am, you may say, in rags, whereas, to-day, I ought to be well clothed. I do not feel right stalking about with means, and more from appearances a beggar. I feel my dependence. But even all this would have been, and was, forgotten, for I was one with you. Time more propitious will arrive yet. Do not act rashly or in haste. I would prefer your first query, 'Go and see how it will be taken in Richmond,' and ere long I shall be better prepared to again be with you. I dislike writing. Would sooner verbally make known my views. Yet your now waiting causes me thus to proceed. Do not in anger peruse this. Weigh all I have said, and, as a rational man and a friend, you cannot censure or upbraid my conduct. I sincerely trust this, nor aught else that shall or may occur, will ever be an obstacle to obliterate our former friendship and attachment. Write me to Baltimore, as I expect to be in about Wednesday or Thursday; or, if you can possibly come on, I will Tuesday meet you at Baltimore at B. "Ever I subscribe myself, your friend, "Sam." Here is the confession of the prisoner Arnold, that he was one with Booth in this conspiracy; the further confession that they are suspected by the government of their country, and the acknowledgment that since they parted Booth had communicated, among other things, a suggestion which leads to the remark in this letter, "I would prefer your first query, 'Go and see how it will be taken at Richmond,' and ere long I shall be better prepared to again be with you." This is a declaration that affects Arnold, Booth, and O'Laughlin alike, if the court are satisfied, and it is difficult to see how they can have doubt on the subject, that the matter to be
  • 71. referred to Richmond is the matter of the assassination of the President and others, to effect which these parties had previously agreed and conspired together. It is a matter in testimony, by the declaration of John H. Surratt, who is as clearly proved to have been in this conspiracy and murder as Booth himself, that about the very date of this letter, the 27th of March, upon the suggestion of Booth, and with his knowledge and consent, he went to Richmond, not only to see "how it would be taken there," but to get funds with which to carry out the enterprise, as Booth had already declared to Chester in one of his last interviews, when he said that he or "some one of the party" would be constrained to go to Richmond for funds to carry out the conspiracy. Surratt returned from Richmond, bringing with him some part of the money for which he went, and was then going to Canada, and, as the testimony discloses, bringing with him the despatches from Jefferson Davis to his chief agents in Canada, which, as Thompson declared to Conover, made the proposed assassination "all right." Surratt, after seeing the parties here, left immediately for Canada and delivered his despatches to Jacob Thompson, the agent of Jefferson Davis. This was done by Surratt upon the suggestion, or in exact accordance with the suggestion, of Arnold, made on the 27th of March in his letter to Booth just read, and yet you are gravely told that four weeks before the 27th of March Arnold had abandoned the conspiracy. Surratt reached Canada with these despatches, as we have seen, about the 6th or 7th of April last, when the witness Conover saw them delivered to Jacob Thompson and heard their contents stated by Thompson, and the declaration from him that these despatches made it "all right." That Surratt was at that time in Canada is not only established by the testimony of Conover, but it is also in evidence that he told Wiechmann on the 3d of April that he was going to Canada, and on that day left for Canada, and afterwards, two letters addressed by Surratt over the fictitious signature of John Harrison, to his mother and to Miss Ward; dated at Montreal, were received by them on the 14th of April, as testified by Wiechmann and by Miss Ward, a witness called for the defense.
  • 72. Thus it appears that the condition named by Arnold in his letter had been complied with. Booth had "gone to Richmond," in the person of Surratt, "to see how it would be taken." The rebel authorities at Richmond had approved it, the agent had returned; and Arnold was, in his own words, thereby the better prepared to rejoin Booth in the prosecution of this conspiracy. To this end Arnold went to Fortress Monroe. As his letter expressly declares, Booth said when they parted, "we would not meet in a month or so, and therefore I made application for employment—an answer to which I shall receive during the week." He did receive the answer that week from Fortress Monroe, and went there to await the "more propitious time," bearing with him the weapon of death which Booth had provided, and ready to obey his call, as the act had been approved at Richmond and been made "all right." Acting upon the same fact that the conspiracy had been approved in Richmond and the funds provided, O'Laughlin came to Washington to identify General Grant, the person who was to become the victim of his violence in the final consummation of this crime—General Grant, whom, as is averred in the specification, it had become the part of O'Laughlin by his agreement in this conspiracy to kill and murder. On the evening preceding the assassination—the 13th of April—by the testimony of three reputable witnesses, against whose truthfulness not one word is uttered here or elsewhere, O'Laughlin went into the house of the Secretary of War, where General Grant then was, and placed himself in position in the hall where he could see him, having declared before he reached that point, to one of these witnesses, that he wished to see General Grant. The house was brilliantly illuminated at the time; two, at least, of the witnesses conversed with the accused and the other stood very near to him, took special notice of his conduct, called attention to it, and suggested that he be put out of the house, and he was accordingly put out by one of the witnesses. These witnesses are confident, and have no doubt, and so swear upon their oaths, that Michael O'Laughlin is the man who was present on that occasion. There is no denial on the part of the accused that he was
  • 73. in Washington during the day and during the night of April 13, and also during the day and during the night of the 14th; and yet, to get rid of this testimony, recourse is had to that common device—an alibi; a device never, I may say, more frequently resorted to than in this trial. But what an alibi! Nobody is called to prove it, save some men who, by their own testimony, were engaged in a drunken debauch through the evening. A reasonable man who reads their evidence can hardly be expected to allow it to outweigh the united testimony of three unimpeached and unimpeachable witnesses who were clear in their statements, who entertain no doubt of the truth of what they say, whose opportunities to know were full and complete, and who were constrained to take special notice of the prisoner by means of his extraordinary conduct. These witnesses describe accurately the appearance, stature, and complexion of the accused, but because they describe his clothing as dark or black, it is urged that as part of his clothing, although dark, was not black, the witnesses are mistaken. O'Laughlin and his drunken companions (one of whom swears that he drank ten times that evening) were strolling in the streets and in the direction of the house of the Secretary of War, up the Avenue; but you are asked to believe that these witnesses could not be mistaken in saying they were not off the Avenue above Seventh Street, or on K Street. I venture to say that no man who reads their testimony can determine satisfactorily all the places that were visited by O'Laughlin and his drunken associates that evening from seven to eleven o'clock P.M. All this time, from seven to eleven o'clock P.M., must be accounted for satisfactorily before the alibi can be established. O'Laughlin does not account for all the time, for he left O'Laughlin after seven o'clock, and rejoined him, as he says, "I suppose about eight o'clock." Grillet did not meet him until half-past ten, and then only casually saw him in passing the hotel. May not Grillet have been mistaken as to the fact, although he did meet O'Laughlin after eleven o'clock the same evening, as he swears? Purdy swears to seeing him in the bar with Grillet about half-past ten, but, as we have seen by Grillet's testimony, it must have been
  • 74. after eleven o'clock. Murphy contradicts as to time both Grillet and Purdy, for he says it was half-past eleven or twelve o'clock when he and O'Laughlin returned to Rullman's from Platz's, and Early swears the accused went from Rullman's to Second Street to a dance about a quarter-past eleven o'clock, when O'Laughlin took the lead in the dance and stayed about one hour. I follow these witnesses no further. They contradict each other, and do not account for O'Laughlin all the time from seven to eleven o'clock. I repeat that no man can read their testimony without finding contradictions most material as to time, and coming to the conviction that they utterly fail to account for O'Laughlin's whereabouts on that evening. To establish an alibi the witnesses must know the fact and testify to it. Laughlan, Grillet, Purdy, Murphy, and Early utterly fail to prove it, and only succeed in showing that they did not know where O'Laughlin was all this time, and that some of them were grossly mistaken in what they testified, both as to time and place. The testimony of James B. Henderson is equally unsatisfactory. He is contradicted by other testimony of the accused as to place. He says O'Laughlin went up the Avenue above Seventh Street, but that he did not go to Ninth Street. The other witnesses swear he went to Ninth Street. He swears he went to Canterbury about nine o'clock, after going back from Seventh Street to Rullman's. Laughlan swears that O'Laughlin was with him at the corner of the Avenue and Ninth Street at nine o'clock, and went from there to Canterbury, while Early swears that O'Laughlin went up as far as Eleventh Street and returned with him and took supper at Welcker's about eight o'clock. If these witnesses prove an alibi, it is really against each other. It is folly to pretend that they prove facts which make it impossible that O'Laughlin could have been at the house of Secretary Stanton, as three witnesses swear he was, on the evening of the 13th of April, looking for General Grant. Has it not, by the testimony thus reviewed, been established prima facie that in the months of February, March, and April, O'Laughlin had combined, confederated, and agreed with John Wilkes Booth and Samuel Arnold to kill and murder Abraham Lincoln,
  • 75. William H. Seward, Andrew Johnson, and Ulysses S. Grant? It is not established, beyond a shadow of doubt, that Booth had so conspired with the rebel agents in Canada as early as October last; that he was in search of agents to do the work on pay, in the interests of the rebellion, and that in this speculation Arnold and O'Laughlin had joined as early as February; that then, and after, with Booth and Surratt, they were in the "oil business," which was the business of assassination by contract as a speculation? If this conspiracy on the part of O'Laughlin with Arnold is established even prima facie, the declarations and acts of Arnold and Booth, the other conspirators, in furtherance of the common design, is evidence against O'Laughlin as well as against Arnold himself or the other parties. The rule of law is, that the act or declaration of one conspirator, done in pursuance or furtherance of the common design, is the act or declaration of all the conspirators.—1 Wharton, 706. The letter, therefore, of his co-conspirator, Arnold, is evidence against O'Laughlin, because it is an act in the prosecution of the common conspiracy, suggesting what should be done in order to make it effective, and which suggestion, as has been stated, was followed out. The defense has attempted to avoid the force of this letter by reciting the statement of Arnold, made to Homer at the time he was arrested, in which he declared, among other things, that the purpose was to abduct President Lincoln and take him South; that it was to be done at the theatre by throwing the President out of the box upon the floor of the stage, when the accused was to catch him. The very announcement of this testimony excited derision that such a tragedy meant only to take the President and carry him gently away! This pigmy to catch the giant as the assassins hurled him to the floor from an elevation of twelve feet! The court has viewed the theatre, and must be satisfied that Booth, in leaping from the President's box, broke his limb. The court cannot fail to conclude that this statement of Arnold was but another silly device, like that of the "oil business," which, for the time being, he employed to hide from the knowledge of his captor the fact that the purpose was to murder the President. No man can, for a moment,
  • 76. believe that any one of these conspirators hoped or desired, by such a proceeding as that stated by this prisoner, to take the President alive in the presence of thousands assembled in the theatre after he had been thus thrown upon the floor of the stage, much less to carry him through the city, through the lines of your army, and deliver him into the hands of the rebels. No such purpose was expressed or hinted by the conspirators in Canada, who commissioned Booth to let these assassinations on contract. I shall waste not a moment more in combatting such an absurdity. Arnold does confess that he was a conspirator with Booth in this purposed, murder; that Booth had a letter of introduction to Dr. Mudd; that Booth, O'Laughlin, Atzerodt, Surratt, a man with an alias "Mosby," and another whom he does not know, and himself, were parties to this conspiracy, and that Booth had furnished them all with arms. He concludes this remarkable statement to Horner with the declaration that at that time, to wit, the first week of March, or four weeks before he went to Fortress Monroe, he left the conspiracy, and that Booth told him to sell his arms if he chose. This is sufficiently answered by the fact that, four weeks afterwards, he wrote his letter to Booth, which was found in Booth's possession after the assassination, suggesting to him what to do in order to make the conspiracy a success, and by the further fact that at the very moment he uttered these declarations part of his arms were found upon his person, and the rest not disposed of, but at his father's house. A party to a treasonable and murderous conspiracy against the government of his country cannot be held to have abandoned it because he makes such a declaration as this, when he is in the hands of the officer of the law, arrested for his crime, and especially when his declaration is in conflict with and expressly contradicted by his written acts, and unsupported by any conduct of his which becomes a citizen and a man. If he abandoned the conspiracy, why did he not make known the fact to Abraham Lincoln and his constitutional advisers that these
  • 77. men, armed with the weapons of assassination, were daily lying in wait for their lives? To pretend that a man who thus conducts himself for weeks after the pretended abandonment, volunteering advice for the successful prosecution of the conspiracy, the evidence of which is in writing, and about which there can be no mistake, has, in fact, abandoned it, is to insult the common understanding of men. O'Laughlin having conspired with Arnold to do this murder, is, therefore, as much concluded by the letter of Arnold of the 27th of March as is Arnold himself. The further testimony touching O'Laughlin, that of Streett, establishes the fact that about the 1st of April he saw him in confidential conversation with J. Wilkes Booth, in this city, on the Avenue. Another man, whom the witness does not know, was in conversation. O'Laughlin called Streett to one side, and told him Booth was busily engaged with his friend—was talking privately to his friend. This remark of O'Laughlin is attempted to be accounted for, but the attempt failed; his counsel taking the pains to ask what induced O'Laughlin to make the remark, received the fit reply: "I did not see the interior of Mr. O'Laughlin's mind; I cannot tell." It is the province of this court to infer why that remark was made and what it signified. That John H. Surratt, George A. Atzerodt, Mary E. Surratt, David E. Herold, and Louis Payne entered into this conspiracy with Booth, is so very clear upon the testimony that little time need be occupied in bringing again before the court the evidence which establishes it. By the testimony of Wiechmann, we find Atzerodt in February at the house of the prisoner, Mrs. Surratt. He inquired for her or for John when he came and remained over night. After this and before the assassination he visited there frequently, and at that house bore the name of "Port Tobacco," the name by which he was known in Canada among the conspirators there. The same witness testifies that he met him on the street, when he said he was going to visit Payne at the Herndon House, and also accompanied him, along with Herold and John H. Surratt, to the theatre in March to hear Booth play in "The Apostate." At the Pennsylvania House, one or two weeks previous to the assassination, Atzerodt made the statement to
  • 78. Lieutenant Keim, when asking for his knife which he had left in his room, a knife corresponding in size with the one exhibited in court, "I want that; if one fails I want the other," wearing at the same time his revolver at his belt. He also stated to Greenawalt, of the Pennsylvania House, in March, that he was nearly broke, but had friends enough to give him as much money as would see him through, adding, "I am going away some of these days, but will return with as much gold as will keep me all my lifetime." Mr. Greenawalt also says that Booth had frequent interviews with Atzerodt, sometimes in the room, and at other times Booth would walk in and immediately go out, Atzerodt following. John M. Lloyd testifies that some six weeks before the assassination, Herold, Atzerodt, and John H. Surratt came to his house at Surrattsville, bringing with them two Spencer carbines with ammunition, also a rope and wrench. Surratt asked the witness to take care of them and to conceal the carbines. Surratt took him into a room in the house, it being his mother's house, and showed the witness where to put the carbines, between the joists on the second floor. The carbines were put there, according to his directions, and concealed. Marcus P. Norton saw Atzerodt in conversation with Booth at the National Hotel about the 2d or 3d of March; the conversation was confidential, and the witness accidentally heard them talking in regard to President Johnson, and say that "the class of witnesses would be of that character that there could be little proven by them." This conversation may throw some light on the fact that Atzerodt was found in possession of Booth's bank book! Colonel Nevens testifies that on the 12th of April last he saw Atzerodt at the Kirkwood House; that Atzerodt there asked him, a stranger, if he knew where Vice-President Johnson was, and where Mr. Johnson's room was. Colonel Nevens showed him where the room of the Vice-President was, and told him that the Vice-President was then at dinner. Atzerodt then looked into the dining-room where Vice-President Johnson was dining alone. Robert R. Jones, the clerk at the Kirkwood House, states that on the 14th, the day of the murder, two days after this, Atzerodt registered his name at the
  • 79. hotel, G. A. Atzerodt, and took No. 126, retaining the room that day, and carrying away the key. In this room, after the assassination, were found the knife and revolver with which he intended to murder the Vice-President. The testimony of all these witnesses leaves no doubt that the prisoner, George A. Atzerodt, entered into this conspiracy with Booth; that he expected to receive a large compensation for the service that he would render in its execution; that he had undertaken the assassination of the Vice-President for a price; that he, with Surratt and Herold, rendered the important service of depositing the arms and ammunition to be used by Booth and his confederates as a protection in their flight after the conspiracy had been executed; and that he was careful to have his intended victim pointed out to him, and the room he occupied in the hotel, so that when he came to perform his horrid work he would know precisely where to go and whom to strike. I take no further notice now of the preparation which this prisoner made for the successful execution of this part of the traitorous and murderous design. The question is, did he enter into this conspiracy? His language overheard by Mr. Norton excludes every other conclusion. Vice-President Johnson's name was mentioned in that secret conversation with Booth, and the very suggestive expression was made between them that "little could be proved by the witnesses." His confession in his defense is conclusive of his guilt. That Payne was in this conspiracy is confessed in the defense made by his counsel, and is also evident, from the facts proved, that when the conspiracy was being organized in Canada by Thompson, Sanders, Tucker, Cleary, and Clay, this man Payne stood at the door of Thompson, was recommended and indorsed by Clay with the words, "We trust him"; that after coming hither he first reported himself at the house of Mrs. Mary E. Surratt, inquired for her and for John H. Surratt, remained there for four days, having conversation with both of them; having provided himself with means of disguise,
  • 80. was also supplied with pistols and a knife, such as he afterwards used, and spurs, preparatory to his flight; was seen with John H. Surratt, practicing with knives such as those employed in this deed of assassination and now before the court; was afterwards provided with lodging at the Herndon House, at the instance of Surratt; was visited there by Atzerodt, and attended Booth and Surratt to Ford's Theatre, occupying with those parties the box, as I believe and which we may readily infer, in which the President was afterwards murdered. If further testimony be wanting that he had entered into the conspiracy, it may be found in the fact sworn to by Wiechmann, whose testimony no candid man will discredit, that about the 20th of March, Mrs. Surratt, in great excitement and weeping, said that her son John had gone away not to return, when, about three hours subsequently, in the afternoon of the same day, John H. Surratt reappeared, came rushing in a state of frenzy into the room, in his mother's house, armed, declaring he would shoot whoever came into the room, and proclaiming that his prospects were blasted and his hopes gone; that soon Payne came into the same room, also armed and under great excitement, and was immediately followed by Booth, with his riding-whip in his hand, who walked rapidly across the floor from side to side, so much excited that for some time he did not notice the presence of the witness. Observing Wiechmann, the parties then withdrew, upon a suggestion from Booth, to an upper room, and there had a private interview. From all that transpired on that occasion, it is apparent that when these parties left the house that day it was with the full purpose of completing some act essential to the final execution of the work of assassination, in conformity with their previous confederation and agreement. They returned foiled—from what cause is unknown— dejected, angry, and covered with confusion. It is almost imposing upon the patience of the court to consume time in demonstrating the fact which none conversant with the testimony of this case can for a moment doubt, that John H. Surratt and Mary E. Surratt were as surely in the conspiracy to murder the
  • 81. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com