100% found this document useful (5 votes)
184 views

Instant Download Mockito for Spring 1st Edition Acharya Sujoy PDF All Chapters

Mockito

Uploaded by

sazmannafath
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (5 votes)
184 views

Instant Download Mockito for Spring 1st Edition Acharya Sujoy PDF All Chapters

Mockito

Uploaded by

sazmannafath
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Experience Seamless Full Ebook Downloads for Every Genre at textbookfull.

com

Mockito for Spring 1st Edition Acharya Sujoy

https://textbookfull.com/product/mockito-for-spring-1st-
edition-acharya-sujoy/

OR CLICK BUTTON

DOWNLOAD NOW

Explore and download more ebook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Spring Quick Reference Guide: A Pocket Handbook for Spring


Framework, Spring Boot, and More Adam L. Davis

https://textbookfull.com/product/spring-quick-reference-guide-a-
pocket-handbook-for-spring-framework-spring-boot-and-more-adam-l-
davis/
textboxfull.com

Instability in Flow Boiling in Microchannels 1st Edition


Sujoy Kumar Saha

https://textbookfull.com/product/instability-in-flow-boiling-in-
microchannels-1st-edition-sujoy-kumar-saha/

textboxfull.com

Marginalization in Globalizing Delhi Issues of Land


Livelihoods and Health 1st Edition Sanghmitra S. Acharya

https://textbookfull.com/product/marginalization-in-globalizing-delhi-
issues-of-land-livelihoods-and-health-1st-edition-sanghmitra-s-
acharya/
textboxfull.com

Testing Java Microservices Using Arquillian Hoverfly


AssertJ JUnit Selenium and Mockito 1st Edition Andy
Gumbrecht
https://textbookfull.com/product/testing-java-microservices-using-
arquillian-hoverfly-assertj-junit-selenium-and-mockito-1st-edition-
andy-gumbrecht/
textboxfull.com
Two-Phase Heat Transfer Enhancement Sujoy Kumar Saha

https://textbookfull.com/product/two-phase-heat-transfer-enhancement-
sujoy-kumar-saha/

textboxfull.com

Mountain Spring Fever Spring s Mountain Men 1st Edition


Andrea Marie Marie Andrea

https://textbookfull.com/product/mountain-spring-fever-spring-s-
mountain-men-1st-edition-andrea-marie-marie-andrea/

textboxfull.com

Performance Evaluation Criteria in Heat Transfer


Enhancement Sujoy Kumar Saha

https://textbookfull.com/product/performance-evaluation-criteria-in-
heat-transfer-enhancement-sujoy-kumar-saha/

textboxfull.com

Spring Data 1st Edition Petri Kainulainen

https://textbookfull.com/product/spring-data-1st-edition-petri-
kainulainen/

textboxfull.com

Spring Cookbook 1st Edition Jaglale Jerome

https://textbookfull.com/product/spring-cookbook-1st-edition-jaglale-
jerome/

textboxfull.com
Mockito for Spring

Learn all you need to know about the Spring Framework


and how to unit test your projects with Mockito

Sujoy Acharya

BIRMINGHAM - MUMBAI
Mockito for Spring

Copyright © 2015 Packt Publishing

All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy
of the information presented. However, the information contained in this book is
sold without warranty, either express or implied. Neither the author, nor Packt
Publishing, and its dealers and distributors will be held liable for any damages
caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.

First published: February 2015

Production reference: 1200215

Published by Packt Publishing Ltd.


Livery Place
35 Livery Street
Birmingham B3 2PB, UK.

ISBN 978-1-78398-378-0

www.packtpub.com
Credits

Author Project Coordinator


Sujoy Acharya Milton Dsouza

Reviewers Proofreaders
Carlo Micieli Martin Diver
Gualtiero Testa Maria Gould
Paul Hindle
Commissioning Editor
Amarabha Banerjee Indexer
Monica Ajmera Mehta
Acquisition Editor
Llewellyn Rozario Production Coordinator
Aparna Bhagat
Content Development Editor
Parita Khedekar Cover Work
Aparna Bhagat
Technical Editors
Manal Pednekar
Chinmay S. Puranik

Copy Editors
Dipti Kapadia
Deepa Nambiar
Vikrant Phadke
About the Author

Sujoy Acharya works as a software architect with Siemens Technology and


Services Pvt. Ltd. (STS). He grew up in a joint family and pursued his graduation in
the fields of computer science and engineering. His hobbies are watching movies and
sitcoms, playing outdoor sports, and reading books.

Sujoy likes to research upcoming technologies. His major contributions are in the
fields of Java, J2EE, SOA, Ajax, GWT, and the Spring Framework.

He has authored three books for Packt Publishing, namely Test-Driven Development
with Mockito, Mastering Unit Testing using Mockito and JUnit, and Mockito Essentials.

He designs and develops healthcare software products. He has over 11 years


of experience in the industry and has architected and implemented large-scale
enterprise solutions.

I'd especially like to thank my wife, Sunanda, firstly for pushing me


to man up and finish the book, and additionally, for her patience and
endless support in the many hours spent on reviewing my draft and
providing valuable inputs.

I would also like to thank my mother and late father for their
support, blessings, and encouragement.

To my 23-month-old kid, Abhigyan, I am sorry I couldn't be around


as much as we all wanted and for the many times I had to get you
away from the laptop. I love you very much.
About the Reviewers

Carlo Micieli has been a software developer since 2001, developing applications
for computer-aided manufacturing with C#.

His main area of interest is application life cycle management, with a strong focus on
topics such as software design and testing.

He is a programming languages enthusiast, and he's currently trying to learn Scala and
Haskell. He shares his experiments on GitHub (http://github.com/CarloMicieli).

Gualtiero Testa is a software analyst, architect, and developer involved in Java


enterprise-level web applications, mainly in the domains of banking, health, and
government agencies. He lives in Pavia, Italy.

His main interests are test-driven development (TDD), testing tools and
methodologies, and everything related to code quality.

You can reach him through his blog at http://www.gualtierotesta.it/.

I would like to thank my wife, Alessandra, and my daughters, Giulia


and Francesca, because they are the source of my happiness.
www.PacktPub.com

Support files, eBooks, discount offers, and more


For support files and downloads related to your book, please visit www.PacktPub.com.

Did you know that Packt offers eBook versions of every book published, with PDF
and ePub files available? You can upgrade to the eBook version at www.PacktPub.
com and as a print book customer, you are entitled to a discount on the eBook copy.
Get in touch with us at service@packtpub.com for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign
up for a range of free newsletters, and receive exclusive discounts and offers on
Packt books and eBooks.
TM

https://www2.packtpub.com/books/subscription/packtlib

Do you need instant solutions to your IT questions? PacktLib is Packt's online digital
book library. Here, you can search, access, and read Packt's entire library of books.

Why subscribe?
• Fully searchable across every book published by Packt
• Copy and paste, print, and bookmark content
• On demand and accessible via a web browser

Free access for Packt account holders


If you have an account with Packt at www.PacktPub.com, you can use this to access
PacktLib today and view nine entirely free books. Simply use your login credentials
for immediate access.
Table of Contents
Preface 1
Chapter 1: Getting Familiar with the Spring Framework 7
Getting started with Spring 7
Exploring the Spring architecture 11
The core container 11
The AOP module 11
The instrumentation module 11
The messaging module 12
The data access module 12
The web layer 12
The test module 13
Learning the Inversion of Control 13
Printing Hello World 19
Examining life cycle messages 21
Working with autowiring and annotations 22
Working with aspects 24
Exploring Spring JDBC 29
Handling a transaction with Spring 36
Working with declarative Spring transaction 40
Exploring transaction attributes 43
Using the @Transactional annotation 45
Working with a programmatic Spring transaction 47
Using TransactionTemplate 48
Using PlatformTransactionManager 48
Building an MVC application with Spring 49
Summary 54
Table of Contents

Chapter 2: Working with JUnit and Mockito 55


Learning unit testing 55
Working with the JUnit framework 57
Configuring Eclipse 58
Examining annotations 59
Verifying an expectation with an assertion 62
Examining exception handling 66
Working with the @RunWith annotation 67
Working with test suites 68
Working with assertThat 69
Exploring equalTo, is, and not 70
Exploring compound matchers – either, both, anyOf, and allOf 71
Exploring collection matchers – hasItem and hasItems 72
Working with string matchers – startsWith, endsWith, and containsString 73
Exploring custom matchers 73
Working with Mockito 77
Learning the significance of Mockito 77
Exploring Mockito 78
Configuring Mockito 78
Mocking in action 79
Mocking objects 81
Stubbing methods 83
Throwing exceptions 89
Summary 90
Chapter 3: Working with Spring Tests 91
Exploring the TestContext framework 92
Writing a custom TestExecutionListener interface 94
Configuring Spring profiles 98
Mocking an environment 101
Mocking the JNDI lookup 105
Using ReflectionTestUtils 107
Working with annotations 108
Testing Spring MVC 110
Mocking the servlet container with MockMvc 115
Handling transactions in Spring tests 118
Summary 122

[ ii ]
Table of Contents

Chapter 4: Resolving Out-of-container Dependencies


with Mockito 123
Unit testing the web layer 124
Unit testing the service layer 132
Unit testing the data access layer 137
Summary 142
Chapter 5: Time Travelling with Spring 143
Discovering the new Spring release 143
Working with asynchronous tasks 144
Exploring @RestController 147
Learning AsyncRestTemplate 150
Caching objects 153
Summary 158
Index 159

[ iii ]
Preface
When I was writing the first draft of this book, I was eager to compare the
manuscript with other books on the Spring Framework. Here are the features
that distinguish this book from others:

• This book is not only about the Spring Framework. It also describes the basics
of Spring, Spring's test module, Spring's integration testing, JUnit testing,
how to mock Spring beans with Mockito, and advanced Spring 4.1 features.
I couldn't find any books that cover these topics.
• This book explains JUnit testing and mocking in the context of Spring.
• The book covers Spring's test module and Spring integration testing in detail.
These are the most difficult parts in the Spring testing world.

I have taken a hands-on approach here by combining theories with examples to


explain the topics.

What this book covers


Chapter 1, Getting Familiar with the Spring Framework, covers the basics of Spring,
Spring projects, and especially the Spring Framework. It explores the Spring
container, the life cycle of beans, dependency injection, AOP, Spring MVC, and
Spring transaction management.

Chapter 2, Working with JUnit and Mockito, covers both basic and advanced JUnit
usages. It covers annotation-based JUnit testing, assertion, the @RunWith annotation,
exception handling, and the Eclipse setup to run JUnit tests, matchers, and
assertThat, as well as the custom lessThanOrEqual() matcher. The Working
with Mockito section explores the Mockito framework and provides technical
examples to demonstrate the capability of Mockito.
Preface

Chapter 3, Working with Spring Tests, illustrates every aspect of unit testing your
Spring applications. It starts with TestContext and explores the JUnit 4 enabled
SpringJUnit4ClassRunner. Then, it explores Spring profiles that can be used to
work with the different sets of configuration files as well as the Spring environment
and how to mock the environment with MockEnvironment and MockPropertySource.
We use the ReflectionTestUtils method to access the private fields of the Spring
beans. The chapter provides usage examples of Spring annotations for testing, unit
tests the MVC application with MockHttpServletRequest, MockHttpSession, and
ModelAndViewAssert, and mocks the servlet container with MockMvc to handle actual
requests and responses, as they will be at runtime. You will also perform real Spring
integration and transaction management with annotations such as @Transactional,
@TransactionConfiguration, and @Rollback.

Chapter 4, Resolving Out-of-container Dependencies with Mockito, deals with unit testing
the service layer in isolation from the data access layer with Mockito, unit testing the
Spring data access layer with Mockito, and unit testing the Spring presentation layer
(MVC) with Mockito.
Chapter 5, Time Travelling with Spring, starts by covering the features of the new major
Spring release 4.0, such as Java 8 support and so on. Then, we pick the four Spring
4 topics and explore them one by one. The Working with asynchronous tasks section
showcases the execution of long running methods asynchronously and provides
examples to handle asynchronous processing. The Exploring @RestController section
eases RESTful web service development with the advent of the @RestController
annotation. The Learning AsyncRestTemplate section explains the RESTful client code
to invoke RESTful web services asynchronously. Caching is inevitable for high
performant, scalable web applications. This section explains EhCache and Spring
integration to achieve a high availability caching solution.

What you need for this book


You will need the following software installed before you run the examples:

• Java 7 or higher: JDK 1.7 or higher can be downloaded from http://www.


oracle.com/technetwork/java/javase/downloads/index.html.
• Eclipse editor: The latest version of Eclipse is Luna (4.4.1), which can be
downloaded from http://www.eclipse.org/downloads/.
• Mockito: This is required for the creation and verification of mock objects
and for stubbing. Mockito can be downloaded from https://code.google.
com/p/mockito/downloads/list.
• Spring modules: These are used for coding and testing. Spring JARs can be
downloaded from http://maven.springframework.org/release/org/
springframework/spring/.

[2]
Preface

Who this book is for


This book is for advanced and novice-level software testers/developers using the
Spring Framework, Mockito, and JUnit. You should have a reasonable amount of
knowledge and understanding of unit testing elements and applications.

It is ideal for developers who have some experience in Java application development
and the Spring Framework as well as some basic knowledge of JUnit testing. However,
it also covers the basic fundamentals of JUnit testing, the Spring Framework, and the
Mockito framework to get you acquainted with these concepts before you use them.

Conventions
In this book, you will find a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions,
pathnames, dummy URLs, user input, and Twitter handles are shown as follows:
"The messaging module comes with key abstractions from the Spring Integration
project such as Message, MessageChannel, and MessageHandler to serve as a
foundation for messaging-based applications."

A block of code is set as follows:


@Test
public void currencyRoundsOff() throws Exception {
assertNotNull(CurrencyFormatter.format(100.999));
assertTrue(CurrencyFormatter.format(100.999).
contains("$"));
assertEquals("$101.00", CurrencyFormatter.format(100.999));
}

When we wish to draw your attention to a particular part of a code block, the
relevant lines or items are set in bold:
public class LocaleTest {
private Locale defaultLocale;
@Before
public void setUp() {
defaultLocale = Locale.getDefault();
Locale.setDefault(Locale.GERMANY);
}

[3]
Preface

@After
public void restore() {
Locale.setDefault(defaultLocale);
}
@Test
public void currencyRoundsOff() throws Exception {
assertEquals("$101.00", CurrencyFormatter.format(100.999));
}
}

New terms and important words are shown in bold. Words that you see on the
screen, in menus or dialog boxes for example, appear in the text like this: "Right-click
on the project; a pop-up menu will appear. Expand the Build Path menu and click on
the Configure Build Path menu item."

Warnings or important notes appear in a box like this.

Tips and tricks appear like this.

Reader feedback
Feedback from our readers is always welcome. Let us know what you think about
this book—what you liked or may have disliked. Reader feedback is important for
us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to feedback@packtpub.com,


and mention the book title via the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing
or contributing to a book, see our author guide on www.packtpub.com/authors.

Customer support
Now that you are the proud owner of a Packt book, we have a number of things to
help you to get the most from your purchase.

[4]
Preface

Downloading the example code


You can download the example code files for all Packt books you have purchased
from your account at http://www.packtpub.com. If you purchased this book
elsewhere, you can visit http://www.packtpub.com/support and register to have
the files e-mailed directly to you.

Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do
happen. If you find a mistake in one of our books—maybe a mistake in the text or the
code—we would be grateful if you would report this to us. By doing so, you can save
other readers from frustration and help us improve subsequent versions of this book.
If you find any errata, please report them by visiting http://www.packtpub.com/
submit-errata, selecting your book, clicking on the errata submission form link,
and entering the details of your errata. Once your errata are verified, your submission
will be accepted and the errata will be uploaded on our website, or added to any list
of existing errata, under the Errata section of that title. Any existing errata can be
viewed by selecting your title from http://www.packtpub.com/support.

Piracy
Piracy of copyright material on the Internet is an ongoing problem across all media.
At Packt, we take the protection of our copyright and licenses very seriously. If you
come across any illegal copies of our works, in any form, on the Internet, please
provide us with the location address or website name immediately so that we
can pursue a remedy.

Please contact us at copyright@packtpub.com with a link to the suspected


pirated material.

We appreciate your help in protecting our authors, and our ability to bring you
valuable content.

Questions
You can contact us at questions@packtpub.com if you are having a problem with
any aspect of the book, and we will do our best to address it.

[5]
Getting Familiar with
the Spring Framework
Spring is a popular enterprise application development framework. This chapter
covers the following topics:

• Spring Framework fundamentals


• Spring projects
• The Spring architecture and modules
• Inversion of control (IoC) and dependency injection (DI)
• Setting up a Spring development environment, a Hello World program,
and autowiring
• Aspect-oriented Programming (AOP)
• Spring JDBC
• Transaction management
• Spring MVC

Getting started with Spring


Spring is an open source enterprise application development framework for Java.
It was first written by Rod Johnson and released under the Apache 2.0 license in
June 2003.

Spring Framework provides comprehensive infrastructure support for developing


Java applications. Spring handles the infrastructure for us and allows us to focus on
our application logic. Spring enables us to build applications from Plain Old Java
Objects (POJOs) and apply enterprise services non-invasively to POJOs.
Getting Familiar with the Spring Framework

The following are examples of POJO-based application development:

• A Java method can handle an HTTP POST/GET request; you don't have to
write a servlet or work with servlet APIs
• A Java method can act as a RESTful web service without dealing with web
service APIs
• A Java method can execute a database transaction without dealing with
transaction APIs
• A local Java method can participate in a remote procedure call (RPC)
without having to deal with remote APIs
• A Java method can consume or handle messages without having to deal with
JMS APIs
• A Java method can work as a management extension without dealing with
JMX APIs

In a nutshell, Spring can be described as follows:

• An open source application framework


• One of the available enterprise application frameworks and a lightweight
solution for enterprise applications
• Non-invasive (POJO-based)
• Modular
• Extensible for other frameworks
• The de facto standard of Java enterprise applications

The following are advantages of Spring:

• Lightweight and minimally invasive development with POJOs


• Loose coupling through dependency injection and interface-orientation
• Declarative programming through aspects and common conventions
• Boilerplate code reduction through aspects and templates

Spring projects provide infrastructure for building security configuration,


web applications, big data, LDAP, and so on. Spring Framework is one of
the Spring projects.

[8]
Chapter 1

There are various Spring projects that can be used. In this book, we'll be using
Spring 4.

The following are the icons of some Spring projects:

IO PLATFORM BOOT
SPRING FRAMEWORK SPRING XD

SPRING CLOUD
INTEGRATION BATCH
SPRING DATA

The following are all Spring projects as of September 2014:

• The Spring IO platform: Spring IO brings together the core Spring APIs into
a cohesive and versioned foundational platform for modern applications.
Spring IO is comprised of the Spring IO Foundation and Spring IO
Execution layers.
• Spring Boot: This helps in creating production-grade Spring applications
that can be run any time with the minimal Spring configuration. It follows
the convention-over-configuration approach.

• Spring Framework: This is an open source framework for Java enterprise


applications. It provides an inversion of control container for Java beans. The
framework offers a number of templates for the developers; the templates hide
the infrastructure code and allow us to concentrate on the business logic.
• Spring XD: This is a unified, distributed, and extensible system for data
ingestion, real-time analytics, batch processing, and data export. The goal
of the project is to simplify the development of big data applications.
• Spring Cloud: Spring Cloud builds on Spring Boot by providing a bunch
of libraries that enhance the behavior of an application when added to the
classpath. You can take advantage of the basic default behavior to get started
really quickly, and then when you need to, you can configure or extend it to
create a custom solution.
• Spring Data: This simplifies data access, offers APIs to work with the
relational databases, NoSQL or non-relational databases, big data or
the map-reduce algorithm, and so on.

[9]
Getting Familiar with the Spring Framework

• Spring Integration: This follows Enterprise Integration Patterns (EIP) to


enable us lightweight, POJO-based messaging for Spring applications to
integrate with external systems.
• Spring Batch: This is a lightweight, comprehensive batch framework
designed to enable the development of robust batch applications vital
for the daily operations of enterprise systems.
The following image displays the icons of the following spring projects:
security, HATEOAS, social, AMQP, web services, Mobile, Android, web
flow, Spring LDAP and Grails

SECURITY SPRING HATEOAS SPRING SOCIAL SPRING AMQP WEB SERVICES

SPRING MOBILE ANDROID WEB FLOW SPRING LDAP GRAILS

• Spring Security: This is a powerful and highly customizable authentication


and access-control framework. It is the de facto standard for securing
Spring-based applications.
• Spring HATEOAS: This allows you to create REST representations that
follow the HATEOAS principle from your Spring-based applications.
• Spring Social: Connect your Spring application with Software as a Service
(SaaS) API providers such as Facebook, Twitter, and LinkedIn.
• Spring AMQP: The Advanced Message Queuing Protocol (AMQP) is
an open standard for messaging. Spring AMQP offers solutions for
AMQP-based messaging, for example, it can be used with the AMQP
broker RabbitMQ.
• Spring Mobile: This is an extension to Spring MVC that aims to simplify the
development of mobile web applications.
• Spring for Android: This is an extension of Spring Framework that aims to
simplify the development of native Android applications.

[ 10 ]
Chapter 1

• Spring Web Flow: This provides the infrastructure to build process


workflows for web-based Spring applications, such as page navigation,
navigation triggers, application state, and services to invoke. This is stateful
and can be a short-lived process flow or long-running flow.
• Spring Web Services: This aims to facilitate contract-first SOAP service
development, and this allows the creation of flexible web services using
one of the many ways to manipulate XML payloads.
• Spring LDAP: This makes it easier to build Spring-based applications that
use the Lightweight Directory Access Protocol (LDAP).

Exploring the Spring architecture


Spring Framework is modular, and its features are organized into different
modules. This section talks about core Spring modules. The following are the
Spring 4 modules:

The core container


The core container holds the backbone of Spring Framework. The following are the
submodules in the core container:

• Core and Beans: These provide the fundamental parts of the framework,
including IoC and dependency injection features
• Context: This is a means to access objects in a framework-style manner that is
similar to the JNDI registry
• Expression Language: This is also known as SpEL; it is an expression
language used to query and modify an object graph and evaluate
mathematical expressions

The AOP module


AOP is an aspect-oriented programming implementation of Spring. It decouples
the business logic from the cross-cutting infrastructure code, such as logging
and security.

The instrumentation module


The instrumentation module provides class instrumentation support for the Spring
application. Instrumentation exposes container resources through MBean and helps
in JMX management.

[ 11 ]
Getting Familiar with the Spring Framework

The messaging module


The messaging module comes with key abstractions from the Spring Integration
project such as Message, MessageChannel, and MessageHandler to serve as a
foundation for messaging-based applications.

The data access module


The following are the submodules in the data access module:

• JDBC: This provides a JDBC abstraction layer


• ORM: This provides integration layers for popular object-relational mapping
APIs, including JPA, JDO, Hibernate, and iBATIS
• OXM: This provides an abstraction layer that supports object/XML mapping
implementations for JAXB, Castor, XMLBeans, JiBX, and Xstream
• JMS: This contains features to produce and consume messages
• Transactions: This supports programmatic and declarative transaction
management

The web layer


The web layer consists of the web, webmvc/servlet, WebSocket, and webmvc-portlet
modules:

• Web: This module provides basic web-oriented integration features such


as multipart file upload functionality and initialization of the IoC container
using servlet listeners and web-oriented application context. It also contains
the web-related parts of Spring's remoting support.
• Webmvc: This module (also known as the web-servlet module) contains
Spring's model-view-controller implementation for web applications.
Spring's MVC framework provides a clean separation between the domain
model code and web forms and integrates with all the other features of
Spring Framework.
• Portlet: This module (also known as the web-portlet module) provides the
MVC implementation to be used in a portlet environment and mirrors the
functionality of the webmvc module.
• WebSocket: This module provides APIs for two-way communication
between client and server. It is extremely useful when the client and server
need to exchange events at high frequency and low latency. Prime candidates
include applications in finance, games, collaboration, and so on.

[ 12 ]
Chapter 1

The test module


The test module supports the unit testing and integration testing of Spring
components with JUnit or TestNG.

The following figure represents the Spring 4 modules:

Data Access Web

JDBC ORM WebSocket Servlet

OXM JMS

Web Portlet
Transactions

AOP Aspects Messaging Instrumentation

Core Container

Beans Core Context SpEL

Test

Learning the Inversion of Control


Inversion of Control (IoC) and dependency injection (DI) are used interchangeably.
IoC is achieved through DI. DI is the process of providing dependencies and IoC is the
end result of DI. Spring's IoC container enforces the DI pattern for your components,
and this leaves them loosely coupled and allows you to code to abstractions.

Dependency injection is a style of object configuration in which an object's fields and


collaborators are set by an external entity. In other words, objects are configured
by an external entity. Dependency injection is an alternative to having the object
configure itself. This might sound a bit vague, so let's look at a simple example.

After visiting the Packt Publishing website, you can search books by the author's
name or different criteria. We'll look at the service that lists books by author.

[ 13 ]
Getting Familiar with the Spring Framework

The following interface defines book retrieval:


public interface BookService {
List<Book> findAll();
}

The following class lists books by author names:


public class BookLister {

private BookService bookFinder = new BookServiceImpl();

public List<Book> findByAuthor(String author){


List<Book> books = new ArrayList<>();

for(Book aBook:bookFinder.findAll()){
for(String anAuthor:aBook.getAuthors()){
if(anAuthor.equals(author)){
books.add(aBook);
break;
}
}
}

return books;
}

The BookLister class needs a BookService implementation; this means that


the BookLister class depends on it. It cannot carry out its work without a
BookService implementation. Therefore, BookLister has a dependency on
the BookService interface and on some implementation of it. The BookLister
class itself instantiates BookServiceImpl as its BookService implementation.
Therefore, the BookLister class is said to satisfy its own dependencies. When a
class satisfies its own dependencies, it automatically also depends on the classes
it satisfies the dependencies with. In this case, BookLister now also depends
on BookServiceImpl, and if any, on the other values passed as a parameter to
the BookServiceImpl constructor. The BookService interface can have many
implementations such as Spring JDBC-based data access and JPA-based data access
implementation. We cannot use a different implementation of the BookService
interface without changing the code.

[ 14 ]
Chapter 1

To refactor this tight coupling, we can move the BookService instantiation to the
constructor of the class. The following is the modified BookLister class:
public class BookLister {

private final BookService bookFinder;

public BookLister(BookService bookFinder) {


this.bookFinder = bookFinder;
}

public List<Book> findByAuthor(String author){


List<Book> books = new ArrayList<>();

for(Book aBook:bookFinder.findAll()){
for(String anAuthor:aBook.getAuthors()){
if(anAuthor.equals(author)){
books.add(aBook);
break;
}
}
}

return books;
}

Note that the BookService dependency is passed to the BookLister constructor


as a constructor argument. Now, BookLister is only depending on BookService.
Whoever instantiates the BookLister constructor will satisfy the dependency. The
BookService dependency is said to be injected into the BookLister constructor,
hence the term dependency injection. It is now possible to change the BookService
implementation used by the BookLister class without changing the BookLister
class.

There are two types of dependency injections:

• Constructor injection
• Setter injection

[ 15 ]
Getting Familiar with the Spring Framework

A Spring configuration file creates/defines and configures (resolves dependencies)


beans. In the Spring configuration file, the constructor injection is constructed
as follows:
<bean id="bookLister" class="com.packt.di.BookLister">
<constructor-arg ref="bookService"/>
</bean>
<bean id="bookService" class="com.packt.di.BookServiceImpl" />

The preceding code is equivalent to the following:


BookService service = new BookServiceImpl();
BookLister bookLister = new BookLister(service);

The setter injection is carried out by setting a property. In a setter injection, instead
of passing bookService as a constructor argument, we change the class to pass as
a setter method argument.

The Spring configuration is as follows:


<bean id="bookListerSetterInjection" class="com.packt.di.BookLister">
<property name="bookService" ref="bookService" />
</bean>

<bean id="bookService" class="com.packt.di.BookServiceImpl" />

The preceding code snippet is equivalent to the following:


BookService service = new BookServiceImpl();
BookLister bookLister = new BookLister();
bookLister.setBookService(service);

The Spring IoC container is known as ApplicationContext. The objects that are
used in our application, defined in ApplicationContext, and managed by the
Spring IoC container are called beans; for example, bookService is a bean.

A bean is an object that is managed by the Spring IoC container; beans are created
with the configuration metadata that you supply to the container, such as in the
form of XML <bean/> definitions or using Java annotations.

A bean definition describes a bean instance. The bean definition contains the
information called configuration metadata, which is needed by the container to know
how to create the bean, the life cycle of the bean, and the dependencies of the bean.

[ 16 ]
Chapter 1

The following properties are used to define a bean:

• class: This is mandatory and provides the fully qualified bean class name
required for the container to create the bean instance.
• name: This attribute (also known as id) uniquely identifies a bean.
• scope: This provides the scope of the objects created from a bean definition,
such as prototype and singleton. We'll learn about them later.
• constructor-arg: This injects a dependency as a bean's constructor argument.
• properties: This injects a dependency as a setter method argument.
• lazy-init: If this is set as true, the IoC container creates the bean
instance when it is first requested, rather than at startup, which means any
configuration error is not discovered until the bean is eventually instantiated
inside the Spring context.
• init-method: This provides the method name of the bean that is being
invoked just after all necessary properties on the bean are set by the IoC
container. This is useful when we need to initialize/compute something
after the bean is instantiated.
• destroy-method: The container calls this method when the bean is
destroyed; this is necessary when we need to clean up something
before the bean is destroyed.

The following are the bean scopes:

• singleton: A single instance of the bean per IoC container. This is not
actually the same as in the singleton design pattern (that is, one instance
per classloader).
• prototype: A single bean definition to have any number of object instances.
A new bean instance is created each time one is needed.
• request: A bean instance per HTTP request, only valid in the web-aware
application context.
• session: A bean instance per HTTP session, only valid in the web-aware
application context.
• global-session: A bean instance per global HTTP session, only valid in the
web-aware application context.

[ 17 ]
Getting Familiar with the Spring Framework

The following are the steps in a bean's life cycle:

1. The first step is to find and instantiate the beans. The Spring IoC container
reads the bean definitions from the XML and then instantiates them.
2. The next step is to populate the bean properties and satisfy the dependencies.
The IoC container uses dependency injection to set the properties.
3. After setting the dependencies, the setBeanName method is invoked on the
beans; if they implement the BeanNameAware interface, the setBeanName()
method is invoked by passing the ID of the bean.
4. After this, if a bean implements the BeanFactoryAware interface, the
setBeanFactory() method is called with an instance of itself.
5. The pre-initialization of BeanPostProcessor is done. If a bean
has any BeanPostProcessor interface associated with it, the
processBeforeInitialization() methods are called on the post processors.
6. The init method is called; if a bean specifies an init-method, it will be called.
7. Finally, the post-initialization is done; if there are any BeanPostProcessors
associated with the bean, their postProcessAfterInitialization()
methods are invoked.

Note that a POJO doesn't need to depend on anything Spring-specific. For


particular cases, Spring provides hooks in the form of these interfaces. Using
them means introducing a dependency on Spring. The following figure depicts
the bean's life cycle:

populate BeanNameAware’s BeanFactoryAware’s


Instantiate
properties setBeanName() setBeanFactory()

ApplicationContextAware’s Pre-initialization InitializingBean’s


setApplicationContext( ) BeanPostProcessors afterPropertiesSet()

call custom Pre-initialization


init-method BeanPostProcessors

Bean is Ready container DisposableBean’s Call custom


to use shuts down destroy() destroy-method

To learn more about DI and IoC, visit the Martin Fowler site at
http://martinfowler.com/articles/injection.html.

[ 18 ]
Other documents randomly have
different content
CHAPTER XI.
EXPLORATIONS IN THE WEST INDIES.

[Æt. 57; 1493]

THE voyage was smooth and prosperous. The expedition


reached the Canaries on the 1st of October, where Columbus laid in
a supply of chickens, sheep, goats, calves, and pigs. It is interesting
to know that these were the pioneer pigs of America. They were
eight in number, and from them descended most of the pigs that now
inhabit the West India islands. On October 7th the fleet again
weighed anchor, and by order of its Admiral steered in a rather
roundabout direction for the islands which were supposed to lie
south of Hispaniola. Columbus was determined—of course for the
noblest and most public-spirited reasons—that no one but himself
should know the true route to the New World; but his trick of steering
first in one direction and then in another could not have had the
desired effect of puzzling any really intelligent sailor. This time
whales, floating bushes, and other signs of land were not needed to
cheer the crews, and consequently they were not seen—a
circumstance that strengthens in the minds of some persons the
belief that Columbus on his first voyage secretly dropped these signs
of land overboard from the bow of his vessel, and then called his
men to look at them. In the latter part of the voyage a heavy thunder-
storm occurred, and while it was in progress lights were seen at the
tops of the masts and elsewhere aloft. These electrical phenomena,
called by the sailors “St. Elmo’s candles,” were received with much
satisfaction as evident tokens that the saint was busily taking care of
the vessels. As he is an able and careful saint, it is perhaps
impertinent to criticise his methods, but it does seem rather odd that
he cannot take care of a ship without running the risk of setting her
on fire by the reckless use of naked and unprotected lights. This was
the only storm of consequence that was met on the passage, and,
thanks to St. Elmo! it does not seem to have done any harm.
On the 3d of November, which was Sunday, the island of
Dominica was sighted, and the usual hymns were sung and prayers
were said. So many islands soon came in sight that it was difficult to
select one on which to land. In this embarrassment of riches, the
Admiral finally landed on an island which he called Marigalante, after
the name of the flag-ship. It was a fair average sort of island, but
after taking formal possession of it and of all other islands, visible
and invisible, belonging to the same group, Columbus left it and
sailed to the island of Guadalupe, a few miles distant, where he
landed on November 4th.
There was a village near the shore, but the inhabitants fled as
the Spaniards landed, leaving behind them only a few useless
babies. Searching the houses, Columbus discovered the stern-post
of a European vessel, which must have drifted across the Atlantic,
since it was much too large to have been sent through the Post
Office, even if we assume—which is grossly improbable—that any
native had written to Europe and ordered a stern-post. From the
number of human bones which were found in the ash-barrels and
garbage-boxes at this village, it was suspected that the people were
cannibals, as in fact they were, being no other than the fierce and
cruel Caribs.
Pursuing his voyage along the coast, Columbus again landed
and explored more deserted villages, capturing a woman and a boy
who had lingered a little too long behind the absconding villagers. On
returning to his ship, the Admiral was pained to learn that one of his
officers, Captain Diego Marque, and eight men, who had gone
ashore without orders, had not yet returned, and were probably
already undergoing preparation for a Caribbean dinner. Alonzo de
Ojeda, a young nobleman who afterward became famous as one of
the ablest and most cruel of Spanish explorers, was sent on shore in
command of a detachment to search for the missing men, and to
bring back as much of them as might remain uneaten. Ojeda
searched in vain, and returned with the report that Marque and his
comrades could not be found, even in the unsatisfactory shape of
cold victuals. Several women who came on board the fleet,
announcing that they were runaway slaves, told frightful stories of
the atrocities perpetrated by the Caribs, and the missing men were
universally believed to have been killed and eaten. At last, after
several days, Marque and his men appeared on the shore, extremely
ragged and hungry. They had merely lost themselves in the woods,
and had not seen a single cannibal. Of course some indignation was
felt at this trivial end of what had been mistaken for a terrible tragedy,
and Columbus promptly punished the delinquents, ostensibly for
being absent without leave.
On the 14th of November, after sailing hither and thither through
the Caribbean archipelago, the fleet anchored at the island of Santa
Cruz. The natives fled into the interior as usual, but a canoe-load of
Indians made its appearance a little later, and, on being chased by
one of the Spanish boats, shot showers of poisoned arrows at the
pursuers. After a lively battle, in which a Spaniard was fatally
wounded and one of the Indians was killed, the canoe was sunk and
the survivors captured. They were so fierce and ugly in appearance
that they were instantly judged to be cannibals of the deepest dye,
and were loaded with chains and afterward sent to Spain as
curiosities.
So many new islands were now sighted that Columbus, whose
stock of names was growing small, called one of them St. Ursula,
and the others her eleven thousand virgins. It is true that there were
not eleven thousand islands; but as St. Ursula never had eleven
thousand virgins, the name was not so extremely inappropriate. The
exact number of these islands was finally ascertained to be fifty.
Discovering Porto Rico, and devoting two days to exploring its
coast-line, Columbus steered for Hispaniola, which he reached on
the 22d of November. The natives came off to the fleet in boats, and
were remarkably polite; but Columbus did not land until he reached
Samana Bay. Here he sent one of his converted Indians on shore,
dressed in the best Spanish fashion, with instructions to lecture to
the natives on the grandeur of Spain; but whether the lecturer was
tedious and met a deserved death at the hands of his first audience,
or whether he seized the opportunity to return to the comforts of
naked paganism, was never known. In any case, he never returned,
and it is greatly to be feared that in his case the trouble and expense
of conversion were wasted.
On the 25th the expedition anchored in a harbor to which the
Admiral gave the name of Monte Christo, in honor of M. Alexandre
Dumas. On landing, the Spaniards were shocked to find four bodies,
one of which was recognized by its beard as the body of a Spaniard.
The circumstances in which these bodies were found showed that
they had been the victims of violence, and it was at once feared that
the colony of La Navidad had met with a disaster. The natives said
they knew nothing about the bodies, and were so innocent in their
demeanor that no one cared to suspect them of murder. The
Admiral, in an anxious frame of mind, made haste to arrive at La
Navidad, which he reached on the 27th, but at too late an hour to
venture to land. Guns were fired and Coston night-signals burned on
board the fleet, but there was no sign of life from the fort. That night
a suspicion dawned upon the minds of some of the fifteen hundred
adventurers that the New World was not worth finding, and that
colonization was a delusion and a snare.
Before morning a canoe containing a cousin of Guacanagari
came out to the fleet in search of Columbus, bringing for him some
valuable presents. The visitors reported that Caribs had invaded the
island, and that Guacanagari had been wounded in battle with them,
and was at a distant village under the care of a doctor,—whose
certificate to that effect, however, he failed to produce. As to the
colony of La Navidad, he did not seem to know very much about it.
He said it was his impression that the colonists had been sick; he
believed some of them had moved away; and he had a vague idea
that they had fought a little among themselves. Having thus cheered
up the Admiral, the friendly native returned to the shore, and the
Spaniards waited anxiously for daylight.
When the day finally dawned, and the Spaniards prepared to
land, they were surprised to find that not a native was visible. On
landing, they were still more surprised to find that the colonists had
totally disappeared, that the fort was in ruins, and that Guacanagari’s
village was a heap of ashes. From the appearance of the fort, it was
evident that it had been captured and sacked. Further search
resulted in the discovery of the buried bodies of eleven Spaniards,
while in the native houses farther in the interior, from which the
inhabitants hastily fled, were found articles which had formerly been
the property of the missing colonists.
Gradually the natives overcame their fears, and came to meet
Columbus. They told a story which was intrinsically probable, and
doubtless true. The colonists had conducted themselves as sailors
left to themselves in a tropical climate, among gentle savages, might
have been expected to. They refused to work, they adopted
polygamy as their chief occupation, and, not content with quarrelling
among themselves, they insulted and outraged the natives until the
latter began to feel seriously provoked. After a time the two
lieutenants of Don Diego de Arana, the Governor, headed a rebellion
against him, but, being defeated, marched off with nine men and a
large supply of wives to search for gold in the interior. Reaching the
dominions of the cacique Caonabo, a powerful chief of Carib birth,
they were pleasantly welcomed and cheerfully put to death. Being of
the opinion that there were still more Spaniards on the island than
were really needed, Caonabo formed an alliance with another chief
of like views, and, falling upon the fort at night, captured it and
massacred every colonist with the exception of a few who saved
themselves by rushing into the sea and drowning in privacy. The
friendly natives further said that they fought under the leadership of
Guacanagari on the side of the Spaniards, and were badly beaten.
A coasting expedition having discovered the village where
Guacanagari was residing, Columbus went to see him. He found the
cacique lying in bed, surrounded by seven wives and suffering
greatly. Guacanagari repeated the story of the capture of the fort,
and put in evidence his wounded leg, marked “Exhibit A,” as proof of
the truth of his story. Unfortunately, no wound was visible, and
although the cacique insisted that his leg had been utterly ruined by
a heavy stone which had struck it, the Spanish surgeon was of
opinion that nothing was the matter. Father Boyle, who was a most
zealous ecclesiastic, held that this was an excellent opportunity for
showing the islanders the merits of the Christian religion, and
recommended that Guacanagari should be promptly burned at the
stake. But the Admiral, although he admitted that it was difficult to
explain the cacique’s leg in a satisfactory way, argued that he would
be much more useful raw than he would if roasted, and to prove this
assertion exchanged a large quantity of glass beads with the cacique
for merely their weight in gold. This demonstration satisfied the
Spaniards temporarily, with the exception of Father Boyle, who was
pained to find Columbus apparently subordinating Christian duty to a
love of gain.
[Æt. 57; 1494]

Guacanagari went on board the flag-ship with the Admiral, where


he was much pleased with the horses, which he saw for the first
time, and pronounced to be very able and ingenious animals. He
was also observed to take altogether too much interest in ten women
whom Columbus had carried off from the Caribbean islands. The
conversation between Guacanagari and the Spaniards is said to
have been constrained and awkward, as indeed it doubtless was, for
no one could converse easily and pleasantly with a cacique who was
constantly gazing in admiration at ten different women. Columbus,
as a token of good-will, hung an image of the Virgin around
Guacanagari’s neck, who, when he learned that the Christians
worshipped it, said he would rather not wear it, lest he should
become a Christian and covet his neighbor’s wife and break his
neighbor’s skull, like the late Christian colonists. Father Boyle was
more anxious to burn him than ever after hearing this blasphemous
remark; but Columbus very properly said it was inhospitable and
unjustifiable to burn visitors, except in the case of a surprise-party,
and that the cacique should go on shore safely, which he shortly did.
The next day Guacanagari did not return to the ship, but in his
place sent his brother, who paid a great deal of attention to the Carib
women, talking with them—as he said—on scientific matters. That
night the ten Carib women jumped overboard and swam ashore, and
when the Spaniards landed in the morning to search for them, no
trace could be found either of the women or of Guacanagari. It was
too evident that the cacique had fallen in love ten deep, and had
eloped with his ten heart’s idols. The Spaniards, who of course took
no interest in the women, were shocked at the painful example of
immorality set by Guacanagari, and agreed that they were now
convinced that he and his hypocritical savages had either betrayed
the colonists to Caonabo, or had slaughtered them and then
invented Caonabo and laid the blame upon him.
CHAPTER XII.
ATTEMPTS AT COLONIZATION.

[Æt. 58; 1494]

GUACANAGARI, IN his last interview with Columbus, had


advised him not to plant a new colony at La Navidad. He said that,
while he was extremely anxious to have the Spaniards as neighbors,
duty compelled him to admit that the locality was an unhealthy one,
and that foreigners settling there were sure to contract chills and
fever. Columbus shared the opinion that it was an unhealthy place,
but he thought that colonists would be more apt to contract
bloodthirsty native chiefs than peaceful malarious fever. At any rate,
he was clear that it would be unwise to repeat the experiment of
colonization at a place with such unpleasant associations.
Expeditions were sent along the coast to find a new location, but
as no eligible building spots were found, the fleet set sail for Monte
Christo. About thirty miles east of Monte Christo a fine harbor was
found, and, on landing, the Admiral was so pleased with the place
that he resolved to build a city without further delay. The ships were
unloaded, and the animals were set on shore. A nice city, called the
city of Isabella, was then laid out, with a church, a government-
house, a town-pump, a custom-house, a jail, and everything that
could make the colonists feel comfortable and at home.
This done, the Spaniards, including Columbus, fell sick with
great unanimity. Most of them felt that they could have been sick to
more advantage in Spain, and that, on the whole, they wanted their
money back. If exploration consisted in crossing an inexcusably wide
ocean merely to build houses among unsociable savages, and to
contract marsh-fever, they were confident that they had had quite
enough of it. Columbus knew that he must soon send the fleet back
to Spain for fresh supplies of food, medicine, and clothing; but he
disliked to send home the unsatisfactory report that the first set of
colonists were all dead, and the second all sick. He therefore
ordered Ojeda to get together a few comparatively well men, and to
march into the interior and discover something that could be
mentioned to advantage in his official report.
With a small force Ojeda marched across the mountain range
that lay back of Isabella, and descended into a delightful plain, where
every prospect pleased him, and the natives were less than usually
vile. Gold was found to be really plentiful, and when Ojeda returned
Columbus saw his way clear to writing a brilliant report, and the
colonists’ spirits revived.
Twelve of the ships were immediately got ready for sea and
loaded with specimens of plants for the Agricultural Bureau, gold for
the Spanish monarchs, and Caribs for the church. Columbus, in his
report, passed lightly and skilfully over the unpleasant features of the
expedition, and dwelt eloquently upon the beauty of the island, the
healthful situation of the city, and the enormous wealth of the gold-
mines. He also forcibly pointed out the great need which the cannibal
Caribs had of being promptly converted. He proposed that Spain
should send out ships laden with supplies, which he would pay for
with Carib slaves, and that when the slaves reached Spain they
could be converted at little expense, and made to do a great deal of
work. Thus the cause of missions could be carried on at a profit of at
least a hundred per cent and a joint stock company for the
enslavement and conversion of Caribs would be able to declare
large and frequent dividends.
Columbus had always maintained that his chief object in
discovering America was to spread the Gospel, and this proposal to
enslave the Caribs shows that he was sincere. Nevertheless, Queen
Isabella said it would be a shame to make the poor Caribs slaves,
and that she was surprised that Columbus should think of such a
thing. Thus the Admiral’s great missionary scheme proved abortive,
but his arguments were afterward used with great success in
defence of the slave-trade which stocked the Georgian and South
Carolinian plantations.
On the 2d of February, 1494, the twelve ships set sail for Spain,
and Columbus felt that unless the officers should prove indiscreet
and tell unpleasant truths, his report would be accepted as a proof of
the success of his second great expedition.
The colonists’ spirits had been raised by the sight of the gold
brought back by Ojeda, but they fell to a very low ebb when the ships
departed. The prospect of remaining behind to die of fever, while
their more fortunate companions could go home and tell magnificent
stories with no one to contradict them, was very depressing. In vain
did Father Boyle celebrate the very highest kind of mass in the
church, and in vain did Columbus put the jail in the best possible
order. Nothing could make the colonists feel contented and happy.
In these circumstances, they naturally abused the Admiral. They
said he was only an Italian, any way, and had no right to command
Spanish gentlemen. They even went so far as to make personal and
disparaging remarks concerning organ-grinders, and expressed the
opinion that an organ-grinder should stick to his monkey and refrain
from meddling with exploration. There was an alleged scientific
person among them—one Fermin Cedo—who pretended there were
no gold-mines on the island. He said he had analyzed the gold
brought back by Ojeda, and it was grossly adulterated. He admitted
that the Indians did have a little real gold, but maintained that they
had inherited it from their ancestors and could not find any more
even if they were to try. The malcontents, under the leadership of
Bernal Diaz, the comptroller, who appears to have had all the
obstinacy and wrong-headedness that pertain to that office in our
own day, resolved to seize the remaining ships and return to Spain,
leaving Columbus to enjoy the fever by himself. Columbus, however,
discovered the plot and immediately recovered his health sufficiently
to arrest Diaz, to punish the least respectable of his followers, and
thus to suppress the mutiny.
In order to divert his men from thoughts of fever and mutiny, the
Admiral now prepared to lead an expedition into the interior. He
appointed his brother Diego Governor of Isabella during his absence,
and with four hundred men—all, in fact, who were well enough to
march—he set out for the gold-bearing mountains of Cibao.
Following the route taken by Ojeda the party crossed the nearest
range of mountains, and entered the fertile plain previously
mentioned. The natives were at first greatly frightened by the
horsemen; and when they discovered that a horse and his rider were
not made in one piece, but could be taken apart, they were more
than ever filled with admiration at the mechanical ingenuity of the
Spaniards.
Crossing the plain, Columbus penetrated into the mountainous
region of Cibao, over which the Carib chief Caonabo ruled. Nothing,
however, was seen of him, and the natives were as friendly as those
of the plain. They brought gold-dust and small nuggets to Columbus,
and assured him that at the distance of about a day’s march gold
could be found in nuggets of the size of a piece of chalk.
This originally meritorious story had now become so old that
Columbus paid no attention to it, knowing that if he were to march all
the rest of his life, the richest gold-mines would always be a little
farther off. So he selected a convenient mountain, where he built a
fort, calling it St. Thomas, which he garrisoned with fifty-six men
commanded by Pedro Margarite. There appears not to have been
any reason for building and garrisoning this fort, unless it was a
desire on the part of the Admiral to station Margarite and his men
where they could not take part in any future mutiny in Isabella.
Returning with the rest of the force, Columbus reached Isabella
on the 29th of March, stopping by the way to trade with the natives
and to learn their method of living. He found the people whom he
had left at Isabella in a more gloomy state than ever. Their stock of
medicines was nearly exhausted, and their provisions were growing
scarce. He was compelled to put them on half rations, and to build a
mill for grinding corn. The mill was a happy thought; but when it was
built, the colonists unanimously agreed that Spanish gentlemen
could not grind corn without losing their self-respect. Columbus said
he rather thought they could, and he compelled every man to take
his turn at grinding, thereby confirming them in the opinion that no
Italian accustomed to grind out “Annie Laurie” and “Baby Mine” could
possibly understand the feelings of a gentleman.
A messenger soon arrived from Fort St. Thomas, announcing
that Caonabo was about to attack it. Ojeda was therefore put in
command of three hundred and ninety-six men, and ordered to
capture Caonabo and inaugurate the new jail with him. Ojeda
promptly started, and on his way met a Spaniard who had been
robbed. Being a just man, Ojeda thereupon seized the cacique of the
province, his son, and nephew, and sent them to Isabella, where
Columbus, filled with horror at the crime which they had not
committed, sentenced them to death—a sentence which he
afterward revoked in order to show his clemency.
As nearly all the able-bodied colonists were now in the interior,
Columbus thought it would be safe to undertake a small exploring
voyage, and so, leaving Don Diego in charge of the city, he took
three of the ships and sailed for Cuba. Had he been a selfish and
heartless man, he might have imagined that during his absence the
sick at Isabella would die, and the Spaniards in the interior would
either starve to death or be killed by Caonabo—thus ridding him of
much care and vexation. As he was not this kind of man, we can
only wonder at his simplicity in dividing his forces in the face of a
cruel enemy, and then calmly sailing away with the most useful of
the ships. He left reams of written instructions to Margarite, Ojeda
and Don Diego, pointing out to them the wickedness of quarrelling,
and recommending them not to allow Caonabo to exterminate them.
He also left Father Boyle behind him, probably because that zealous
ecclesiastic’s longing to burn somebody made him an unsafe person
to take to sea, where the utmost caution in regard to fire is
necessary.
CHAPTER XIII.
SEARCH FOR CHINA.—SUBJUGATION OF
HISPANIOLA.

[Æt. 58; 1494]

ON the 24th of April Columbus set sail, determined this time to


reach the Empire of China. He anchored for a night at La Navidad,
but saw nothing of Guacanagari. Sailing thence, he reached Cuba
and began to coast along the south side of the island. The natives
ran away as usual, and were afterward coaxed back with beads.
They told him, with some variations, the familiar story of a gold-
bearing island farther south, and Columbus decided to give them
one more chance to prove its truth. He steered south in search of the
mythical Babeque, and when he came within sight of a fine large
island, he began to hope that Babeque was found at last; but it
proved to be only Jamaica.
Instead of running away, the natives came out in canoes to
welcome the Spaniards with bloody lances to hospitable drowning-
places. Without stopping to fight the first batch of seventy canoes,
the fleet sailed on in search of a good harbor. When an apparently
eligible place for anchoring was found, a boat was sent to make
soundings, and was attacked by the natives, who swarmed on the
beach. A force was therefore landed to convince the natives that
their conduct was impolite; and after many of them had been shot
and the rest driven into the woods in terror, with a savage dog in hot
pursuit, they were convinced of their error. The local cacique sent
envoys and negotiated a treaty, after which the Spaniards were
permitted to repair their vessels and take in water in peace.
Columbus explored the coast for some little distance to the
westward, but finding no signs of gold, or of the rum for which it
afterward became famous, returned to Cuba and resumed his
search for China.
Day after day he sailed slowly westward, keeping near the coast
and frequently landing to inquire if China was close at hand.
Sometimes the information he received gave him great
encouragement. For example, one able and imaginative cacique told
him of a tribe of men with tails. As it was notorious that men with tails
inhabited a part of Asia, Columbus naturally thought the cacique’s
story referred to them, and that he would soon reach the region
described by the veracious Sir John Mandeville. Another cacique
told him of a king who habitually wore a white garment and was
called a saint. This king Columbus immediately identified with
Prester John, though he ought to have remembered that no true
Presbyterian would dream of wearing white robes except in the
seclusion of his bedchamber. Encouraged by these stories, the
hopeful explorer sailed on toward China, now narrowly escaping
shipwreck in the maze of small islands known to us as the “Keys,”
and now learning with astonishment what violent thunder-storms the
West Indies can produce when they are needed. At one time the sea
became the color of milk, which greatly alarmed the sailors. They
said that putting milk into the sea was a defiance of the laws of
nature, which provide that water should always be put into milk, and
that they did not like to cruise in latitudes where so unnatural a
practice was followed. Still, Columbus persevered. Cuba seemed
really to have no end, or to be, in other words, a continent.
Finally, at the end of fifty days, when not a particle of China had
been found, and the vessels were so strained as to be entirely
unseaworthy, the sailors informed Columbus that this thing had gone
quite far enough, and that it was time to turn back. The Admiral was
so sure that Pekin must be within a few days’ sail that he was very
anxious to pursue the voyage, but he finally agreed to compromise
the matter. He said he would turn back, provided every officer, sailor,
and boy would make an affidavit that Cuba was a part of the
mainland of Asia. This they consented to do with much alacrity, and
when every affidavit had been duly sworn in the presence of a
notary, Columbus announced that any person who should at any
time express the view that Cuba was an island would be judged
guilty of perjury and punished by a fine of ten thousand maravedies,
or by a hundred lashes and the amputation of the tongue.
Having thus conclusively ascertained that Cuba was Asia, he
steered south-east, and on the 13th of June anchored at the Isle of
Pines. Had he only kept on his voyage westward a day or two longer,
he would have reached the western extremity of Cuba, and would
have learned that it was an island.
The voyage back along the Cuban coast was laborious, the
weather being often boisterous and the winds adverse. The sailors
became so worn out that Columbus was compelled to anchor in a
convenient harbor and live on shore with his men for more than a
week, in order that they might rest. Here he met with a venerable
cacique, who gave him excellent advice as to his future conduct, and
assured him that if he did not treat the natives justly he would be
punished in a future world. Judging from the report of the cacique’s
sermon, he was almost as good a Christian as Father Boyle.
When his men were sufficiently repaired, Columbus sailed to
Jamaica and resumed the exploration of its coast-line. He
circumnavigated the island without meeting with any hostile
demonstrations from the natives, and, although he saw no gold, he
was kind enough to speak well of Jamaica in his official report. He
was rather embarrassed by a particularly gorgeous cacique, arrayed
in a cotton helmet and a necklace of green stones, who with his
entire family boarded the flag-ship and informed the Admiral that he
intended to go to Spain with him. Columbus had some difficulty in
declining the cacique’s company, but he finally convinced him that if
he wished to take passage he must apply at the office of the
company and provide himself with tickets in the usual way. The truth
is, the female part of the cacique’s family was numerous and
beautiful, and the judicious Admiral feared that the presence of the
ladies would seriously interfere with the duties of his officers.
On the 20th of August the fleet reached Hispaniola, but
Columbus did not recognize it, and fancied that he had discovered a
new island. A day or two later a cacique came off to meet him in a
canoe, and, addressing him in broken Spanish, informed him of his
true locality. Columbus therefore landed nine of his men, with orders
to proceed to Isabella and report to Don Diego, and then continued
his voyage along the south coast of the island. The winds, however,
persistently opposed him, and he was compelled to lie at anchor for
many days. This slow progress, added to the toils and cares which
he had lately experienced, told heavily on the Admiral’s health,
already enfeebled by his illness at Isabella. He kept on his feet till the
last moment, but on the 24th of September was struck down by an
attack which rendered him totally insensible, and in that condition he
remained for several days, while the fleet pursued its way and finally
reached Isabella.
One of the first to welcome the Admiral when he landed was his
brother Bartholomew. Years before, when Columbus was seeking
some monarch who would take an interest in exploration, he sent
Bartholomew to England to see if King Henry VII. was that kind of
king. Either the Post Office of the period was badly managed, or
Christopher Columbus was so much occupied with thoughts of
exploration that he forgot the existence of Bartholomew. At any rate,
neither brother appears to have heard a word from the other until
Bartholomew accidentally learned that the Admiral had actually
discovered the New World and was on the point of fitting out a
second expedition. Bartholomew had at last induced King Henry to
agree to give his brother the command of an exploring expedition,
but of course the news from Spain rendered this agreement useless.
Bartholomew hastened to Spain by the most rapid route, and when
he found on arriving that his brother had already sailed, he called on
Ferdinand and Isabella, who immediately gave him three ships and
sent him with supplies to the new colony.
There is no doubt that Bartholomew Columbus was an able man,
to whom full justice has never been done. He was sent to England
on an errand, and he stayed till it was accomplished, although it took
him ten years to do it. Where is the man of the present day who
would execute the wishes of a brother with this strict and patient
fidelity, especially if during the whole time he should never receive a
letter or a telegram from home? That Bartholomew was a bold and
skilful sailor is proved by the fact that he found his way across the
Atlantic to Isabella without any sailing directions, and in spite of the
care that Christopher had taken to conceal the knowledge of the
direct route. Evidently Bartholomew could both obey and command,
and there is no reason to suppose that he was in any way inferior to
his more famous brother.
The Admiral appears to have recalled without much difficulty the
fact that he had once had a brother Bartholomew, and to have
readily recognized him. Probably he explained that, owing to a
pressure of business, Bartholomew had escaped his memory, and
he certainly showed that he was glad to see him by appointing him
Adelentado, or Deputy Governor, of Hispaniola. As he was still
confined to his bed, the arrival of his brother was a very fortunate
thing, affairs in the colony being in a precarious and dangerous
state.
When Ojeda and his army had reached Fort St. Thomas,
Margarite, as ranking officer assumed the supreme command, and,
leaving Ojeda with fifty men to garrison the fort, he set out,
ostensibly to explore the island and intimidate Caonabo and other
hostile chiefs. Instead of carrying out this plan, he descended to the
fertile plain at the foot of the mountains, where he quartered his
troops on the natives and began to enjoy himself. Following his
example, the soldiers conducted themselves after the usual manner
of idle and dissolute soldiers, and in a short time earned the
enthusiastic hatred of the natives. Don Diego sent a remonstrance to
Margarite, which that high-spirited gentleman regarded as an
unwarrantable liberty. He refused to acknowledge Diego’s authority,
and, supported by his officers, set him at defiance. When it was
evident that the patience of the natives would soon be exhausted,
Margarite and some of his friends, including Father Boyle—who had
become worn out by vainly waiting for an opportunity to experiment
with a combustible heretic—seized one of the ships and sailed away
to Spain.
The soldiers, being left without any commander, lost all
organization, and the army melted away. The natives found steady
and pleasant employment in killing them in small quantities at a time,
and about a hundred of them took refuge with our old friend
Guacanagari. Caonabo thought this would be a good opportunity for
capturing Fort St. Thomas, and accordingly he besieged it with a
large force, but after thirty days withdrew, completely baffled by the
bravery of Ojeda and his handful of men. He then undertook to unite
the caciques in a league against the Spaniards, and succeeded in
inducing all of them to join him, with the exception of Guacanagari.
The latter went to Isabella soon after Columbus arrived, and warned
him that an overwhelming force was about to attack the city. Troops
were sent out to attack the nearest of the hostile caciques, who was
soon reduced to submission.
In the mean time, Ojeda with a small escort went to Caonabo’s
village and invited the cacique to visit Columbus and make a treaty
with him, pledging him a safe-conduct. The cacique, weakly
believing Ojeda’s promise, accepted the invitation and started with a
small army of followers. On the march Ojeda showed the cacique a
pair of handcuffs, which he said were a decoration which the
Spanish King conferred only on the most eminent of his subjects.
Such, however, was the high opinion that the King had of Caonabo,
that Ojeda was authorized to confer this splendid distinction upon
him. As a preliminary, it would be necessary for Caonabo to mount
on horseback, the bracelets being conferred only on mounted
knights. Caonabo, feeling himself highly honored, climbed on
Ojeda’s horse, behind that astute officer, and submitted to be
manacled. No sooner was this done than Ojeda, and his escort
galloped away and brought the captive cacique to Isabella, where he
was safely lodged in jail.
That Ojeda’s conduct in this affair was treacherous and
dishonorable there can be no question. Indeed, had he been the
United States Government, and had Caonabo been a Black Hill
Sioux, he could hardly have conducted himself more dishonorably
than he did.
The native league was thus temporarily broken up, and the
arrival of four ships from Spain, bringing, besides colonists and
stores, a doctor and an entire apothecary’s shop, gave Columbus
strength enough to get out of bed before the doctor could begin
operations on him. The King and Queen sent Columbus a letter,
announcing that they took their several pens in hand to say that they
were well and hoped Columbus was enjoying the same blessing,
and that they had the utmost confidence in him. This letter
completed the Admiral’s cure, and he immediately organized an
expedition against the natives, who were about to resume hostilities
under the leadership of a brother of Caonabo.
Before setting out, he sent Diego back to Spain, ostensibly to
look after his interests. Perhaps the true reason was that Diego was
of very little use and was extremely unpopular. He was a well-
meaning man, but his true sphere in life was that of a justice of the
peace in Connecticut; and as Connecticut was not yet ready for him,
Columbus thought he had better go home and wait until a good
opening in East Lyme or Falls Village should present itself. At the
same time, five hundred natives were sent to Spain to be sold as
slaves, Columbus remarking that he hoped in this way to prepare
their precious souls for the humanizing influence of the Gospel.
Having seen Diego safely started, Columbus, with Bartholomew,
two hundred and twenty Spaniards, and twenty other bloodhounds,
started to attack the savages. He met a hundred thousand of them—
so the story goes—and defeated them with great slaughter. It is very
probable that the number of the enemy was exaggerated, and that
there were not more than ninety-nine thousand nine hundred and
ninety-six, with perhaps two small-boys. There is no doubt, however,
that they were shot down by the soldiers, ridden down by the horses,
and mangled by the dogs to an immense extent, and that the battle
was a glorious triumph of civilization over barbarism.
The victory was followed up by Columbus with energy. He
marched through almost the entire length and breadth of the island,
and compelled the caciques to make peace and pay a heavy tribute
to the Spaniards. Every native was taxed either a certain amount of
gold or its equivalent in cotton, according to Columbus’s view of their
relative value; and to secure his conquest, the Admiral built and
garrisoned forts in different parts of the island, the most important of
which was called Fort Concepcion, and was situated in the beautiful
plain lying back of Isabella. Even Guacanagari and his people, who
had remained faithful to Columbus, were taxed as heavily as the
hostile natives, and that amiable cacique was so disgusted by this
reward of his fidelity that he resigned his chieftainship and died of
what in the case of a white monarch would be called a broken heart.
The yoke that the Spaniards had put on the native neck was too
heavy to be borne. The savages resolved to starve their oppressors,
and with this view destroyed their crops and retired to the mountains,
to live on roots until the Spaniards should die of starvation. The plan
was not successful. The Spaniards hunted the natives with dogs and
dragged them back to work as slaves. Within a few months the free
and happy people who had welcomed the Spaniards to the island,
and were ready to worship them as superior beings, were converted
into a horde of cowed and wretched slaves.
In later years, when Columbus had seen his own authority in
Hispaniola set aside, and the island under the control of his rivals
and enemies, he protested that the sight of the sufferings of the
unhappy natives filled him with grief and horror. It was, however, to
his political advantage at just that time to have his heart bleed for the
poor savages, and the unprejudiced reader must regret that it did not
bleed at an earlier period. It was under the immediate rule of
Columbus that the natives of Hispaniola were first reduced to
slavery, and it was Columbus who made his old friend and faithful
ally, Guacanagari, suffer the same fate as the chiefs who had
rebelled against the Spaniards. Then it cannot be forgotten that, in
spite of the direct and repeated commands of Queen Isabella,
Columbus sent cargo after cargo of slaves to Spain. He may have
been very sorry to see the natives oppressed by Spaniards whom he
disliked, but he certainly oppressed them quite as vigorously as did
any of his successors. The contrast between his pious and humane
protestations and his acts as an oppressor and a slave-trader is not
easily explicable if we adopt the usual theory that he was one of the
most sincere and noble of men. We may concede that he was
naturally kind-hearted, and that he would have preferred gold-mining
to slave-hunting; but when his interest urged him to cruelty, he
usually listened to it with respectful attention, and straightway
showed by his conduct that, although he was not a countryman of
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like