SlideShare a Scribd company logo
Spring in Action - Sixth Edition (MEAP V04)
Craig Walls download
https://textbookfull.com/product/spring-in-action-sixth-edition-
meap-v04-craig-walls/
Download more ebook from https://textbookfull.com
We believe these products will be a great fit for you. Click
the link to download now, or visit textbookfull.com
to discover even more!
Spring in Action Craig Walls
https://textbookfull.com/product/spring-in-action-craig-walls/
Apache Pulsar in Action MEAP V04 David Kjerrumgaard
https://textbookfull.com/product/apache-pulsar-in-action-
meap-v04-david-kjerrumgaard/
Machine Learning Engineering in Action MEAP V04 Ben T
Wilson
https://textbookfull.com/product/machine-learning-engineering-in-
action-meap-v04-ben-t-wilson/
Spring Microservices in Action 1st Edition John Carnell
https://textbookfull.com/product/spring-microservices-in-
action-1st-edition-john-carnell/
Spring Security in Action 1st Edition Laurentiu Spilca
https://textbookfull.com/product/spring-security-in-action-1st-
edition-laurentiu-spilca/
Spring Security in Action 1st Edition Laurentiu Spilca
Spilc■ Lauren■iu
https://textbookfull.com/product/spring-security-in-action-1st-
edition-laurentiu-spilca-spilca-laurentiu/
Spring Microservices in Action Second Edition MEAP V06
John Carnell Illary Huaylupo Sánchez
https://textbookfull.com/product/spring-microservices-in-action-
second-edition-meap-v06-john-carnell-illary-huaylupo-sanchez/
Spring Microservices in Action Second Edition MEAP V08
John Carnell Illary Huaylupo Sanchez
https://textbookfull.com/product/spring-microservices-in-action-
second-edition-meap-v08-john-carnell-illary-huaylupo-sanchez/
Spring Integration in Action First Edition Mark Fisher
Jonas Partner Marius Bogoevici Iwein Fuld
https://textbookfull.com/product/spring-integration-in-action-
first-edition-mark-fisher-jonas-partner-marius-bogoevici-iwein-
fuld/
Spring in Action - Sixth Edition (MEAP V04) Craig Walls
©Manning Publications Co. To comment go to liveBook
MEAP Edition
Manning Early Access Program
Spring in Action
Sixth Edition
Version 4
Copyright 2021 Manning Publications
For more information on this and other Manning titles go to
manning.com
©Manning Publications Co. To comment go to liveBook
welcome
Thank you for purchasing the MEAP for Spring in Action, Sixth Edition. We've come a
long way over the course of the last five editions and I’m thrilled to have a chance to bring
the latest and greatest Spring has to offer in this new edition. This book should be a
valuable resource regardless of whether you’re completely new to Spring or are reading
this book to brush up on the newest features.
I’ve attempted to make this edition follow a hands-on, narrative style; leading you
through a journey of building an application, starting with initializing the project and going
all the way through to how to ready the application for deployment.
We’re releasing the first five chapters to start. These chapters aren't all that different from
the previous edition, although there are additional updates coming soon that haven't been
worked into these chapters yet. In chapter 1, you’ll learn how to kick start your Spring
project leveraging the Spring Initializr and Spring Boot, and in chapter 2, we’ll build on that
foundation by using Spring MVC to develop additional browser-based functionality.
Chapter 3 looks at persisting data with JDBC and Spring Data JPA. In chapter 4, we'll look
at securing applications with Spring Security. Finally, chapter 5 gets into configuring Spring
using configuration properties.
Looking further ahead, we'll expand on this first group of chapters additional persistence
options, including Spring Data JDBC and non-relational databases such as MongoDB and
Cassandra. In part 2 of the book will see us integrating our application with other
applications. In part 3, we’ll dig into Spring 6’s support for reactive programming and
revisit some previously developed components to make them more reactive. Finally, in part
4 we’ll talk more about deployment.
We hope to have frequent updates to the book, every few weeks, whether that is new
chapters or updates to existing chapters. As you are reading, I invite you to visit the
liveBook's Discussion Forum to ask questions and leave comments. Your feedback is truly
appreciated and I find it valuable in guiding me as I write it.
—Craig Walls
brief contents
PART 1 : FOUNDATIONAL SPRING
1 Getting started with Spring
2 Developing web applications
3 Working with data
4 Working with non-relational data
5 Securing Spring
6 Working with configuration properties
PART 2 : INTEGRATED SPRING
7 Creating REST services
8 Consuming REST services
9 Securing REST
10 Sending messages asynchronously
11 Integrating Spring
PART 3 : REACTIVE SPRING
12 Introducing Reactor
13 Developing reactive APIs
14 Working with RSocket
15 Persisting data reactively
PART 4 : DEPLOYED SPRING
16 Working with Spring Boot Actuator
17 Administering Spring
18 Monitoring Spring with JMX
19 Deploying Spring
©Manning Publications Co. To comment go to liveBook
1
This chapter covers
Although the Greek philosopher Heraclitus wasn’t well known as a software developer, he
seemed to have a good handle on the subject. He has been quoted as saying, “The only constant
is change.” That statement captures a foundational truth of software development.
The way we develop applications today is different than it was a year ago, 5 years ago, 10 years
ago, and certainly 20 years ago, before an initial form of the Spring Framework was introduced
in Rod Johnson’s book, (Wrox, 2002,
Expert One-on-One J2EE Design and Development
).
http://mng.bz/oVjy
Back then, the most common types of applications developed were browser-based web
applications, backed by relational databases. While that type of development is still relevant, and
Spring is well equipped for those kinds of applications, we’re now also interested in developing
applications composed of microservices destined for the cloud that persist data in a variety of
databases. And a new interest in reactive programming aims to provide greater scalability and
improved performance with non-blocking operations.
As software development evolved, the Spring Framework also changed to address modern
development concerns, including microservices and reactive programming. Spring also set out to
simplify its own development model by introducing Spring Boot.
Whether you’re developing a simple database-backed web application or constructing a modern
Getting started with Spring
Spring and Spring Boot essentials
Initializing a Spring project
An overview of the Spring landscape
1
©Manning Publications Co. To comment go to liveBook
application built around microservices, Spring is the framework that will help you achieve your
goals. This chapter is your first step in a journey through modern application development with
Spring.
I know you’re probably itching to start writing a Spring application, and I assure you that before
this chapter ends, you’ll have developed a simple one. But first, let me set the stage with a few
basic Spring concepts that will help you understand what makes Spring tick.
Any non-trivial application is composed of many components, each responsible for its own piece
of the overall application functionality, coordinating with the other application elements to get
the job done. When the application is run, those components somehow need to be created and
introduced to each other.
At its core, Spring offers a , often referred to as the , that
container Spring application context
creates and manages application components. These components, or , are wired together
beans
inside the Spring application context to make a complete application, much like bricks, mortar,
timber, nails, plumbing, and wiring are bound together to make a house.
The act of wiring beans together is based on a pattern known as (DI).
dependency injection
Rather than have components create and maintain the lifecycle of other beans that they depend
on, a dependency-injected application relies on a separate entity (the container) to create and
maintain all components and inject those into the beans that need them. This is done typically
through constructor arguments or property accessor methods.
For example, suppose that among an application’s many components, there are two that you’ll
address: an inventory service (for fetching inventory levels) and a product service (for providing
basic product information). The product service depends on the inventory service to be able to
provide a complete set of information about products. Figure 1.1 illustrates the relationships
between these beans and the Spring application context.
1.1 What is Spring?
2
©Manning Publications Co. To comment go to liveBook
Figure 1.1 Application components are managed and injected into each other by the Spring
application context
On top of its core container, Spring and a full portfolio of related libraries offer a web
framework, a variety of data persistence options, a security framework, integration with other
systems, runtime monitoring, microservice support, a reactive programming model, and many
other features necessary for modern application development.
Historically, the way you would guide Spring’s application context to wire beans together was
with one or more XML files that described the components and their relationship to other
components.
For example, the following XML declares two beans, an bean and a
InventoryService
bean, and wires the bean into via a
ProductService InventoryService ProductService
constructor argument:
In recent versions of Spring, however, a Java-based configuration is more common. The
following Java-based configuration class is equivalent to the XML configuration:
<bean id="inventoryService"
class="com.example.InventoryService" />
<bean id="productService"
class="com.example.ProductService" />
<constructor-arg ref="inventoryService" />
</bean>
@Configuration
public class ServiceConfiguration {
@Bean
public InventoryService inventoryService() {
3
©Manning Publications Co. To comment go to liveBook
The annotation indicates to Spring that this is a configuration class that will
@Configuration
provide beans to the Spring application context. The configuration’s class methods are annotated
with , indicating that the objects they return should be added as beans in the application
@Bean
context (where, by default, their respective bean IDs will be the same as the names of the
methods that define them).
Java-based configuration offers several benefits over XML-based configuration, including
greater type safety and improved refactorability. Even so, explicit configuration with either Java
or XML is only necessary if Spring is unable to automatically configure the components.
Automatic configuration has its roots in the Spring techniques known as and
autowiring
. With component scanning, Spring can automatically discover components
component scanning
from an application’s classpath and create them as beans in the Spring application context. With
autowiring, Spring automatically injects the components with the other beans that they depend
on.
More recently, with the introduction of Spring Boot, automatic configuration has gone well
beyond component scanning and autowiring. Spring Boot is an extension of the Spring
Framework that offers several productivity enhancements. The most well-known of these
enhancements is , where Spring Boot can make reasonable guesses of what
autoconfiguration
components need to be configured and wired together, based on entries in the classpath,
environment variables, and other factors.
I’d like to show you some example code that demonstrates autoconfiguration. But I can’t. You
see, autoconfiguration is much like the wind. You can see the effects of it, but there’s no code
that I can show you and say “Look! Here’s an example of autoconfiguration!” Stuff happens,
components are enabled, and functionality is provided without writing code. It’s this lack of code
that’s essential to autoconfiguration and what makes it so wonderful.
Spring Boot autoconfiguration has dramatically reduced the amount of explicit configuration
(whether with XML or Java) required to build an application. In fact, by the time you finish the
example in this chapter, you’ll have a working Spring application that has only a single line of
Spring configuration code!
Spring Boot enhances Spring development so much that it’s hard to imagine developing Spring
applications without it. For that reason, this book treats Spring and Spring Boot as if they were
one and the same. We’ll use Spring Boot as much as possible, and explicit configuration only
return new InventoryService();
}
@Bean
public ProductService productService() {
return new ProductService(inventoryService());
}
}
4
©Manning Publications Co. To comment go to liveBook
when necessary. And, because Spring XML configuration is the old-school way of working with
Spring, we’ll focus primarily on Spring’s Java-based configuration.
But enough of this chitchat, yakety-yak, and flimflam. This book’s title includes the phrase in
, so let’s get moving, and you can start writing your first application with Spring.
action
Through the course of this book, you’ll create Taco Cloud, an online application for ordering the
most wonderful food created by man—tacos. Of course, you’ll use Spring, Spring Boot, and a
variety of related libraries and frameworks to achieve this goal.
You’ll find several options for initializing a Spring application. Although I could walk you
through the steps of manually creating a project directory structure and defining a build
specification, that’s wasted time—time better spent writing application code. Therefore, you’re
going to lean on the Spring Initializr to bootstrap your application.
The Spring Initializr is both a browser-based web application and a REST API, which can
produce a skeleton Spring project structure that you can flesh out with whatever functionality
you want. Several ways to use Spring Initializr follow:
From the web application at http://start.spring.io
From the command line using the command
curl
From the command line using the Spring Boot command-line interface
When creating a new project with Spring Tool Suite
When creating a new project with IntelliJ IDEA
When creating a new project with NetBeans
Rather than spend several pages of this chapter talking about each one of these options, I’ve
collected those details in the appendix. In this chapter, and throughout this book, I’ll show you
how to create a new project using my favorite option: Spring Initializr support in the Spring Tool
Suite.
As its name suggests, Spring Tool Suite is a fantastic Spring development environment. But it
also offers a handy Spring Boot Dashboard feature that makes it easy to start, restart, and stop
Spring Boot applications from the IDE.
If you’re not a Spring Tool Suite user, that’s fine; we can still be friends. Hop over to the
appendix and substitute the Initializr option that suits you best for the instructions in the
following sections. But know that throughout this book, I may occasionally reference features
specific to Spring Tool Suite, such as the Spring Boot Dashboard. If you’re not using Spring
Tool Suite, you’ll need to adapt those instructions to fit your IDE.
1.2 Initializing a Spring application
5
©Manning Publications Co. To comment go to liveBook
To get started with a new Spring project in Spring Tool Suite, go to the File menu and select
New, and then Spring Starter Project. Figure 1.2 shows the menu structure to look for.
Figure 1.2 Starting a new project with the Initializr in Spring Tool Suite
Once you select Spring Starter Project, a new project wizard dialog (figure 1.3) appears. The first
page in the wizard asks you for some general project information, such as the project name,
description, and other essential information. If you’re familiar with the contents of a Maven
pom.xml file, you’ll recognize most of the fields as items that end up in a Maven build
specification. For the Taco Cloud application, fill in the dialog as shown in figure 1.3, and then
click Next.
1.2.1 Initializing a Spring project with Spring Tool Suite
6
©Manning Publications Co. To comment go to liveBook
Figure 1.3 Specifying general project information for the Taco Cloud application
The next page in the wizard lets you select dependencies to add to your project (see figure 1.4).
Notice that near the top of the dialog, you can select which version of Spring Boot you want to
base your project on. This defaults to the most current version available. It’s generally a good
idea to leave it as is unless you need to target a different version.
As for the dependencies themselves, you can either expand the various sections and seek out the
desired dependencies manually, or search for them in the search box at the top of the Available
7
©Manning Publications Co. To comment go to liveBook
list. For the Taco Cloud application, you’ll start with the dependencies shown in figure 1.4.
Figure 1.4 Choosing starter dependencies
At this point, you can click Finish to generate the project and add it to your workspace. But if
you’re feeling slightly adventurous, click Next one more time to see the final page of the new
starter project wizard, as shown in figure 1.5.
8
©Manning Publications Co. To comment go to liveBook
Figure 1.5 Optionally specifying an alternate Initializr address
By default, the new project wizard makes a call to the Spring Initializr at to
http://start.spring.io
generate the project. Generally, there’s no need to override this default, which is why you could
have clicked Finish on the second page of the wizard. But if for some reason you’re hosting your
own clone of Initializr (perhaps a local copy on your own machine or a customized clone running
inside your company firewall), then you’ll want to change the Base Url field to point to your
Initializr instance before clicking Finish.
9
©Manning Publications Co. To comment go to liveBook
After you click Finish, the project is downloaded from the Initializr and loaded into your
workspace. Wait a few moments for it to load and build, and then you’ll be ready to start
developing application functionality. But first, let’s take a look at what the Initializr gave you.
After the project loads in the IDE, expand it to see what it contains. Figure 1.6 shows the
expanded Taco Cloud project in Spring Tool Suite.
Figure 1.6 The initial Spring project structure as shown in Spring Tool Suite
You may recognize this as a typical Maven or Gradle project structure, where application source
code is placed under src/main/java, test code is placed under src/test/java, and non-Java resources
are placed under src/main/resources. Within that project structure, you’ll want to take note of
these items:
mvnw and — These are Maven wrapper scripts. You can use these scripts to
mvnw.cmd
build your project even if you don’t have Maven installed on your machine.
pom.xml — This is the Maven build specification. We’ll look deeper into this in a
moment.
TacoCloudApplication.java —This is the Spring Boot main class that bootstraps the
project. We’ll take a closer look at this class in a moment.
application.properties — This file is initially empty, but offers a place where you can
1.2.2 Examining the Spring project structure
10
©Manning Publications Co. To comment go to liveBook
specify configuration properties. We’ll tinker with this file a little in this chapter, but I’ll
postpone a detailed explanation of configuration properties to chapter 5.
static — This folder is where you can place any static content (images, stylesheets,
JavaScript, and so forth) that you want to serve to the browser. It’s initially empty.
templates — This folder is where you’ll place template files that will be used to render
content to the browser. It’s initially empty, but you’ll add a Thymeleaf template soon.
TacoCloudApplicationTests.java — This is a simple test class that ensures that the
Spring application context loads successfully. You’ll add more tests to the mix as you
develop the application.
As the Taco Cloud application grows, you’ll fill in this barebones project structure with Java
code, images, stylesheets, tests, and other collateral that will make your project more complete.
But in the meantime, let’s dig a little deeper into a few of the items that Spring Initializr
provided.
When you filled out the Initializr form, you specified that your project should be built with
Maven. Therefore, the Spring Initializr gave you a pom.xml file already populated with the
choices you made. The following listing shows the entire pom.xml file provided by the Initializr.
EXPLORING THE BUILD SPECIFICATION
11
©Manning Publications Co. To comment go to liveBook
Listing 1.1 The initial Maven build specification
<?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
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.0</version>
<relativePath />
</parent>
<groupId>sia</groupId>
<artifactId>taco-cloud</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>taco-cloud</name>
<description>Taco Cloud Example</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
<repositories>
<repository>
12
©Manning Publications Co. To comment go to liveBook
Spring Boot version
Starter dependencies
Spring Boot plugin
The first thing to take note of is the element and, more specifically, its
<parent> <version>
child. This specifies that your project has as its parent POM.
spring-boot-starter-parent
Among other things, this parent POM provides dependency management for several libraries
commonly used in Spring projects. For those libraries covered by the parent POM, you won’t
have to specify a version, as it’s inherited from the parent. The version, , indicates that
2.4.0
you’re using Spring Boot 2.4.0 and, thus, will inherit dependency management as defined by that
version of Spring Boot. Among other things, Spring Boot’s dependency management for version
2.4.0 specifies that the underlying version of the core Spring Framework will be 5.3.0.
While we’re on the subject of dependencies, note that there are four dependencies declared under
the element. The first three should look somewhat familiar to you. They
<dependencies>
correspond directly to the , , and dependencies
Spring Web Thymeleaf Spring Boot DevTools
that you selected before clicking the Finish button in the Spring Tool Suite new project wizard.
The other dependency is one that provides a lot of helpful testing capabilities. You didn’t have to
check a box for it to be included because the Spring Initializr assumes (hopefully, correctly) that
you’ll be writing tests.
You may also notice that all dependencies except for the DevTools dependency have the word
in their artifact ID. Spring Boot starter dependencies are special in that they typically
starter
don’t have any library code themselves, but instead transitively pull in other libraries. These
starter dependencies offer three primary benefits:
Your build file will be significantly smaller and easier to manage because you won’t need
to declare a dependency on every library you might need.
You’re able to think of your dependencies in terms of what capabilities they provide,
rather than in terms of library names. If you’re developing a web application, you’ll add
the web starter dependency rather than a laundry list of individual libraries that enable
you to write a web application.
You’re freed from the burden of worrying about library versions. You can trust that for a
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
</project>
13
©Manning Publications Co. To comment go to liveBook
given version of Spring Boot, the versions of the libraries brought in transitively will be
compatible. You only need to worry about which version of Spring Boot you’re using.
Finally, the build specification ends with the Spring Boot plugin. This plugin performs a few
important functions:
It provides a Maven goal that enables you to run the application using Maven. You’ll try
out this goal in section 1.3.4.
It ensures that all dependency libraries are included within the executable JAR file and
available on the runtime classpath.
It produces a manifest file in the JAR file that denotes the bootstrap class (
, in your case) as the main class for the executable JAR.
TacoCloudApplication
Speaking of the bootstrap class, let’s open it up and take a closer look.
Because you’ll be running the application from an executable JAR, it’s important to have a main
class that will be executed when that JAR file is run. You’ll also need at least a minimal amount
of Spring configuration to bootstrap the application. That’s what you’ll find in the
class, shown in the following listing.
TacoCloudApplication
Listing 1.2 The Taco Cloud bootstrap class
Spring Boot application
Runs the application
Although there’s little code in , what’s there packs quite a punch. One
TacoCloudApplication
of the most powerful lines of code is also one of the shortest. The @SpringBootApplication
annotation clearly signifies that this is a Spring Boot application. But there’s more to
than meets the eye.
@SpringBootApplication
@SpringBootApplication is a composite annotation that combines three other annotations:
@SpringBootConfiguration — Designates this class as a configuration class. Although
there’s not much configuration in the class yet, you can add Java-based Spring
BOOTSTRAPPING THE APPLICATION
package tacos;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class TacoCloudApplication {
public static void main(String[] args) {
SpringApplication.run(TacoCloudApplication.class, args);
}
}
14
©Manning Publications Co. To comment go to liveBook
Framework configuration to this class if you need to. This annotation is, in fact, a
specialized form of the annotation.
@Configuration
@EnableAutoConfiguration — Enables Spring Boot automatic configuration. We’ll
talk more about autoconfiguration later. For now, know that this annotation tells Spring
Boot to automatically configure any components that it thinks you’ll need.
@ComponentScan — Enables component scanning. This lets you declare other classes
with annotations like , , , and others, to have Spring
@Component @Controller @Service
automatically discover them and register them as components in the Spring application
context.
The other important piece of is the method. This is the method
TacoCloudApplication main()
that will be run when the JAR file is executed. For the most part, this method is boilerplate code;
every Spring Boot application you write will have a method similar or identical to this one (class
name differences notwithstanding).
The method calls a static method on the SpringApplication class, which performs
main() run()
the actual bootstrapping of the application, creating the Spring application context. The two
parameters passed to the method are a configuration class and the command-line
run()
arguments. Although it’s not necessary that the configuration class passed to be the same
run()
as the bootstrap class, this is the most convenient and typical choice.
Chances are you won’t need to change anything in the bootstrap class. For simple applications,
you might find it convenient to configure one or two other components in the bootstrap class, but
for most applications, you’re better off creating a separate configuration class for anything that
isn’t autoconfigured. You’ll define several configuration classes throughout the course of this
book, so stay tuned for details.
Testing is an important part of software development. Recognizing this, the Spring Initializr
gives you a test class to get started. The following listing shows the baseline test class.
Listing 1.3 A baseline application test
A Spring Boot test
TESTING THE APPLICATION
package tacos;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public class TacoCloudApplicationTests {
@Test
public void contextLoads() {
}
}
15
©Manning Publications Co. To comment go to liveBook
The test method
There’s not much to be seen in : the one test method in the class
TacoCloudApplicationTests
is empty. Even so, this test class does perform an essential check to ensure that the Spring
application context can be loaded successfully. If you make any changes that prevent the Spring
application context from being created, this test fails, and you can react by fixing the problem.
The annotation tells JUnit to bootstrap the test with Spring Boot capabilities.
@SpringBootTest
Just like , is a composite annotation, which is
@SpringBootApplication @SpringBootTest
itself annotated with , to add Spring testing
@ExtendWith(SpringExtension.class)
capabilities to JUnit 5. For now, though, it’s enough to think of this as the test class equivalent of
calling in a method. Over the course of this book, you’ll
SpringApplication.run() main()
see several times, and we’ll uncover some of its power.
@SpringBootTest
Finally, there’s the test method itself. Although is tasked with loading the
@SpringBootTest
Spring application context for the test, it won’t have anything to do if there aren’t any test
methods. Even without any assertions or code of any kind, this empty test method will prompt
the two annotations to do their job and load the Spring application context. If there are any
problems in doing so, the test fails.
At this point, we’ve concluded our review of the code provided by the Spring Initializr. You’ve
seen some of the boilerplate foundation that you can use to develop a Spring application, but you
still haven’t written a single line of code. Now it’s time to fire up your IDE, dust off your
keyboard, and add some custom code to the Taco Cloud application.
Because you’re just getting started, we’ll start off with a relatively small change to the Taco
Cloud application, but one that will demonstrate a lot of Spring’s goodness. It seems appropriate
that as you’re just starting, the first feature you’ll add to the Taco Cloud application is a
homepage. As you add the homepage, you’ll create two code artifacts:
A controller class that handles requests for the homepage
A view template that defines what the homepage looks like
And because testing is important, you’ll also write a simple test class to test the homepage. But
first things first …​ let’s write that controller.
1.3 Writing a Spring application
16
©Manning Publications Co. To comment go to liveBook
Spring comes with a powerful web framework known as Spring MVC. At the center of Spring
MVC is the concept of a , a class that handles requests and responds with information
controller
of some sort. In the case of a browser-facing application, a controller responds by optionally
populating model data and passing the request on to a view to produce HTML that’s returned to
the browser.
You’re going to learn a lot about Spring MVC in chapter 2. But for now, you’ll write a simple
controller class that handles requests for the root path (for example, ) and forwards those
/
requests to the homepage view without populating any model data. The following listing shows
the simple controller class.
Listing 1.4 The homepage controller
The controller
Handles requests for the root path /
Returns the view name
As you can see, this class is annotated with . On its own, doesn’t do
@Controller @Controller
much. Its primary purpose is to identify this class as a component for component scanning.
Because is annotated with , Spring’s component scanning
HomeController @Controller
automatically discovers it and creates an instance of as a bean in the Spring
HomeController
application context.
In fact, a handful of other annotations (including , , and )
@Component @Service @Repository
serve a purpose similar to . You could have just as effectively annotated
@Controller
with any of those other annotations, and it would have still worked the same.
HomeController
The choice of is, however, more descriptive of this component’s role in the
@Controller
application.
The method is as simple as controller methods come. It’s annotated with
home() @GetMapping
to indicate that if an HTTP GET request is received for the root path /, then this method should
1.3.1 Handling web requests
package tacos;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
@GetMapping("/")
public String home() {
return "home";
}
}
17
©Manning Publications Co. To comment go to liveBook
handle that request. It does so by doing nothing more than returning a value of .
String home
This value is interpreted as the logical name of a view. How that view is implemented depends
on a few factors, but because Thymeleaf is in your classpath, you can define that template with
Thymeleaf.
NOTE Why Thymeleaf?
You may be wondering why to chose Thymeleaf for a template engine. Why
not JSP? Why not FreeMarker? Why not one of several other options?
Put simply, I had to choose something, and I like Thymeleaf and generally
prefer it over those other options. And even though JSP may seem like an
obvious choice, there are some challenges to overcome when using JSP with
Spring Boot. I didn’t want to go down that rabbit hole in chapter 1. Hang tight.
We’ll look at other template options, including JSP, in chapter 2.
The template name is derived from the logical view name by prefixing it with /templates/ and
postfixing it with .html. The resulting path for the template is /templates/home.html. Therefore,
you’ll need to place the template in your project at /src/main/resources/templates/home.html.
Let’s create that template now.
In the interest of keeping your homepage simple, it should do nothing more than welcome users
to the site. The next listing shows the basic Thymeleaf template that defines the Taco Cloud
homepage.
Listing 1.5 The Taco Cloud homepage template
There’s not much to discuss with regard to this template. The only notable line of code is the one
with the tag to display the Taco Cloud logo. It uses a Thymeleaf attribute and an
<img> th:src
expression to reference the image with a context-relative path. Aside from that, it’s not
@{…}
much more than a Hello World page.
Let’s talk about that image a bit more. I’ll leave it up to you to define a Taco Cloud logo that you
1.3.2 Defining the view
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<head>
<title>Taco Cloud</title>
</head>
<body>
<h1>Welcome to...</h1>
<img th:src="@{/images/TacoCloud.png}"/>
</body>
</html>
18
©Manning Publications Co. To comment go to liveBook
like. But you’ll need to make sure you place it at the right place within the project.
The image is referenced with the context-relative path /images/TacoCloud.png. As you’ll recall
from our review of the project structure, static content such as images is kept in the
/src/main/resources/static folder. That means that the Taco Cloud logo image must also reside
within the project at /src/main/resources/static/images/ TacoCloud.png.
Now that you’ve got a controller to handle requests for the homepage and a view template to
render the homepage, you’re almost ready to fire up the application and see it in action. But first,
let’s see how you can write a test against the controller.
Testing web applications can be tricky when making assertions against the content of an HTML
page. Fortunately, Spring comes with some powerful test support that makes testing a web
application easy.
For the purposes of the homepage, you’ll write a test that’s comparable in complexity to the
homepage itself. Your test will perform an HTTP GET request for the root path / and expect a
successful result where the view name is home and the resulting content contains the phrase
“Welcome to…​”. The following should do the trick.
Listing 1.6 A test for the homepage controller
Web test for HomeController
1.3.3 Testing the controller
package tacos;
import static org.hamcrest.Matchers.containsString;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(HomeController.class)
public class HomeControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void testHomePage() throws Exception {
mockMvc.perform(get("/"))
.andExpect(status().isOk())
.andExpect(view().name("home"))
.andExpect(content().string(
containsString("Welcome to...")));
}
}
19
©Manning Publications Co. To comment go to liveBook
Injects MockMvc
Performs GET /
Expects HTTP 200
Expects home view
Expects Welcome to…
The first thing you might notice about this test is that it differs slightly from the
class with regard to the annotations applied to it. Instead of
TacoCloudApplicationTests
markup, HomeControllerTest is annotated with . This is a
@SpringBootTest @WebMvcTest
special test annotation provided by Spring Boot that arranges for the test to run in the context of
a Spring MVC application. More specifically, in this case, it arranges for HomeController to be
registered in Spring MVC so that you can throw requests against it.
@WebMvcTest also sets up Spring support for testing Spring MVC. Although it could be made to
start a server, mocking the mechanics of Spring MVC is sufficient for your purposes. The test
class is injected with a object for the test to drive the mockup.
MockMvc
The method defines the test you want to perform against the homepage. It
testHomePage()
starts with the object to perform an HTTP GET request for / (the root path). From that
MockMvc
request, it sets the following expectations:
The response should have an HTTP 200 (OK) status.
The view should have a logical name of home.
The rendered view should contain the text “Welcome to….”
If, after the object performs the request, any of those expectations aren’t met, then the
MockMvc
test fails. But your controller and view template are written to satisfy those expectations, so the
test should pass with flying colors—or at least with some shade of green indicating a passing
test.
The controller has been written, the view template created, and you have a passing test. It seems
that you’ve implemented the homepage successfully. But even though the test passes, there’s
something slightly more satisfying with seeing the results in a browser. After all, that’s how
Taco Cloud customers are going to see it. Let’s build the application and run it.
Just as there are several ways to initialize a Spring application, there are several ways to run one.
If you like, you can flip over to the appendix to read about some of the more common ways to
run a Spring Boot application.
Because you chose to use Spring Tool Suite to initialize and work on the project, you have a
1.3.4 Building and running the application
20
©Manning Publications Co. To comment go to liveBook
handy feature called the Spring Boot Dashboard available to help you run your application inside
the IDE. The Spring Boot Dashboard appears as a tab, typically near the bottom left of the IDE
window. Figure 1.7 shows an annotated screenshot of the Spring Boot Dashboard.
Figure 1.7 Highlights of the Spring Boot Dashboard
I don’t want to spend much time going over everything the Spring Boot Dashboard does,
although figure 1.7 covers some of the most useful details. The important thing to know right
now is how to use it to run the Taco Cloud application. Make sure taco-cloud application is
highlighted in the list of projects (it’s the only application shown in figure 1.7), and then click
the start button (the left-most button with both a green triangle and a red square). The application
should start right up.
As the application starts, you’ll see some Spring ASCII art fly by in the console, followed by
some log entries describing the steps as the application starts. Before the logging stops, you’ll
see a log entry saying Tomcat started on port(s): 8080 (http), which means that you’re ready to
point your web browser at the homepage to see the fruits of your labor.
Wait a minute. Tomcat started? When did you deploy the application to Tomcat?
Spring Boot applications tend to bring everything they need with them and don’t need to be
21
©Manning Publications Co. To comment go to liveBook
deployed to some application server. You never deployed your application to Tomcat …​ Tomcat
is a part of your application! (I’ll describe the details of how Tomcat became part of your
application in section 1.3.6.)
Now that the application has started, point your web browser to (or click
http://localhost:8080
the globe button in the Spring Boot Dashboard) and you should see something like figure 1.8.
Your results may be different if you designed your own logo image. But it shouldn’t vary much
from what you see in figure 1.8.
Figure 1.8 The Taco Cloud homepage
It may not be much to look at. But this isn’t exactly a book on graphic design. The humble
appearance of the homepage is more than sufficient for now. And it provides you a solid start on
getting to know Spring.
One thing I’ve glossed over up until now is DevTools. You selected it as a dependency when
initializing your project. It appears as a dependency in the produced pom.xml file. And the
Spring Boot Dashboard even shows that the project has DevTools enabled. But what is
DevTools, and what does it do for you? Let’s take a quick survey of a couple of DevTools’ most
useful features.
As its name suggests, DevTools provides Spring developers with some handy development-time
tools. Among those are
1.3.5 Getting to know Spring Boot DevTools
22
©Manning Publications Co. To comment go to liveBook
Automatic application restart when code changes
Automatic browser refresh when browser-destined resources (such as templates,
JavaScript, stylesheets, and so on) change
Automatic disable of template caches
Built in H2 Console if the H2 database is in use
It’s important to understand that DevTools isn’t an IDE plugin, nor does it require that you use a
specific IDE. It works equally well in Spring Tool Suite, IntelliJ IDEA, and NetBeans.
Furthermore, because it’s only intended for development purposes, it’s smart enough to disable
itself when deploying in a production setting. (We’ll discuss how it does this when you get
around to deploying your application in chapter 19.) For now, let’s focus on the most useful
features of Spring Boot DevTools, starting with automatic application restart.
With DevTools as part of your project, you’ll be able to make changes to Java code and
properties files in the project and see those changes applied after a brief moment. DevTools
monitors for changes, and when it sees something has changed, it automatically restarts the
application.
More precisely, when DevTools is in play, the application is loaded into two separate class
loaders in the Java virtual machine (JVM). One class loader is loaded with your Java code,
property files, and pretty much anything that’s in the src/main/ path of the project. These are
items that are likely to change frequently. The other class loader is loaded with dependency
libraries, which aren’t likely to change as often.
When a change is detected, DevTools reloads only the class loader containing your project code
and restarts the Spring application context, but leaves the other class loader and the JVM intact.
Although subtle, this strategy affords a small reduction in the time it takes to start the
application.
The downside of this strategy is that changes to dependencies won’t be available in automatic
restarts. That’s because the class loader containing dependency libraries isn’t automatically
reloaded. This means that any time you add, change, or remove a dependency in your build
specification, you’ll need to do a hard restart of the application for those changes to take effect.
By default, template options such as Thymeleaf and FreeMarker are configured to cache the
results of template parsing so that templates don’t need to be reparsed with every request they
serve. This is great in production, as it buys a bit of performance benefit.
Cached templates, however, are not so great at development time. Cached templates make it
impossible to make changes to the templates while the application is running and see the results
AUTOMATIC APPLICATION RESTART
AUTOMATIC BROWSER REFRESH AND TEMPLATE CACHE DISABLE
23
©Manning Publications Co. To comment go to liveBook
after refreshing the browser. Even if you’ve made changes, the cached template will still be in
use until you restart the application.
DevTools addresses this issue by automatically disabling all template caching. Make as many
changes as you want to your templates and know that you’re only a browser refresh away from
seeing the results.
But if you’re like me, you don’t even want to be burdened with the effort of clicking the
browser’s refresh button. It’d be much nicer if you could make the changes and witness the
results in the browser immediately. Fortunately, DevTools has something special for those of us
who are too lazy to click a refresh button.
When DevTools is in play, it automatically enables a LiveReload ( ) server
http://livereload.com/
along with your application. By itself, the LiveReload server isn’t very useful. But when coupled
with a corresponding LiveReload browser plugin, it causes your browser to automatically refresh
when changes are made to templates, images, stylesheets, JavaScript, and so on—in fact, almost
anything that ends up being served to your browser.
LiveReload has browser plugins for Google Chrome, Safari, and Firefox browsers. (Sorry,
Internet Explorer and Edge fans.) Visit to find information on
http://livereload.com/extensions/
how to install LiveReload for your browser.
Although your project doesn’t yet use a database, that will change in chapter 3. If you choose to
use the H2 database for development, DevTools will also automatically enable an H2 Console
that you can access from your web browser. You only need to point your web browser to
to gain insight into the data your application is working with.
http://localhost:8080/h2-console
At this point, you’ve written a complete, albeit simple, Spring application. You’ll expand on it
throughout the course of the book. But now is a good time to step back and review what you’ve
accomplished and how Spring played a part.
Think back on how you got to this point. In short, these are the steps you’ve taken to build your
Spring-based Taco Cloud application:
You created an initial project structure using Spring Initializr.
You wrote a controller class to handle the homepage request.
You defined a view template to render the homepage.
You wrote a simple test class to prove out your work.
Seems pretty straightforward, doesn’t it? With the exception of the first step to bootstrap the
BUILT IN H2 CONSOLE
1.3.6 Let’s review
24
©Manning Publications Co. To comment go to liveBook
project, each action you’ve taken has been keenly focused on achieving the goal of producing a
homepage.
In fact, almost every line of code you’ve written is aimed toward that goal. Not counting Java
statements, I count only two lines of code in your controller class and no lines in the
import
view template that are Spring-specific. And although the bulk of the test class utilizes Spring
testing support, it seems a little less invasive in the context of a test.
That’s an important benefit of developing with Spring. You can focus on the code that meets the
requirements of an application rather than on satisfying the demands of a framework. Although
you’ll no doubt need to write some framework-specific code from time to time, it’ll usually be
only a small fraction of your codebase. As I said before, Spring (with Spring Boot) can be
considered the .
frameworkless framework
How does this even work? What is Spring doing behind the scenes to make sure your application
needs are met? To understand what Spring is doing, let’s start by looking at the build
specification.
In the pom.xml file, you declared a dependency on the and starters. These two
Web Thymeleaf
dependencies transitively brought in a handful of other dependencies, including
Spring’s MVC framework
Embedded Tomcat
Thymeleaf and the Thymeleaf layout dialect
It also brought Spring Boot’s autoconfiguration library along for the ride. When the application
starts, Spring Boot autoconfiguration detects those libraries and automatically
Configures the beans in the Spring application context to enable Spring MVC
Configures the embedded Tomcat server in the Spring application context
Configures a Thymeleaf view resolver for rendering Spring MVC views with Thymeleaf
templates
In short, autoconfiguration does all the grunt work, leaving you to focus on writing code that
implements your application functionality. That’s a pretty sweet arrangement, if you ask me!
Your Spring journey has just begun. The Taco Cloud application only touched on a small portion
of what Spring has to offer. Before you take your next step, let’s survey the Spring landscape and
see what landmarks you’ll encounter on your journey.
25
©Manning Publications Co. To comment go to liveBook
Another Random Document on
Scribd Without Any Related Topics
alone is liked—that which sounds an alarm to the unconverted, and
bids them prepare for the coming of the Judge.
But there are for all Christians frequent calls to a service in which
they need the courage of faith and every hope the covenant can
give. At the present time no greater mistake is possible than to sit in
comfort under the shadow of ancient forms and creeds. We cannot
realise the value of the promise given to genuine faith unless we
abandon the crumbling walls and meet our assailants in the open
ground, where we can see them face to face, and know the spirit
with which they fight, the ensigns of their war. There is no brave
thinking now in those old shelters, no room to use the armour of
light. Christianity is one of the free forces of human life. Its true
inspiration is found only when those who stand by it are bent on
securing and extending the liberties of men. The trumpets that lift to
heaven the prayers of the faithful and fill the soldiers of the Cross
with the hope of victory can never be in the hands of those who
claim exclusive spiritual authority, nor will they ever again sound the
old Hebrew note. They inspire those who are generous, who feel
that the more they give the more they are blessed, who would
impart to others their own life that God's love to the world may be
known. They call us not to defend our own privileges, but to keep
the way of salvation open to all, to prevent the Pharisee and the
unbeliever from closing against men the door of heavenly grace.
Once more; in the days of gladness and solemn feasting the
trumpets were to be blown over the burnt offerings and peace
offerings. The joy of the Passover, the hope of the new-moon
festival, especially in the beginning of the seventh month, were to be
sent up to heaven with the sound of these instruments, not as if
Jehovah had forgotten His people and His covenant, but for the
assurance and comfort of the worshippers. He was a Friend before
whom they could rejoice, a King whose forgiveness was abundant,
who showed mercy unto the thousands who loved Him and kept His
commandments. The music, loud, and clear, and bold, was to carry
to all who heard it the conviction that God had been sought in the
way of His holy law, and would cause blessing to descend upon
Israel.
We claim with gentler sounds, those of lowly prayer and pleading,
the help of the Most High. Even in the secret chamber when the
door is shut we can address our Father, knowing that our claim will
be answered for the sake of Christ. Yet there are times when the
loud and clear hallelujahs, borne heavenward by human voices and
pealing organ, seem alone to express our exultation. Then the
instruments and methods of modern art may be said to bind the old
Hebrew times, the ancient faith of the wilderness and of Zion, to our
own. We carry out ideas that lie at the heart of the race; we realise
that human skill, human discovery, find their highest use and delight
when they make beautiful and inspiring the service of God.
3. The Order of March
Numbers x. 11-28
The difficulties connected with the order of march prescribed in this
passage have been often and fully rehearsed. According to the
enumeration given in chap. ii., the van of the host formed by the
division of Judah, men, women, and children, must have reached
some six hundred thousand at least. The second division, headed by
Reuben, would number five hundred thousand. The Levites, with
their wives and children, according to the same computation would
be altogether about seventy thousand. Then came the two
remaining camps, about nine hundred thousand souls. At the first
signal six hundred thousand would have to get into marching order
and move off across the desert. There could be no absolute
separation of the fighting men from their families and flocks, and
even if there were no narrow passes to confine the vast multitude, it
would occupy miles of road. We must not put a day's journey at
more than ten miles. The foremost groups would therefore have
reached the camping ground, let us say, when the last ranks of the
second division were only beginning to move; and the rear would
still be on its way when night had long fallen upon the desert.
Whatever obstacles were removed for the Israelites, the actual
distance to be traversed could not be made less; and the journey is
always represented as a stern and serious discipline. When we take
into account the innumerable hindrances which so vast a company
would certainly have to contend with, it seems impossible that the
order of march as detailed in this passage could have been followed
for two days together.
Suppose we receive the explanation that the numbers have been
accidentally increased in the transcription of records. This would
relieve the narrative, not only here but at many points, of a burden it
can hardly carry. And we remember that according to the Book of
Nehemiah less than fifty thousand Jews, returning from Babylon at
the close of the captivity, reconstructed the nation, so that it soon
showed considerable spirit and energy. If the numbers as they stand
in the Pentateuch were reduced, divided by ten, as some propose,
the desert journey would appear less of a mere marvel. It would
remain one of the most striking and important migrations known to
history; it would lose none of its religious significance. No religious
idea is affected by the numbers who receive it; nor do the great
purposes of God depend on multitudes for their fulfilment. We can
view with composure the criticism which touches the record on its
numerical side, because we know the prophetic work of Moses and
the providential education of Israel to be incontrovertible facts.
It has been suggested that the order of march as described did not
continue to be kept throughout the whole of the wilderness journey;
that in point of fact it may have been followed only so far as Kadesh.
Whether this was so or not it must be taken into account that for the
greater part of the forty years there was absolutely no travelling; the
tribes were settled in the wilderness of Paran. The proofs are
incidental but conclusive. From a central point, where the cloud
rested (Numb. x. 12), the people spread themselves, we may
suppose, in various directions, seeking grass for their cattle, and
living for the most part like the other inhabitants of the district. Even
if there were but three years of travelling in all, before and after the
sojourn in the neighbourhood of Kadesh, there would be ample time
for the movement from one place to another mentioned in the
records.
VIII
HOBAB THE KENITE
Numbers x. 29-36
The Kenites, an Arab tribe belonging to the region of Midian, and
sometimes called Midianites, sometimes Amalekites, were already in
close and friendly relation with Israel. Moses, when he went first to
Midian, had married a daughter of their chief Jethro, and, as we
learn from Exod. xviii., this patriarch, with his daughter Zipporah and
the two sons she had borne to Moses, came to the camp of Israel at
the mount of God. The meeting was an occasion of great rejoicing;
and Jethro, as priest of his tribe, having congratulated the Hebrews
on the deliverance Jehovah had wrought for them, "took a burnt
offering and sacrifices for God," and was joined by Moses, Aaron,
and all the elders of Israel in the sacrificial feast. A union was thus
established between Kenites and Israelites of the most solemn and
binding kind. The peoples were sworn to continual friendship.
While Jethro remained in the camp his counsel was given in regard
to the manner of administering justice. In accordance with it rulers
of thousands, hundreds, fifties, and tens were chosen, "able men,
such as feared God, men of truth, hating covetousness"; and to
them matters of minor importance were referred for judgment, the
hard causes only being brought before Moses. The sagacity of one
long experienced in the details of government came in to
supplement the intellectual power and the inspiration of the Hebrew
leader.
It does not appear that any attempt was made to attach Jethro and
the whole of his tribe to the fortunes of Israel. The small company of
the Kenites could travel far more swiftly than a great host, and, if
they desired, could easily overtake the march. Moses, we are told,
let his father-in-law depart, and he went to his own place. But now
that the long stay of the Israelites at Sinai is over and they are about
to advance to Canaan, the visit of a portion of the Kenite tribe is
made the occasion of an appeal to their leader to cast in his lot with
the people of God. There is some confusion in regard to the
relationship of Hobab with Jethro or Raguel. Whether Hobab was a
son or grandson of the chief cannot be made out. The word
translated father-in-law (Numb. x. 29), means a relation by
marriage. Whatever was the tie between Hobab and Moses, it was at
all events so close, and the Kenite had so much sympathy with
Israel, that it was natural to make the appeal to him: "Come thou
with us, and we will do thee good." Himself assured of the result of
the enterprise, anticipating with enthusiasm the high destiny of the
tribes of Israel, Moses endeavours to persuade these children of the
desert to take the way to Canaan.
There was a fascination in the movement of that people who,
rescued from bondage by their Heavenly Friend, were on their
journey to the land of His promise. This fascination Hobab and his
followers appear to have felt; and Moses counted upon it. The
Kenites, used to the wandering life, accustomed to strike their tents
any day as occasion required, no doubt recoiled from the thought of
settling even in a fertile country, still more from dwelling in any
walled town. But the south of Canaan was practically a wilderness,
and there, keeping to a great extent their ancestral habits, they
might have had the liberty they loved, yet kept in touch with their
friends of Israel. Some aversion from the Hebrews, who still bore
certain marks of slavery, would have to be overcome. Yet, with the
bond already established, there needed only some understanding of
the law of Jehovah, and some hope in His promise to bring the
company of Hobab to decision.
And Moses had right in saying, "Come with us, and we will do thee
good; for Jehovah hath spoken good concerning Israel." The outlook
to a future was something which the Kenites as a people had not,
never could have in their desultory life. Unprogressive, out of the
way of the great movements of humanity, gaining nothing as
generations went by, but simply reproducing the habits and
treasuring the beliefs of their fathers, the Arab tribe might maintain
itself, might occasionally strike for righteousness in some conflict,
but otherwise had no prospect, could have no enthusiasm. They
would live their hard life, they would enjoy freedom, they would die
—such would be their history. Compared with that poor outlook, how
good it would be to share the noble task of establishing on the soil
of Canaan a nation devoted to truth and righteousness, in league
with the living God, destined to extend His kingdom and make His
faith the means of blessing to all. It was the great opportunity of
these nomads. As yet, indeed, there was no courage of religion, no
brightness of enthusiasm among the Israelites. But there was the
ark of the covenant, there were the sacrifices, the law; and Jehovah
Himself, always present with His people, was revealing His will and
His glory by oracle, by discipline and deliverance.
Now these Kenites may be taken as representing a class, in the
present day to a certain extent attracted, even fascinated, by the
Church, who standing irresolute are appealed to in terms like those
addressed by Moses to Hobab. They feel a certain charm, for in the
wide organisation and vast activity of the Christian Church, quite
apart from the creed on which it is based, there are signs of vigour
and purpose which contrast favourably with endeavours directed to
mere material gain. In idea and in much of its effort the Church is
splendidly humane, and it provides interests, enjoyments, both of an
intellectual and artistic kind, in which all can share. Not so much its
universality nor its mission of converting the world, nor its spiritual
worship, but rather the social advantages and the culture it offers
draw towards it those minds and lives. And to them it extends, too
often without avail, the invitation to join its march.
Is it asked why many, partly fascinated, remain proof against its
appeals? why an increasing number prefer, like Hobab, the liberty of
the desert, their own unattached, desultory, hopeless way of life?
The answer must partly be that, as it is, the Church does not fully
commend itself by its temper, its enthusiasm, its sincerity and
Christianity. It attracts but is unable to command, because with all
its culture of art it does not appear beautiful, with all its claims of
spirituality it is not unworldly; because, professing to exist for the
redemption of society, its methods and standards are too often
human rather than Divine. It is not that the outsider shrinks from the
religiousness of the Church as overdone; rather does he detect a
lack of that very quality. He could believe in the Divine calling and
join the enterprise of the Church if he saw it journeying steadily
towards a better country, that is a heavenly. Its earnestness would
then command him; faith would compel faith. But social status and
temporal aims are not subordinated by the members of the Church,
nor even by its leaders. And whatever is done in the way of
providing attractions for the pleasure-loving, and schemes of a social
kind, these, so far from gaining the undecided, rather make them
less disposed to believe. More exciting enjoyments can be found
elsewhere. The Church offering pleasures and social reconstruction
is attempting to catch those outside by what, from their point of
view, must appear to be chaff.
It is a question which every body of Christians has need to ask itself
—Can we honestly say to those without, Come with us, and we will
do you good? In order that there may be certainty on this point,
should not every member of the Church be able to testify that the
faith he has gives joy and peace, that his fellowship with God is
making life pure and strong and free? Should there not be a clear
movement of the whole body, year by year, towards finer spirituality,
broader and more generous love? The gates of membership are in
some cases opened to such only as make very clear and ample
profession. It does not, however, appear that those already within
have always the Christian spirit corresponding to that high
profession. And yet as Moses could invite Hobab and his company
without misgiving because Jehovah was the Friend and Guide of
Israel and had spoken good concerning her, so because Christ is the
Head of the Church, and Captain of her salvation, those outside may
well be urged to join her fellowship. If all depended on the
earnestness of our faith and the steadfastness of our virtue we
should not dare to invite others to join the march. But it is with
Christ we ask them to unite. Imperfect in many ways, the Church is
His, exists to show His death, to proclaim His Gospel and extend His
power. In the whole range of human knowledge and experience
there is but one life that is free, pure, hopeful, energetic in every
noble sense, and at the same time calm. In the whole range of
human existence there is but one region in which the mind and the
soul find satisfaction and enlargement, in which men of all sorts and
conditions find true harmony. That life and that region of existence
are revealed by Christ; into them He only is the Way. The Church,
maintaining this, demonstrating this, is to invite all who stand aloof.
They who join Christ and follow Him will come to a good land, a
heavenly heritage.
The first invitation given to Hobab was set aside. "Nay," he said, "I
will not go; but I will depart to my own land and to my kindred." The
old ties of country and people were strong for him. The true Arab
loves his country passionately. The desert is his home, the
mountains are his friends. His hard life is a life of liberty. He is
strongly attached to his tribe, which has its own traditions, its own
glories. There have been feuds, the memory of which must be
cherished. There are heirlooms that give dignity to those who
possess them. The people of the clan are brothers and sisters. Very
little of the commercial mingles with the life of the desert; so
perhaps family feeling has the more power. These influences Hobab
felt, and this besides deterred him, that if he joined the Israelites he
would be under the command of Moses. Hobab was prospective
head of his tribe, already in partial authority at least. To obey the
word of command instead of giving it was a thing he could not
brook. No doubt the leader of Israel had proved himself brave,
resolute, wise. He was a man of ardent soul and fitted for royal
power. But Hobab preferred the chieftainship of his own small clan to
service under Moses; and, brought to the point of deciding, he
would not agree.
Freedom, habit, the hopes that have become part of life—these in
like manner interpose between many and a call which is known to be
from God. There is restraint within the circle of faith; old ideas,
traditional conceptions of life, and many personal ambitions have to
be relinquished by those who enter it. Accustomed to that Midian
where every man does according to the bent of his own will, where
life is hard but uncontrolled, where all they have learned to care for
and desire may be found, many are unwilling to choose the way of
religion, subjection to the law of Christ, the life of spiritual conflict
and trial, however much may be gained at once and in the eternal
future. Yet the liberty of their Midian is illusory. It is simply freedom
to spend strength in vain, to roam from place to place where all alike
are barren, to climb mountains lightning-riven, swept by
interminable storms. And the true liberty is with Christ, who opens
the prospect of the soul, and redeems the life from evil, vanity, and
fear. The heavenward march appears to involve privation and
conflict, which men do not care to face. But is the worldly life free
from enemies, hardships, disappointments? The choice is, for many,
between a bare life over which death triumphs, and a life moving on
over obstacles, through tribulations, to victory and glory. The
attractions of land and people, set against those of Christian hope,
have no claim. "Every one," says the Lord, "that hath left houses, or
brethren, or sisters, or father, or mother, or children, or lands, for My
sake, shall receive a hundredfold, and shall inherit eternal life."
Passing on, the narrative informs us that Moses used another plea:
"Leave us not, I pray thee; forasmuch as thou knowest how we are
to encamp in the wilderness, and thou shalt be to us instead of
eyes." Hobab did not respond to the promise of advantage to
himself; he might be moved by the hope of being useful. Knowing
that he had to deal with a man who was proud, and in his way
magnanimous, Moses wisely used this appeal. And he used it frankly,
without pretence. Hobab might do real and valuable service to the
tribes on their march to Canaan. Accustomed to the desert, over
which he had often travelled, acquainted with the best methods of
disposing a camp in any given position, with the quick eye and habit
of observation which the Arab life gives, Hobab would be the very
adjutant to whom Moses might commit many details. If he joins the
tribes on this footing it will be without pretence. He professes no
greater faith either in Israel's destiny or in Jehovah's sole Godhead
than he really feels. Wishing Israel well, interested in the great
experiment, yet not bound up in it, he may give his counsel and
service heartily so far as they avail.
We are here introduced to another phase of the relation between the
Church and those who do not altogether accept its creed, or
acknowledge its mission to be supernatural, Divine. Confessing
unwillingness to receive the Christian system as a whole, perhaps
openly expressing doubts of the miraculous, for example, many in
our day have still so much sympathy with the ethics and culture of
Christianity that they would willingly associate themselves with the
Church, and render it all the service in their power. Their tastes have
led them to subjects of study and modes of self-development not in
the proper sense religious. Some are scientific, some have literary
talent, some artistic, some financial. The question may be, whether
the Church should invite these to join her ranks in any capacity,
whether room may be made for them, tasks assigned to them. On
the one hand, would it be dangerous to Christian faith? on the other
hand, would it involve them in self-deception? Let it be assumed that
they are men of honour and integrity, men who aim at a high moral
standard and have some belief in the spiritual dignity man may
attain. On this footing may their help be sought and cordially
accepted by the Church?
We cannot say that the example of Moses should be taken as a rule
for Christians. It was one thing to invite the co-operation with Israel
for a certain specified purpose of an Arab chief who differed
somewhat in respect of faith; it would be quite another thing to
invite one whose faith, if he has any, is only a vague theism, to give
his support to Christianity. Yet the cases are so far parallel that the
one illustrates the other. And one point appears to be this, that the
Church may show itself at least as sympathetic as Israel. Is there but
a single note of unison between a soul and Christianity? Let that be
recognised, struck again and again till it is clearly heard. Our Lord
rewarded the faith of a Syrophœnician woman, of a Roman
centurion. His religion cannot be injured by generosity. Attachment
to Himself personally, disposition to hear His words and accept His
morality, should be hailed as the possible dawn of faith, not frowned
upon as a splendid sin. Every one who helps sound knowledge helps
the Church. The enthusiast for true liberty has a point of contact
with Him whose truth gives freedom. The Church is a spiritual city
with gates that stand wide open day and night towards every region
and condition of human life, towards the north and south, the east
and west. If the wealthy are disposed to help, let them bring their
treasures; if the learned devote themselves reverently and patiently
to her literature, let their toil be acknowledged. Science has a tribute
that should be highly valued, for it is gathered from the works of
God; and art of every kind—of the poet, the musician, the sculptor,
the painter—may assist the cause of Divine religion. The powers
men have are given by Him who claims all as His own. The vision of
Isaiah in which he saw Tarshish and the isles, Sheba and Seba
offering gifts to the temple of God, did not assume that the tribute
was in all cases that of covenant love. And the Church of Christ has
broader human sympathy and better right to the service of the world
than Isaiah knew. For the Church's good, and for the good of those
who may be willing in any way to aid her work and development, all
gifts should be gladly received, and those who stand hesitating
should be invited to serve.
But the analogy of the invitation to Hobab involves another point
which must always be kept in view. It is this, that the Church is not
to slacken her march not divert her march in any degree because
men not fully in sympathy with her join the company and contribute
their service. The Kenite may cast in his lot with the Israelites and
aid them with his experience. But Moses will not cease to lead the
tribes towards Canaan, will not delay their progress a single day for
Hobab's sake. Nor will he less earnestly claim sole Godhead for
Jehovah, and insist that every sacrifice shall be made to Him and
every life kept holy in His way, for His service. Perhaps the Kenite
faith differed little in its elements from that which the Israelites
inherited. It may have been monotheistic; and we know that part of
the worship was by way of sacrifice not unlike that appointed by the
Mosaic law. But it had neither the wide ethical basis nor the spiritual
aim and intensity which Moses had been the means of imparting to
Israel's religion. And from the ideas revealed to him and embodied in
the moral and ceremonial law he could not for the sake of Hobab
resile in the least. There should be no adjustment of creed or ritual
to meet the views of the new ally. Onward to Canaan, onward also
along the lines of religious duty and development, the tribes would
hold their way as before.
In modern alliances with the Church a danger is involved, sufficiently
apparent to all who regard the state of religion. History is full of
instances in which, to one company of helpers and another, too
much has been conceded; and the march of spiritual Christianity is
still greatly impeded by the same thing. Money contributed, by
whomsoever, is held to give the donors a right to take their place in
councils of the Church, or at least to sway decision now in one
direction, now in another. Prestige is offered with the tacit
understanding that it shall be repaid with deference. The artist uses
his skill, but not in subordination to the ideas of spiritual religion. He
assumes the right to give them his own colour, and may even, while
professing to serve Christianity, sensualise its teaching. Scholarship
offers help, but is not content to submit to Christ. Having been
allowed to join itself with the Church, it proceeds, not infrequently,
to play the traitor's part, assailing the faith it was invoked to serve.
Those who care more for pleasure than for religion may within a
certain range find gratification in Christian worship; they are apt to
claim more and still more of the element that meets their taste. And
those who are bent on social reconstruction would often, without
any thought of doing wrong, divert the Church entirely from its
spiritual mission. When all these influences are taken into account, it
will be seen that Christianity has to go its way amid perils. It must
not be unsympathetic. But those to whom its camp is opened,
instead of helping the advance, may neutralise the whole enterprise.
Every Church has great need at present to consider whether that
clear spiritual aim which ought to be the constant guide is not
forgotten, at least occasionally, for the sake of this or that alliance
supposed to be advantageous. It is difficult to find the mean,
difficult to say who serve the Church, who hinder its success. More
difficult still is it to distinguish those who are heartily with
Christianity from those who are only so in appearance, having some
nostrum of their own to promote. Hobab may decide to go with
Israel; but the invitation he accepts, perhaps with an air of
superiority, of one conferring a favour, is really extended to him for
his good, for the saving of his life. Let there be no blowing of the
silver trumpets to announce that a prince of the Kenites henceforth
journeys with Israel; they were not made for that! Let there be no
flaunting of a gay ensign over his tent. We shall find that a day
comes when the men who stand by true religion have—perhaps
through Kenite influence—the whole congregation to face. So it is in
Churches. On the other hand, Pharisaism is a great danger, equally
tending to destroy the value of religion; and Providence ever mingles
the elements that enter into the counsels of Christianity, challenging
the highest wisdom, courage, and charity of the faithful.
The closing verses of chap. x. (33-6), belonging, like the passage
just considered, to the prophetic narrative, affirm that the ark was
borne from Sinai three days' journey before the host to find a
halting-place. The reconciliation between this statement and the
order which places the ark in the centre of the march, may be that
the ideal plan was at the outset not observed, for some sufficient
reason. The absolute sincerity of the compilers of the Book of
Numbers is shown in their placing almost side by side the two
statements without any attempt to harmonise. Both were found in
the ancient documents, and both were set down in good faith. The
scribes into whose hands the old records came did not assume the
rôle of critics.
At the beginning of every march Moses is reported to have used the
chant: "Rise up, O Jehovah, and let Thine enemies be scattered; and
let them that hate Thee flee before Thee." When the ark rested he
said: "Return, O Jehovah, unto the ten thousands of the thousands
of Israel." The former is the opening strain of Psalm lxviii., and its
magnificent strophes move towards the idea of that rest which Israel
finds in the protection of her God. Part of the ode returns upon the
desert journey, adding some features and incidents omitted in the
narrations of the Pentateuch—such as the plentiful rain which
refreshed the weary tribes, the publishing by women of some Divine
oracle. But on the whole the psalm agrees with the history, making
Sinai the scene of the great revelation of God, and indicating the
guidance He gave through the wilderness by means of the cloudy
pillar. The chants of Moses would be echoed by the people, and
would help to maintain the sense of constant relation between the
tribes and their unseen Defender.
Through the wilderness Israel went, not knowing from what quarter
the sudden raid of a desert people might be made. Swiftly, silently,
as if springing out of the very sand, the Arab raiders might bear
down upon the travellers. They were assured of the guardianship of
Him whose eye never slumbered, when they kept His way and held
themselves at His command. Here the resemblance to our case in
the journey of life is clear; and we are reminded of our need of
defence and the only terms on which we may expect it. We may look
for protection against those who are the enemies of God. But we
have no warrant for assuming that on whatever errand we are
bound we have but to invoke the Divine arm in order to be secure.
The dreams of those who think their personal claim on God may
always be urged have no countenance in the prayer, "Rise up, O
Jehovah, and let Thine enemies be scattered." And as Israel settling
to rest after some weary march could enjoy the sense of Jehovah's
presence only if the duties of the day had been patiently done, and
the thought of God's will had made peace in every tribe, and His
promise had given courage and hope—so for us, each day will close
with the Divine benediction when we have "fought a good fight and
kept the faith." Fidelity there must be; or, if it has failed, the deep
repentance that subdues wandering desire and rebellious will,
bringing the whole of life anew into the way of lowly service.
IX
THE STRAIN OF THE DESERT
JOURNEY
Numbers xi
The narrative has accompanied the march of Israel but a short way
from the mount of God to some spot marked for an encampment by
the ark of the covenant, and already complaining has to be told of,
and the swift judgment of those who complained. The Israelites
have made a reservation in their covenant with God, that though
obedience and trust are solemnly promised, yet leave shall be taken
to murmur against His providence. They will have God for their
Protector, they will worship Him; but let Him make their life smooth.
Much has had to be borne which they did not anticipate; and they
grumble and speak evil.
Generally men do not realise that their murmuring is against God.
They have no intention to accuse His providence. It is of other men
they complain, who come in their way; of accidents, so called, for
which no one seems to be responsible; of regulations, well enough
meant, which at some point prove vexatious; the obtuseness and
carelessness of those who undertake but do not perform. And there
does seem to be a great difference between displeasure with human
agents whose follies and failures provoke us, and discontent with our
own lot and its trials. At the same time, this has to be kept in view,
that while we carefully refrain from criticising Providence, there may
be, underlying our complaints, a tacit opinion that the world is not
well made nor well ordered. To a certain extent the persons who
irritate us are responsible for their mistakes; but just among those
who are prone to err our discipline has been appointed. To gird at
them is as much a revolt against the Creator as to complain of the
heat of summer or the winter cold. With our knowledge of what the
world is, of what our fellow-creatures are, should go the perception
that God rules everywhere and stands against us when we resent
what, in His world, we have to do or to suffer. He is against those
who fail in duty also. Yet it is not for us to be angry. Our due will not
be withheld. Even when we suffer most it is still offered, still given.
While we endeavour to remedy the evils we feel, it must be without
a thought that the order appointed by the Great King fails us at any
point.
The punishment of those who complained is spoken of as swift and
terrible. "The fire of the Lord burnt among them, and devoured in
the uttermost part of the camp." This judgment falls under a
principle assumed throughout the whole book, that disaster must
overtake transgressors, and conversely that death by pestilence,
earthquake, or lightning is invariably a result of sin. For the Israelites
this was one of the convictions that maintained a sense of moral
duty and of the danger of offending God. Again and again in the
wilderness, where thunderstorms were common and plagues spread
rapidly, the impression was strongly confirmed that the Most High
observed everything that was done against His will. The journey to
Canaan brought in this way a new experience of God to those who
had been accustomed to the equable conditions of climate and the
comparative health enjoyed in Egypt. The moral education of the
people advanced by the quickening of conscience in regard to all
that befell Israel.
From the disaster at Taberah the narrative passes to another phase
of complaint in which the whole camp was involved. The
dissatisfaction began amongst the "mixed multitude"—that
somewhat lawless crowd of low-caste Egyptians and people of the
Delta and the wilderness who attached themselves to the host.
Among them first, because they had absolutely no interest in Israel's
hope, a disposition to quarrel with their circumstances would
naturally arise. But the spirit of dissatisfaction grew apace, and the
burden of the new complaint was: "We have nought but this manna
to look to." The part of the desert into which the travellers had now
penetrated was even more sterile than Midian. Hitherto the food had
been varied somewhat by occasional fruits and the abundant milk of
kine and goats. But pasturage for the cattle was scanty in the
wilderness of Paran, and there were no trees of any kind. Appetite
found nothing that was refreshing. Their soul was dried away.
It was a common belief in our Lord's time that the manna, falling
from heaven, very food of the angels, had been so satisfying, so
delicious, that no people could have been more favoured than those
who ate of it. When Christ spoke of the meat which endureth unto
eternal life, the thought of His hearers immediately turned to the
manna as the special gift of God to their fathers, and they conceived
an expectation that Jesus would give them that bread of heaven,
and so prove Himself worthy of their faith. But He replied, "Moses
gave you not that bread out of heaven, but My Father giveth you the
true bread out of heaven. I am the Bread of Life."
In the course of time the manna had been, so to speak, glorified. It
appeared to the later generations one of the most wonderful and
impressive things recorded in the whole history of their nation, this
provision made for the wandering host. There was the water from
the rock, and there was the manna. What a benignant Providence
had watched over the tribes! How bountiful God had been to the
people in the old days! They longed for a sign of the same kind. To
enjoy it would restore their faith and put them again in the high
position which had been denied for ages.
But these notions are not borne out by the history as we have it in
the passage under notice. Nothing is said about angels' food—that is
a poetical expression which a psalmist used in his fervour. Here we
read, as to the coming of the manna, that when the dew fell upon
the camp at night the manna fell upon it, or with it. And so far from
the people being satisfied, they complained that instead of the fish
and onions, cucumbers and melons of Egypt, they had nothing but
manna to eat. The taste of it is described as like that of fresh oil. In
Exodus it is said to have resembled wafers mixed with honey. It was
not the privilege of the Israelites in the wilderness but their
necessity to live on this somewhat cloying food. In no sense can it
be called ideal. Nevertheless, complaining about it, they were in
serious fault, betraying the foolish expectation that on the way to
liberty they should have no privations. And their discontent with the
manna soon became alarming to Moses. A sort of hysteria spread
through the camp. Not the women only, but the men at the doors of
their tents bewailed their hard lot. There was a tempest of tears and
cries.
God, through His providence, determining for men, carrying out His
own designs for their good, does not allow them to keep in the
region of the usual and of mere comfort. Something is brought into
their life which stirs the soul. In new hope they begin an enterprise
the course and end of which they cannot foresee. The conventional,
the pleasant, the peace and abundance of Egypt, can be no longer
enjoyed if the soul is to have its own. By Moses Jehovah summoned
the Israelites from the land of plenty to fulfil a high mission; and
when they responded, it was so far a proof that there was in them
spirit enough for an uncommon destiny. But for the accomplishment
of it they had to be nerved and braced by trial. Their ordeal was that
mortifying of the flesh and of sensuous desire which must be
undergone if the hopes through which the mind becomes conscious
of the will of God are to be fulfilled.
In our personal history God, reaching us by His word, enlightening
us with regard to the true ends of our being, calls us to begin a
journey which has no earthly terminus and promises no earthly
reward. We may be quite sure that we have not yet responded to
His call if there is nothing of the wilderness in our life, no hardship,
no adventure, no giving up of what is good in a temporal sense for
what is good in a spiritual sense. The very essence of the design of
God concerning a man is that he leave the lower and seek the
higher, that he deny himself that which according to the popular
view is his life, in order to seek a remote and lofty goal. There will
be duty that calls for faith, that needs hope and courage. In doing it
he will have recurring trials of his spirit, necessities of self-discipline,
stern difficulties of choice and action. Every one of these he must
face.
What is wrong with many lives is that they have no strain in them as
of a desert journey towards a heavenly Canaan, the realisation of
spiritual life. Adventure, when it is undertaken, is often for the sake
of getting fish and melons and cucumbers by-and-by in greater
abundance and of better kinds. Many live hardly just now, not
because they are on the way to spiritual freedom and the high
destiny of life in God, but because they believe themselves to be on
the way to better social position, to wealth or honour. But take the
life that has begun its high enterprise at the urgency of a Divine
vocation, and that life will find hardness, deprivations, perils, of its
own. It is not given to us to be absolutely certain in decision and
endeavour. Out in the wilderness, even when manna is provided,
and the pillar of cloud seems to show the way, the people of God are
in danger of doubting whether they have done wisely, whether they
have not taken too much upon themselves or laid too much upon
the Lord. The Israelites might have said, We have obeyed God: why,
then, should the sun smite us with burning heat, and the dust-
storms sweep down upon our march, and the night fall with so bitter
a chill? Interminable toil, in travelling, in attending to cattle and
domestic duties, in pitching tents and striking them, gathering fuel,
searching far and wide through the camp for food, helping the
children, carrying the sick and aged, toil that did not cease till far
into the night and had to be resumed with early morning—such, no
doubt, were the things that made life in the wilderness irksome. And
although many now have a lighter burden, yet our social life, adding
new difficulties with every improvement, our domestic affairs, the
continual struggle necessary in labour and business, furnish not a
few causes of irritation and of bitterness. God does not remove
annoyances out of the way even of His devoted servants. We
remember how Paul was vexed and burdened while carrying the
world's thought on into a new day. We remember what a weight the
infirmities and treacheries of men laid upon the heart of Christ.
Let us thank God if we feel sometimes across the wilderness a
breeze from the hills of the heavenly Canaan, and now and then
catch glimpses of them far away. But the manna may seem flat and
tasteless, nevertheless; the road may seem long; the sun may
scorch. Tempted to despond, we need afresh to assure ourselves
that God is faithful who has given us His promise. And although we
seem to be led not towards the heavenly frontier, but often aside
through close defiles into some region more barren and dismal than
we have yet crossed, doubt is not for us. He knoweth the way that
we take; when He has tried us, we shall come forth where He
appoints.
From the people we turn to Moses and the strain he had to bear as
leader. Partly it was due to his sense of the wrath of God against
Israel. To a certain extent he was responsible for those he led, for
nothing he had done was apart from his own will. The enterprise
was laid on him as a duty certainly; yet he undertook it freely. Such
as the Israelites were, with that mixed multitude among them, a
dangerous element enough, Moses had personally accepted the
leadership of them. And now the murmuring, the lusting, the childish
weeping, fall upon him. He feels that he must stand between the
people and Jehovah. The behaviour of the multitude vexes him to
the soul; yet he must take their part, and avert, if possible, their
condemnation.
The position is one in which a leader of men often finds himself.
Things are done which affront him personally, yet he cannot turn
against the wayward and unbelieving, for, if he did, the cause would
be lost. The Divine judgment of the transgressors falls on him all the
more because they themselves are unaware of it. The burden such
an one has to sustain points directly to the sin-bearing of Christ.
Wounded to the soul by the wrong-doing of men, He had to
interpose between them and the stroke of the law, the judgment of
God. And may not Moses be said to be a type of Christ? The parallel
may well be drawn; yet the imperfect mediation of Moses fell far
short of the perfect mediation of our Lord. The narrative here
reflects that partial knowledge of the Divine character which made
the mediation of Moses human and erring for all its greatness.
For one thing Moses exaggerated his own responsibility. He asked of
God: "Why hast Thou evil entreated Thy servant? Why dost Thou lay
the burden of all this people upon me? Am I their father? Am I to
carry the whole multitude as a father carries his young child in his
bosom?" These are ignorant words, foolish words. Moses is
responsible, but not to that extent. It is fit that he should be grieved
when the Israelites do wrong, but not proper that he should charge
God with laying on him the duty of keeping and carrying them like
children. He speaks unadvisedly with his lips.
Responsibility of those who endeavour to lead others has its limits;
and the range of duty is bounded in two ways—on the one hand by
the responsibility of men for themselves, on the other hand by God's
responsibility for them, God's care of them. Moses should see that
no law or ordinance makes him chargeable with the childish
lamentations of those who know they should not complain, who
ought to be manly and endure with stout hearts. If persons who can
go on their own feet want to be carried, no one is responsible for
carrying them. It is their own fault when they are left behind. If
those who can think and discover duty for themselves, desire
constantly to have it pointed out to them, crave daily
encouragement in doing their duty, and complain because they are
not sufficiently considered, the leader, like Moses, is not responsible.
Every man must bear his own burden—that is, must bear the burden
of duty, of thought, of effort, so far as his ability goes.
Then, on the other side, the power of God is beneath all, His care
extends over all. Moses ought not for a moment to doubt Jehovah's
mindfulness of His people. Men who hold office in society or the
Church are never to think that their effort is commensurate with
God's. Proud indeed he would be who said: "The care of all these
souls lies on me: if they are to be saved, I must save them; if they
perish, I shall be chargeable with their blood." Speaking ignorantly
and in haste, Moses went almost that length; but his error is not to
be repeated. The charge of the Church and of the world is God's;
and He never fails to do for all and for each what is right. The
teacher of men, the leader of affairs, with full sympathy and
indefatigable love, is to do all he can, yet never trench on the
responsibility of men for their own life, or assume to himself the part
of Providence.
Moses made one mistake and went on to another. He was on the
whole a man of rare patience and meekness; yet on this occasion he
spoke to Jehovah in terms of daring resentment. His cry was to get
rid of the whole enterprise: "If Thou deal thus with me, kill me, I
pray Thee, out of hand, and let me not see my wretchedness." He
seemed to himself to have this work to do and no other, apparently
imagining that if he was not competent for this, he could be of no
use in the world. But even if he had failed as a leader, highest in
office, he might have been fit enough for a secondary place, under
Joshua or some other whom God might inspire: this he failed to see.
And although he was bound up in Israel's well-being, so that if the
expedition did not prosper he had no wish to live, and was so far
sincerely patriotic, yet what good end could his death serve? The
desire to die shows wounded pride. Better live on and turn shepherd
again. No man is to despise his life, whatever it is, however it may
seem to come short of the high ambition he has cherished as a
servant of God and men. Discovering that in one line of endeavour
he cannot do all he would, let him make trial of others, not pray for
death.
The narrative represents God as dealing graciously with his erring
servant. Help was provided for him by the appointment of seventy
elders, who were to share the task of guiding and controlling the
tribes. These seventy were to have a portion of the leader's spirit—
zeal and enthusiasm like his own. Their influence in the camp would
prevent the faithlessness and dejection which threatened to wreck
the Hebrew enterprise. Further, the murmuring of the people was to
be effectually silenced. Flesh was to be given them till they loathed
it. They should learn that the satisfaction of ignorant desire meant
punishment rather than pleasure.
The promise of flesh was speedily fulfilled by an extraordinary flight
of quails, brought up, according to the seventy-eighth Psalm, by a
wind which blew from the south and east—that is, from the Elanitic
Gulf. These quails cannot sustain themselves long on the wing, and
after crossing the desert some thirty or forty miles they would
scarcely be able to fly. The enormous numbers of them which
fluttered around the camp are not beyond ordinary possibility. Fowls
of this kind migrate at certain seasons in such enormous multitudes
that in the small island of Capri, near Naples, one hundred and sixty
thousand have been netted in one season. When exhausted, they
would easily be taken as they flew at a height of about two cubits
above the ground. The whole camp was engaged in capturing quails
from one morning to the evening of the following day; and the
quantity was so great that he who gathered least had ten homers,
probably a heap estimated to be of that measure. To keep them for
further use the birds were prepared and spread on the ground to dry
in the sun.
When the epidemic of weeping broke out through the camp, the
doubt occurred to Moses whether there was any spiritual quality in
the people, any fitness for duty or destiny of a religious kind. They
seemed to be all unbelievers on whom the goodness of God and the
sacred instruction had been wasted. They were earthly and sensual.
How could they ever trust God enough to reach Canaan?—or if they
reached it, how would their occupation of it be justified? They would
but form another heathen nation, all the worse that they had once
known the true God and had abandoned Him. But a different view of
things was presented to Moses when the chosen elders, men of
worth, were gathered at the tent of meeting, and on a sudden
impulse of the Spirit began to prophesy. As these men in loud and
ecstatic language proclaimed their faith, Moses found his confidence
in Jehovah's power and in the destiny of Israel re-established. His
mind was relieved at once of the burden of responsibility and the
dread of an extinction of the heavenly light he had been the means
of kindling among the tribes. If there were seventy men capable of
receiving the Spirit of God, there might be hundreds, even
thousands. A spring of new enthusiasm is opened, and Israel's
future is again possible.
Now there were two men, Eldad and Medad, who were of the
seventy, but had not come to the tent of meeting, where the
prophetic spirit fell upon the rest. They had not heard the summons,
we may suppose. Unaware of what was taking place at the
tabernacle, yet realising the honour conferred upon them, they were
perhaps engaged in ordinary duties, or, having found some need for
their interference, they may have been rebuking murmurers and
endeavouring to restore order among the unruly. And suddenly they
also, under the same influence as the other sixty-eight, began to
prophesy. The spirit of earnestness caught them. With the same
ecstasy they declared their faith and praised the God of Israel.
There was in one sense a limitation of the spirit of prophecy,
whatever it was. Of all the host only the seventy received it. Other
good men and true in Israel that day might have seemed as capable
of the heavenly endowment as those who prophesied. It was,
however, in harmony with a known principle that the men
designated to special office alone received the gift. The sense of a
choice felt to be that of God does unquestionably exalt the mind and
spirit of those chosen. They realise that they stand higher and must
do more for God and men than others, that they are inspired to say
what otherwise they could not dare to say. The limitation of the
Spirit in this sense is not invariable, is not strict. At no time in the
world's history has the call to office been indispensable to prophetic
fervour and courage. Yet the sequence is sufficiently common to be
called a law.
But while in a sense there is restriction of the spiritual influence, in
another sense there is no restraint. The Divine afflatus is not
confined to those who have gathered at the tabernacle. It is not
place or occasion that makes the prophets; it is the Spirit, the power
from on high entering into life; and out in the camp the two have
their portion of the new energy and zeal. Spiritual influence, then, is
not confined to any particular place. Neither was the neighbourhood
of the tabernacle so holy that there alone the elders could receive
their gift; nor is any place of meeting, any church, capable of such
consecration and singular identification with the service of God that
there alone the power of the Divine Spirit can be manifested or
received. Let there be a man chosen of God, ready for the duties of
a holy calling, and on that man the Spirit will come, wherever he is,
in whatever he is engaged. He may be employed in common work,
but in doing it he will be moved to earnest service and testimony. He
may be labouring, under great difficulties, to restore the justice that
has been impaired by social errors and political chicanery—and his
words will be prophetic; he will be a witness for God to those who
are without faith, without holy fear.
While Eldad and Medad prophesied in the camp, a young man who
heard them ran officiously to inform Moses. To this young man as to
others—for no doubt there were many who loved and revered the
Usual—the two elders were presumptuous fools. The camp was, as
we say, secular: was it not? People in the camp looked after ordinary
affairs, tended their cattle, chaffered and bargained, quarrelled
about trifles, murmured against Moses and against God. Was it right
to prophesy there, carrying religious words and ideas into the midst
of common life? If Eldad and Medad could prophesy, let them go to
the tabernacle. And besides, what right had they to speak for
Jehovah, in Jehovah's name? Was not Moses the prophet, the only
prophet? Israel was accustomed to think him so, would keep to that
opinion. It would be confusing if at any one's tent door a prophet
might begin to speak without warning. So the young man thought it
his duty to run and tell Moses what was taking place. And Joshua,
when he heard, was alarmed, and desired Moses to put an end to
the irregular ministry. "My lord Moses, forbid them," he said. He was
jealous not for himself and the other elders, but for Moses' sake. So
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

More Related Content

PDF
PDF Spring in Action - Sixth Edition (MEAP V04) Craig Walls download
PDF
Spring Start Here Learn What You Need And Learn It Well 1st Edition Laurentiu...
PPTX
Spring 1 day program
PDF
Spring In Action 1 Illustrated Edition Craig Walls Ryan Breidenbach
PPT
Spring - a framework written by developers
PPTX
Spring framework
PPTX
spring
PPT
Hybernat and structs, spring classes in mumbai
PDF Spring in Action - Sixth Edition (MEAP V04) Craig Walls download
Spring Start Here Learn What You Need And Learn It Well 1st Edition Laurentiu...
Spring 1 day program
Spring In Action 1 Illustrated Edition Craig Walls Ryan Breidenbach
Spring - a framework written by developers
Spring framework
spring
Hybernat and structs, spring classes in mumbai

Similar to Spring in Action - Sixth Edition (MEAP V04) Craig Walls (20)

PDF
Getting Started With Spring Framework J Sharma Ashish Sarin
PPTX
Spring Framework Rohit
PDF
Overview chap1
PPT
Spring introduction
PPTX
Spring framework
PPTX
Introduction to Spring Framework
PDF
Spring Essentials 1st Edition Kunjumohamed Shameer Sattari Hamidreza
PPT
Spring ppt
PPTX
Spring Web Presentation - Framework and Its Ecosystem
PPTX
Spring
PPTX
Spring Web Presentation 123143242341234234
PPT
Spring Framework
PPTX
Spring tutorials
PDF
Java spring framework
PDF
Spring core module
PDF
Spring Framework
PPTX
Skillwise-Spring framework 1
PPT
PDF
Getting Started with Spring Framework
ODP
Spring Mvc,Java, Spring
Getting Started With Spring Framework J Sharma Ashish Sarin
Spring Framework Rohit
Overview chap1
Spring introduction
Spring framework
Introduction to Spring Framework
Spring Essentials 1st Edition Kunjumohamed Shameer Sattari Hamidreza
Spring ppt
Spring Web Presentation - Framework and Its Ecosystem
Spring
Spring Web Presentation 123143242341234234
Spring Framework
Spring tutorials
Java spring framework
Spring core module
Spring Framework
Skillwise-Spring framework 1
Getting Started with Spring Framework
Spring Mvc,Java, Spring
Ad

Recently uploaded (20)

PDF
RMMM.pdf make it easy to upload and study
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PDF
Complications of Minimal Access Surgery at WLH
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Yogi Goddess Pres Conference Studio Updates
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PPTX
Orientation - ARALprogram of Deped to the Parents.pptx
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
A systematic review of self-coping strategies used by university students to ...
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Classroom Observation Tools for Teachers
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
RMMM.pdf make it easy to upload and study
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Module 4: Burden of Disease Tutorial Slides S2 2025
Complications of Minimal Access Surgery at WLH
Microbial diseases, their pathogenesis and prophylaxis
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Yogi Goddess Pres Conference Studio Updates
human mycosis Human fungal infections are called human mycosis..pptx
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
Orientation - ARALprogram of Deped to the Parents.pptx
Abdominal Access Techniques with Prof. Dr. R K Mishra
A systematic review of self-coping strategies used by university students to ...
Final Presentation General Medicine 03-08-2024.pptx
Microbial disease of the cardiovascular and lymphatic systems
O7-L3 Supply Chain Operations - ICLT Program
Classroom Observation Tools for Teachers
Chinmaya Tiranga quiz Grand Finale.pdf
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Ad

Spring in Action - Sixth Edition (MEAP V04) Craig Walls

  • 1. Spring in Action - Sixth Edition (MEAP V04) Craig Walls download https://textbookfull.com/product/spring-in-action-sixth-edition- meap-v04-craig-walls/ Download more ebook from https://textbookfull.com
  • 2. We believe these products will be a great fit for you. Click the link to download now, or visit textbookfull.com to discover even more! Spring in Action Craig Walls https://textbookfull.com/product/spring-in-action-craig-walls/ Apache Pulsar in Action MEAP V04 David Kjerrumgaard https://textbookfull.com/product/apache-pulsar-in-action- meap-v04-david-kjerrumgaard/ Machine Learning Engineering in Action MEAP V04 Ben T Wilson https://textbookfull.com/product/machine-learning-engineering-in- action-meap-v04-ben-t-wilson/ Spring Microservices in Action 1st Edition John Carnell https://textbookfull.com/product/spring-microservices-in- action-1st-edition-john-carnell/
  • 3. Spring Security in Action 1st Edition Laurentiu Spilca https://textbookfull.com/product/spring-security-in-action-1st- edition-laurentiu-spilca/ Spring Security in Action 1st Edition Laurentiu Spilca Spilc■ Lauren■iu https://textbookfull.com/product/spring-security-in-action-1st- edition-laurentiu-spilca-spilca-laurentiu/ Spring Microservices in Action Second Edition MEAP V06 John Carnell Illary Huaylupo Sánchez https://textbookfull.com/product/spring-microservices-in-action- second-edition-meap-v06-john-carnell-illary-huaylupo-sanchez/ Spring Microservices in Action Second Edition MEAP V08 John Carnell Illary Huaylupo Sanchez https://textbookfull.com/product/spring-microservices-in-action- second-edition-meap-v08-john-carnell-illary-huaylupo-sanchez/ Spring Integration in Action First Edition Mark Fisher Jonas Partner Marius Bogoevici Iwein Fuld https://textbookfull.com/product/spring-integration-in-action- first-edition-mark-fisher-jonas-partner-marius-bogoevici-iwein- fuld/
  • 5. ©Manning Publications Co. To comment go to liveBook MEAP Edition Manning Early Access Program Spring in Action Sixth Edition Version 4 Copyright 2021 Manning Publications For more information on this and other Manning titles go to manning.com
  • 6. ©Manning Publications Co. To comment go to liveBook welcome Thank you for purchasing the MEAP for Spring in Action, Sixth Edition. We've come a long way over the course of the last five editions and I’m thrilled to have a chance to bring the latest and greatest Spring has to offer in this new edition. This book should be a valuable resource regardless of whether you’re completely new to Spring or are reading this book to brush up on the newest features. I’ve attempted to make this edition follow a hands-on, narrative style; leading you through a journey of building an application, starting with initializing the project and going all the way through to how to ready the application for deployment. We’re releasing the first five chapters to start. These chapters aren't all that different from the previous edition, although there are additional updates coming soon that haven't been worked into these chapters yet. In chapter 1, you’ll learn how to kick start your Spring project leveraging the Spring Initializr and Spring Boot, and in chapter 2, we’ll build on that foundation by using Spring MVC to develop additional browser-based functionality. Chapter 3 looks at persisting data with JDBC and Spring Data JPA. In chapter 4, we'll look at securing applications with Spring Security. Finally, chapter 5 gets into configuring Spring using configuration properties. Looking further ahead, we'll expand on this first group of chapters additional persistence options, including Spring Data JDBC and non-relational databases such as MongoDB and Cassandra. In part 2 of the book will see us integrating our application with other applications. In part 3, we’ll dig into Spring 6’s support for reactive programming and revisit some previously developed components to make them more reactive. Finally, in part 4 we’ll talk more about deployment. We hope to have frequent updates to the book, every few weeks, whether that is new chapters or updates to existing chapters. As you are reading, I invite you to visit the liveBook's Discussion Forum to ask questions and leave comments. Your feedback is truly appreciated and I find it valuable in guiding me as I write it. —Craig Walls
  • 7. brief contents PART 1 : FOUNDATIONAL SPRING 1 Getting started with Spring 2 Developing web applications 3 Working with data 4 Working with non-relational data 5 Securing Spring 6 Working with configuration properties PART 2 : INTEGRATED SPRING 7 Creating REST services 8 Consuming REST services 9 Securing REST 10 Sending messages asynchronously 11 Integrating Spring PART 3 : REACTIVE SPRING 12 Introducing Reactor 13 Developing reactive APIs 14 Working with RSocket 15 Persisting data reactively PART 4 : DEPLOYED SPRING 16 Working with Spring Boot Actuator 17 Administering Spring 18 Monitoring Spring with JMX 19 Deploying Spring ©Manning Publications Co. To comment go to liveBook
  • 8. 1 This chapter covers Although the Greek philosopher Heraclitus wasn’t well known as a software developer, he seemed to have a good handle on the subject. He has been quoted as saying, “The only constant is change.” That statement captures a foundational truth of software development. The way we develop applications today is different than it was a year ago, 5 years ago, 10 years ago, and certainly 20 years ago, before an initial form of the Spring Framework was introduced in Rod Johnson’s book, (Wrox, 2002, Expert One-on-One J2EE Design and Development ). http://mng.bz/oVjy Back then, the most common types of applications developed were browser-based web applications, backed by relational databases. While that type of development is still relevant, and Spring is well equipped for those kinds of applications, we’re now also interested in developing applications composed of microservices destined for the cloud that persist data in a variety of databases. And a new interest in reactive programming aims to provide greater scalability and improved performance with non-blocking operations. As software development evolved, the Spring Framework also changed to address modern development concerns, including microservices and reactive programming. Spring also set out to simplify its own development model by introducing Spring Boot. Whether you’re developing a simple database-backed web application or constructing a modern Getting started with Spring Spring and Spring Boot essentials Initializing a Spring project An overview of the Spring landscape 1 ©Manning Publications Co. To comment go to liveBook
  • 9. application built around microservices, Spring is the framework that will help you achieve your goals. This chapter is your first step in a journey through modern application development with Spring. I know you’re probably itching to start writing a Spring application, and I assure you that before this chapter ends, you’ll have developed a simple one. But first, let me set the stage with a few basic Spring concepts that will help you understand what makes Spring tick. Any non-trivial application is composed of many components, each responsible for its own piece of the overall application functionality, coordinating with the other application elements to get the job done. When the application is run, those components somehow need to be created and introduced to each other. At its core, Spring offers a , often referred to as the , that container Spring application context creates and manages application components. These components, or , are wired together beans inside the Spring application context to make a complete application, much like bricks, mortar, timber, nails, plumbing, and wiring are bound together to make a house. The act of wiring beans together is based on a pattern known as (DI). dependency injection Rather than have components create and maintain the lifecycle of other beans that they depend on, a dependency-injected application relies on a separate entity (the container) to create and maintain all components and inject those into the beans that need them. This is done typically through constructor arguments or property accessor methods. For example, suppose that among an application’s many components, there are two that you’ll address: an inventory service (for fetching inventory levels) and a product service (for providing basic product information). The product service depends on the inventory service to be able to provide a complete set of information about products. Figure 1.1 illustrates the relationships between these beans and the Spring application context. 1.1 What is Spring? 2 ©Manning Publications Co. To comment go to liveBook
  • 10. Figure 1.1 Application components are managed and injected into each other by the Spring application context On top of its core container, Spring and a full portfolio of related libraries offer a web framework, a variety of data persistence options, a security framework, integration with other systems, runtime monitoring, microservice support, a reactive programming model, and many other features necessary for modern application development. Historically, the way you would guide Spring’s application context to wire beans together was with one or more XML files that described the components and their relationship to other components. For example, the following XML declares two beans, an bean and a InventoryService bean, and wires the bean into via a ProductService InventoryService ProductService constructor argument: In recent versions of Spring, however, a Java-based configuration is more common. The following Java-based configuration class is equivalent to the XML configuration: <bean id="inventoryService" class="com.example.InventoryService" /> <bean id="productService" class="com.example.ProductService" /> <constructor-arg ref="inventoryService" /> </bean> @Configuration public class ServiceConfiguration { @Bean public InventoryService inventoryService() { 3 ©Manning Publications Co. To comment go to liveBook
  • 11. The annotation indicates to Spring that this is a configuration class that will @Configuration provide beans to the Spring application context. The configuration’s class methods are annotated with , indicating that the objects they return should be added as beans in the application @Bean context (where, by default, their respective bean IDs will be the same as the names of the methods that define them). Java-based configuration offers several benefits over XML-based configuration, including greater type safety and improved refactorability. Even so, explicit configuration with either Java or XML is only necessary if Spring is unable to automatically configure the components. Automatic configuration has its roots in the Spring techniques known as and autowiring . With component scanning, Spring can automatically discover components component scanning from an application’s classpath and create them as beans in the Spring application context. With autowiring, Spring automatically injects the components with the other beans that they depend on. More recently, with the introduction of Spring Boot, automatic configuration has gone well beyond component scanning and autowiring. Spring Boot is an extension of the Spring Framework that offers several productivity enhancements. The most well-known of these enhancements is , where Spring Boot can make reasonable guesses of what autoconfiguration components need to be configured and wired together, based on entries in the classpath, environment variables, and other factors. I’d like to show you some example code that demonstrates autoconfiguration. But I can’t. You see, autoconfiguration is much like the wind. You can see the effects of it, but there’s no code that I can show you and say “Look! Here’s an example of autoconfiguration!” Stuff happens, components are enabled, and functionality is provided without writing code. It’s this lack of code that’s essential to autoconfiguration and what makes it so wonderful. Spring Boot autoconfiguration has dramatically reduced the amount of explicit configuration (whether with XML or Java) required to build an application. In fact, by the time you finish the example in this chapter, you’ll have a working Spring application that has only a single line of Spring configuration code! Spring Boot enhances Spring development so much that it’s hard to imagine developing Spring applications without it. For that reason, this book treats Spring and Spring Boot as if they were one and the same. We’ll use Spring Boot as much as possible, and explicit configuration only return new InventoryService(); } @Bean public ProductService productService() { return new ProductService(inventoryService()); } } 4 ©Manning Publications Co. To comment go to liveBook
  • 12. when necessary. And, because Spring XML configuration is the old-school way of working with Spring, we’ll focus primarily on Spring’s Java-based configuration. But enough of this chitchat, yakety-yak, and flimflam. This book’s title includes the phrase in , so let’s get moving, and you can start writing your first application with Spring. action Through the course of this book, you’ll create Taco Cloud, an online application for ordering the most wonderful food created by man—tacos. Of course, you’ll use Spring, Spring Boot, and a variety of related libraries and frameworks to achieve this goal. You’ll find several options for initializing a Spring application. Although I could walk you through the steps of manually creating a project directory structure and defining a build specification, that’s wasted time—time better spent writing application code. Therefore, you’re going to lean on the Spring Initializr to bootstrap your application. The Spring Initializr is both a browser-based web application and a REST API, which can produce a skeleton Spring project structure that you can flesh out with whatever functionality you want. Several ways to use Spring Initializr follow: From the web application at http://start.spring.io From the command line using the command curl From the command line using the Spring Boot command-line interface When creating a new project with Spring Tool Suite When creating a new project with IntelliJ IDEA When creating a new project with NetBeans Rather than spend several pages of this chapter talking about each one of these options, I’ve collected those details in the appendix. In this chapter, and throughout this book, I’ll show you how to create a new project using my favorite option: Spring Initializr support in the Spring Tool Suite. As its name suggests, Spring Tool Suite is a fantastic Spring development environment. But it also offers a handy Spring Boot Dashboard feature that makes it easy to start, restart, and stop Spring Boot applications from the IDE. If you’re not a Spring Tool Suite user, that’s fine; we can still be friends. Hop over to the appendix and substitute the Initializr option that suits you best for the instructions in the following sections. But know that throughout this book, I may occasionally reference features specific to Spring Tool Suite, such as the Spring Boot Dashboard. If you’re not using Spring Tool Suite, you’ll need to adapt those instructions to fit your IDE. 1.2 Initializing a Spring application 5 ©Manning Publications Co. To comment go to liveBook
  • 13. To get started with a new Spring project in Spring Tool Suite, go to the File menu and select New, and then Spring Starter Project. Figure 1.2 shows the menu structure to look for. Figure 1.2 Starting a new project with the Initializr in Spring Tool Suite Once you select Spring Starter Project, a new project wizard dialog (figure 1.3) appears. The first page in the wizard asks you for some general project information, such as the project name, description, and other essential information. If you’re familiar with the contents of a Maven pom.xml file, you’ll recognize most of the fields as items that end up in a Maven build specification. For the Taco Cloud application, fill in the dialog as shown in figure 1.3, and then click Next. 1.2.1 Initializing a Spring project with Spring Tool Suite 6 ©Manning Publications Co. To comment go to liveBook
  • 14. Figure 1.3 Specifying general project information for the Taco Cloud application The next page in the wizard lets you select dependencies to add to your project (see figure 1.4). Notice that near the top of the dialog, you can select which version of Spring Boot you want to base your project on. This defaults to the most current version available. It’s generally a good idea to leave it as is unless you need to target a different version. As for the dependencies themselves, you can either expand the various sections and seek out the desired dependencies manually, or search for them in the search box at the top of the Available 7 ©Manning Publications Co. To comment go to liveBook
  • 15. list. For the Taco Cloud application, you’ll start with the dependencies shown in figure 1.4. Figure 1.4 Choosing starter dependencies At this point, you can click Finish to generate the project and add it to your workspace. But if you’re feeling slightly adventurous, click Next one more time to see the final page of the new starter project wizard, as shown in figure 1.5. 8 ©Manning Publications Co. To comment go to liveBook
  • 16. Figure 1.5 Optionally specifying an alternate Initializr address By default, the new project wizard makes a call to the Spring Initializr at to http://start.spring.io generate the project. Generally, there’s no need to override this default, which is why you could have clicked Finish on the second page of the wizard. But if for some reason you’re hosting your own clone of Initializr (perhaps a local copy on your own machine or a customized clone running inside your company firewall), then you’ll want to change the Base Url field to point to your Initializr instance before clicking Finish. 9 ©Manning Publications Co. To comment go to liveBook
  • 17. After you click Finish, the project is downloaded from the Initializr and loaded into your workspace. Wait a few moments for it to load and build, and then you’ll be ready to start developing application functionality. But first, let’s take a look at what the Initializr gave you. After the project loads in the IDE, expand it to see what it contains. Figure 1.6 shows the expanded Taco Cloud project in Spring Tool Suite. Figure 1.6 The initial Spring project structure as shown in Spring Tool Suite You may recognize this as a typical Maven or Gradle project structure, where application source code is placed under src/main/java, test code is placed under src/test/java, and non-Java resources are placed under src/main/resources. Within that project structure, you’ll want to take note of these items: mvnw and — These are Maven wrapper scripts. You can use these scripts to mvnw.cmd build your project even if you don’t have Maven installed on your machine. pom.xml — This is the Maven build specification. We’ll look deeper into this in a moment. TacoCloudApplication.java —This is the Spring Boot main class that bootstraps the project. We’ll take a closer look at this class in a moment. application.properties — This file is initially empty, but offers a place where you can 1.2.2 Examining the Spring project structure 10 ©Manning Publications Co. To comment go to liveBook
  • 18. specify configuration properties. We’ll tinker with this file a little in this chapter, but I’ll postpone a detailed explanation of configuration properties to chapter 5. static — This folder is where you can place any static content (images, stylesheets, JavaScript, and so forth) that you want to serve to the browser. It’s initially empty. templates — This folder is where you’ll place template files that will be used to render content to the browser. It’s initially empty, but you’ll add a Thymeleaf template soon. TacoCloudApplicationTests.java — This is a simple test class that ensures that the Spring application context loads successfully. You’ll add more tests to the mix as you develop the application. As the Taco Cloud application grows, you’ll fill in this barebones project structure with Java code, images, stylesheets, tests, and other collateral that will make your project more complete. But in the meantime, let’s dig a little deeper into a few of the items that Spring Initializr provided. When you filled out the Initializr form, you specified that your project should be built with Maven. Therefore, the Spring Initializr gave you a pom.xml file already populated with the choices you made. The following listing shows the entire pom.xml file provided by the Initializr. EXPLORING THE BUILD SPECIFICATION 11 ©Manning Publications Co. To comment go to liveBook
  • 19. Listing 1.1 The initial Maven build specification <?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 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.4.0</version> <relativePath /> </parent> <groupId>sia</groupId> <artifactId>taco-cloud</artifactId> <version>0.0.1-SNAPSHOT</version> <name>taco-cloud</name> <description>Taco Cloud Example</description> <properties> <java.version>11</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> <repositories> <repository> 12 ©Manning Publications Co. To comment go to liveBook
  • 20. Spring Boot version Starter dependencies Spring Boot plugin The first thing to take note of is the element and, more specifically, its <parent> <version> child. This specifies that your project has as its parent POM. spring-boot-starter-parent Among other things, this parent POM provides dependency management for several libraries commonly used in Spring projects. For those libraries covered by the parent POM, you won’t have to specify a version, as it’s inherited from the parent. The version, , indicates that 2.4.0 you’re using Spring Boot 2.4.0 and, thus, will inherit dependency management as defined by that version of Spring Boot. Among other things, Spring Boot’s dependency management for version 2.4.0 specifies that the underlying version of the core Spring Framework will be 5.3.0. While we’re on the subject of dependencies, note that there are four dependencies declared under the element. The first three should look somewhat familiar to you. They <dependencies> correspond directly to the , , and dependencies Spring Web Thymeleaf Spring Boot DevTools that you selected before clicking the Finish button in the Spring Tool Suite new project wizard. The other dependency is one that provides a lot of helpful testing capabilities. You didn’t have to check a box for it to be included because the Spring Initializr assumes (hopefully, correctly) that you’ll be writing tests. You may also notice that all dependencies except for the DevTools dependency have the word in their artifact ID. Spring Boot starter dependencies are special in that they typically starter don’t have any library code themselves, but instead transitively pull in other libraries. These starter dependencies offer three primary benefits: Your build file will be significantly smaller and easier to manage because you won’t need to declare a dependency on every library you might need. You’re able to think of your dependencies in terms of what capabilities they provide, rather than in terms of library names. If you’re developing a web application, you’ll add the web starter dependency rather than a laundry list of individual libraries that enable you to write a web application. You’re freed from the burden of worrying about library versions. You can trust that for a <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> </repository> </repositories> <pluginRepositories> <pluginRepository> <id>spring-milestones</id> <name>Spring Milestones</name> <url>https://repo.spring.io/milestone</url> </pluginRepository> </pluginRepositories> </project> 13 ©Manning Publications Co. To comment go to liveBook
  • 21. given version of Spring Boot, the versions of the libraries brought in transitively will be compatible. You only need to worry about which version of Spring Boot you’re using. Finally, the build specification ends with the Spring Boot plugin. This plugin performs a few important functions: It provides a Maven goal that enables you to run the application using Maven. You’ll try out this goal in section 1.3.4. It ensures that all dependency libraries are included within the executable JAR file and available on the runtime classpath. It produces a manifest file in the JAR file that denotes the bootstrap class ( , in your case) as the main class for the executable JAR. TacoCloudApplication Speaking of the bootstrap class, let’s open it up and take a closer look. Because you’ll be running the application from an executable JAR, it’s important to have a main class that will be executed when that JAR file is run. You’ll also need at least a minimal amount of Spring configuration to bootstrap the application. That’s what you’ll find in the class, shown in the following listing. TacoCloudApplication Listing 1.2 The Taco Cloud bootstrap class Spring Boot application Runs the application Although there’s little code in , what’s there packs quite a punch. One TacoCloudApplication of the most powerful lines of code is also one of the shortest. The @SpringBootApplication annotation clearly signifies that this is a Spring Boot application. But there’s more to than meets the eye. @SpringBootApplication @SpringBootApplication is a composite annotation that combines three other annotations: @SpringBootConfiguration — Designates this class as a configuration class. Although there’s not much configuration in the class yet, you can add Java-based Spring BOOTSTRAPPING THE APPLICATION package tacos; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class TacoCloudApplication { public static void main(String[] args) { SpringApplication.run(TacoCloudApplication.class, args); } } 14 ©Manning Publications Co. To comment go to liveBook
  • 22. Framework configuration to this class if you need to. This annotation is, in fact, a specialized form of the annotation. @Configuration @EnableAutoConfiguration — Enables Spring Boot automatic configuration. We’ll talk more about autoconfiguration later. For now, know that this annotation tells Spring Boot to automatically configure any components that it thinks you’ll need. @ComponentScan — Enables component scanning. This lets you declare other classes with annotations like , , , and others, to have Spring @Component @Controller @Service automatically discover them and register them as components in the Spring application context. The other important piece of is the method. This is the method TacoCloudApplication main() that will be run when the JAR file is executed. For the most part, this method is boilerplate code; every Spring Boot application you write will have a method similar or identical to this one (class name differences notwithstanding). The method calls a static method on the SpringApplication class, which performs main() run() the actual bootstrapping of the application, creating the Spring application context. The two parameters passed to the method are a configuration class and the command-line run() arguments. Although it’s not necessary that the configuration class passed to be the same run() as the bootstrap class, this is the most convenient and typical choice. Chances are you won’t need to change anything in the bootstrap class. For simple applications, you might find it convenient to configure one or two other components in the bootstrap class, but for most applications, you’re better off creating a separate configuration class for anything that isn’t autoconfigured. You’ll define several configuration classes throughout the course of this book, so stay tuned for details. Testing is an important part of software development. Recognizing this, the Spring Initializr gives you a test class to get started. The following listing shows the baseline test class. Listing 1.3 A baseline application test A Spring Boot test TESTING THE APPLICATION package tacos; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest public class TacoCloudApplicationTests { @Test public void contextLoads() { } } 15 ©Manning Publications Co. To comment go to liveBook
  • 23. The test method There’s not much to be seen in : the one test method in the class TacoCloudApplicationTests is empty. Even so, this test class does perform an essential check to ensure that the Spring application context can be loaded successfully. If you make any changes that prevent the Spring application context from being created, this test fails, and you can react by fixing the problem. The annotation tells JUnit to bootstrap the test with Spring Boot capabilities. @SpringBootTest Just like , is a composite annotation, which is @SpringBootApplication @SpringBootTest itself annotated with , to add Spring testing @ExtendWith(SpringExtension.class) capabilities to JUnit 5. For now, though, it’s enough to think of this as the test class equivalent of calling in a method. Over the course of this book, you’ll SpringApplication.run() main() see several times, and we’ll uncover some of its power. @SpringBootTest Finally, there’s the test method itself. Although is tasked with loading the @SpringBootTest Spring application context for the test, it won’t have anything to do if there aren’t any test methods. Even without any assertions or code of any kind, this empty test method will prompt the two annotations to do their job and load the Spring application context. If there are any problems in doing so, the test fails. At this point, we’ve concluded our review of the code provided by the Spring Initializr. You’ve seen some of the boilerplate foundation that you can use to develop a Spring application, but you still haven’t written a single line of code. Now it’s time to fire up your IDE, dust off your keyboard, and add some custom code to the Taco Cloud application. Because you’re just getting started, we’ll start off with a relatively small change to the Taco Cloud application, but one that will demonstrate a lot of Spring’s goodness. It seems appropriate that as you’re just starting, the first feature you’ll add to the Taco Cloud application is a homepage. As you add the homepage, you’ll create two code artifacts: A controller class that handles requests for the homepage A view template that defines what the homepage looks like And because testing is important, you’ll also write a simple test class to test the homepage. But first things first …​ let’s write that controller. 1.3 Writing a Spring application 16 ©Manning Publications Co. To comment go to liveBook
  • 24. Spring comes with a powerful web framework known as Spring MVC. At the center of Spring MVC is the concept of a , a class that handles requests and responds with information controller of some sort. In the case of a browser-facing application, a controller responds by optionally populating model data and passing the request on to a view to produce HTML that’s returned to the browser. You’re going to learn a lot about Spring MVC in chapter 2. But for now, you’ll write a simple controller class that handles requests for the root path (for example, ) and forwards those / requests to the homepage view without populating any model data. The following listing shows the simple controller class. Listing 1.4 The homepage controller The controller Handles requests for the root path / Returns the view name As you can see, this class is annotated with . On its own, doesn’t do @Controller @Controller much. Its primary purpose is to identify this class as a component for component scanning. Because is annotated with , Spring’s component scanning HomeController @Controller automatically discovers it and creates an instance of as a bean in the Spring HomeController application context. In fact, a handful of other annotations (including , , and ) @Component @Service @Repository serve a purpose similar to . You could have just as effectively annotated @Controller with any of those other annotations, and it would have still worked the same. HomeController The choice of is, however, more descriptive of this component’s role in the @Controller application. The method is as simple as controller methods come. It’s annotated with home() @GetMapping to indicate that if an HTTP GET request is received for the root path /, then this method should 1.3.1 Handling web requests package tacos; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; @Controller public class HomeController { @GetMapping("/") public String home() { return "home"; } } 17 ©Manning Publications Co. To comment go to liveBook
  • 25. handle that request. It does so by doing nothing more than returning a value of . String home This value is interpreted as the logical name of a view. How that view is implemented depends on a few factors, but because Thymeleaf is in your classpath, you can define that template with Thymeleaf. NOTE Why Thymeleaf? You may be wondering why to chose Thymeleaf for a template engine. Why not JSP? Why not FreeMarker? Why not one of several other options? Put simply, I had to choose something, and I like Thymeleaf and generally prefer it over those other options. And even though JSP may seem like an obvious choice, there are some challenges to overcome when using JSP with Spring Boot. I didn’t want to go down that rabbit hole in chapter 1. Hang tight. We’ll look at other template options, including JSP, in chapter 2. The template name is derived from the logical view name by prefixing it with /templates/ and postfixing it with .html. The resulting path for the template is /templates/home.html. Therefore, you’ll need to place the template in your project at /src/main/resources/templates/home.html. Let’s create that template now. In the interest of keeping your homepage simple, it should do nothing more than welcome users to the site. The next listing shows the basic Thymeleaf template that defines the Taco Cloud homepage. Listing 1.5 The Taco Cloud homepage template There’s not much to discuss with regard to this template. The only notable line of code is the one with the tag to display the Taco Cloud logo. It uses a Thymeleaf attribute and an <img> th:src expression to reference the image with a context-relative path. Aside from that, it’s not @{…} much more than a Hello World page. Let’s talk about that image a bit more. I’ll leave it up to you to define a Taco Cloud logo that you 1.3.2 Defining the view <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <title>Taco Cloud</title> </head> <body> <h1>Welcome to...</h1> <img th:src="@{/images/TacoCloud.png}"/> </body> </html> 18 ©Manning Publications Co. To comment go to liveBook
  • 26. like. But you’ll need to make sure you place it at the right place within the project. The image is referenced with the context-relative path /images/TacoCloud.png. As you’ll recall from our review of the project structure, static content such as images is kept in the /src/main/resources/static folder. That means that the Taco Cloud logo image must also reside within the project at /src/main/resources/static/images/ TacoCloud.png. Now that you’ve got a controller to handle requests for the homepage and a view template to render the homepage, you’re almost ready to fire up the application and see it in action. But first, let’s see how you can write a test against the controller. Testing web applications can be tricky when making assertions against the content of an HTML page. Fortunately, Spring comes with some powerful test support that makes testing a web application easy. For the purposes of the homepage, you’ll write a test that’s comparable in complexity to the homepage itself. Your test will perform an HTTP GET request for the root path / and expect a successful result where the view name is home and the resulting content contains the phrase “Welcome to…​”. The following should do the trick. Listing 1.6 A test for the homepage controller Web test for HomeController 1.3.3 Testing the controller package tacos; import static org.hamcrest.Matchers.containsString; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.test.web.servlet.MockMvc; @WebMvcTest(HomeController.class) public class HomeControllerTest { @Autowired private MockMvc mockMvc; @Test public void testHomePage() throws Exception { mockMvc.perform(get("/")) .andExpect(status().isOk()) .andExpect(view().name("home")) .andExpect(content().string( containsString("Welcome to..."))); } } 19 ©Manning Publications Co. To comment go to liveBook
  • 27. Injects MockMvc Performs GET / Expects HTTP 200 Expects home view Expects Welcome to… The first thing you might notice about this test is that it differs slightly from the class with regard to the annotations applied to it. Instead of TacoCloudApplicationTests markup, HomeControllerTest is annotated with . This is a @SpringBootTest @WebMvcTest special test annotation provided by Spring Boot that arranges for the test to run in the context of a Spring MVC application. More specifically, in this case, it arranges for HomeController to be registered in Spring MVC so that you can throw requests against it. @WebMvcTest also sets up Spring support for testing Spring MVC. Although it could be made to start a server, mocking the mechanics of Spring MVC is sufficient for your purposes. The test class is injected with a object for the test to drive the mockup. MockMvc The method defines the test you want to perform against the homepage. It testHomePage() starts with the object to perform an HTTP GET request for / (the root path). From that MockMvc request, it sets the following expectations: The response should have an HTTP 200 (OK) status. The view should have a logical name of home. The rendered view should contain the text “Welcome to….” If, after the object performs the request, any of those expectations aren’t met, then the MockMvc test fails. But your controller and view template are written to satisfy those expectations, so the test should pass with flying colors—or at least with some shade of green indicating a passing test. The controller has been written, the view template created, and you have a passing test. It seems that you’ve implemented the homepage successfully. But even though the test passes, there’s something slightly more satisfying with seeing the results in a browser. After all, that’s how Taco Cloud customers are going to see it. Let’s build the application and run it. Just as there are several ways to initialize a Spring application, there are several ways to run one. If you like, you can flip over to the appendix to read about some of the more common ways to run a Spring Boot application. Because you chose to use Spring Tool Suite to initialize and work on the project, you have a 1.3.4 Building and running the application 20 ©Manning Publications Co. To comment go to liveBook
  • 28. handy feature called the Spring Boot Dashboard available to help you run your application inside the IDE. The Spring Boot Dashboard appears as a tab, typically near the bottom left of the IDE window. Figure 1.7 shows an annotated screenshot of the Spring Boot Dashboard. Figure 1.7 Highlights of the Spring Boot Dashboard I don’t want to spend much time going over everything the Spring Boot Dashboard does, although figure 1.7 covers some of the most useful details. The important thing to know right now is how to use it to run the Taco Cloud application. Make sure taco-cloud application is highlighted in the list of projects (it’s the only application shown in figure 1.7), and then click the start button (the left-most button with both a green triangle and a red square). The application should start right up. As the application starts, you’ll see some Spring ASCII art fly by in the console, followed by some log entries describing the steps as the application starts. Before the logging stops, you’ll see a log entry saying Tomcat started on port(s): 8080 (http), which means that you’re ready to point your web browser at the homepage to see the fruits of your labor. Wait a minute. Tomcat started? When did you deploy the application to Tomcat? Spring Boot applications tend to bring everything they need with them and don’t need to be 21 ©Manning Publications Co. To comment go to liveBook
  • 29. deployed to some application server. You never deployed your application to Tomcat …​ Tomcat is a part of your application! (I’ll describe the details of how Tomcat became part of your application in section 1.3.6.) Now that the application has started, point your web browser to (or click http://localhost:8080 the globe button in the Spring Boot Dashboard) and you should see something like figure 1.8. Your results may be different if you designed your own logo image. But it shouldn’t vary much from what you see in figure 1.8. Figure 1.8 The Taco Cloud homepage It may not be much to look at. But this isn’t exactly a book on graphic design. The humble appearance of the homepage is more than sufficient for now. And it provides you a solid start on getting to know Spring. One thing I’ve glossed over up until now is DevTools. You selected it as a dependency when initializing your project. It appears as a dependency in the produced pom.xml file. And the Spring Boot Dashboard even shows that the project has DevTools enabled. But what is DevTools, and what does it do for you? Let’s take a quick survey of a couple of DevTools’ most useful features. As its name suggests, DevTools provides Spring developers with some handy development-time tools. Among those are 1.3.5 Getting to know Spring Boot DevTools 22 ©Manning Publications Co. To comment go to liveBook
  • 30. Automatic application restart when code changes Automatic browser refresh when browser-destined resources (such as templates, JavaScript, stylesheets, and so on) change Automatic disable of template caches Built in H2 Console if the H2 database is in use It’s important to understand that DevTools isn’t an IDE plugin, nor does it require that you use a specific IDE. It works equally well in Spring Tool Suite, IntelliJ IDEA, and NetBeans. Furthermore, because it’s only intended for development purposes, it’s smart enough to disable itself when deploying in a production setting. (We’ll discuss how it does this when you get around to deploying your application in chapter 19.) For now, let’s focus on the most useful features of Spring Boot DevTools, starting with automatic application restart. With DevTools as part of your project, you’ll be able to make changes to Java code and properties files in the project and see those changes applied after a brief moment. DevTools monitors for changes, and when it sees something has changed, it automatically restarts the application. More precisely, when DevTools is in play, the application is loaded into two separate class loaders in the Java virtual machine (JVM). One class loader is loaded with your Java code, property files, and pretty much anything that’s in the src/main/ path of the project. These are items that are likely to change frequently. The other class loader is loaded with dependency libraries, which aren’t likely to change as often. When a change is detected, DevTools reloads only the class loader containing your project code and restarts the Spring application context, but leaves the other class loader and the JVM intact. Although subtle, this strategy affords a small reduction in the time it takes to start the application. The downside of this strategy is that changes to dependencies won’t be available in automatic restarts. That’s because the class loader containing dependency libraries isn’t automatically reloaded. This means that any time you add, change, or remove a dependency in your build specification, you’ll need to do a hard restart of the application for those changes to take effect. By default, template options such as Thymeleaf and FreeMarker are configured to cache the results of template parsing so that templates don’t need to be reparsed with every request they serve. This is great in production, as it buys a bit of performance benefit. Cached templates, however, are not so great at development time. Cached templates make it impossible to make changes to the templates while the application is running and see the results AUTOMATIC APPLICATION RESTART AUTOMATIC BROWSER REFRESH AND TEMPLATE CACHE DISABLE 23 ©Manning Publications Co. To comment go to liveBook
  • 31. after refreshing the browser. Even if you’ve made changes, the cached template will still be in use until you restart the application. DevTools addresses this issue by automatically disabling all template caching. Make as many changes as you want to your templates and know that you’re only a browser refresh away from seeing the results. But if you’re like me, you don’t even want to be burdened with the effort of clicking the browser’s refresh button. It’d be much nicer if you could make the changes and witness the results in the browser immediately. Fortunately, DevTools has something special for those of us who are too lazy to click a refresh button. When DevTools is in play, it automatically enables a LiveReload ( ) server http://livereload.com/ along with your application. By itself, the LiveReload server isn’t very useful. But when coupled with a corresponding LiveReload browser plugin, it causes your browser to automatically refresh when changes are made to templates, images, stylesheets, JavaScript, and so on—in fact, almost anything that ends up being served to your browser. LiveReload has browser plugins for Google Chrome, Safari, and Firefox browsers. (Sorry, Internet Explorer and Edge fans.) Visit to find information on http://livereload.com/extensions/ how to install LiveReload for your browser. Although your project doesn’t yet use a database, that will change in chapter 3. If you choose to use the H2 database for development, DevTools will also automatically enable an H2 Console that you can access from your web browser. You only need to point your web browser to to gain insight into the data your application is working with. http://localhost:8080/h2-console At this point, you’ve written a complete, albeit simple, Spring application. You’ll expand on it throughout the course of the book. But now is a good time to step back and review what you’ve accomplished and how Spring played a part. Think back on how you got to this point. In short, these are the steps you’ve taken to build your Spring-based Taco Cloud application: You created an initial project structure using Spring Initializr. You wrote a controller class to handle the homepage request. You defined a view template to render the homepage. You wrote a simple test class to prove out your work. Seems pretty straightforward, doesn’t it? With the exception of the first step to bootstrap the BUILT IN H2 CONSOLE 1.3.6 Let’s review 24 ©Manning Publications Co. To comment go to liveBook
  • 32. project, each action you’ve taken has been keenly focused on achieving the goal of producing a homepage. In fact, almost every line of code you’ve written is aimed toward that goal. Not counting Java statements, I count only two lines of code in your controller class and no lines in the import view template that are Spring-specific. And although the bulk of the test class utilizes Spring testing support, it seems a little less invasive in the context of a test. That’s an important benefit of developing with Spring. You can focus on the code that meets the requirements of an application rather than on satisfying the demands of a framework. Although you’ll no doubt need to write some framework-specific code from time to time, it’ll usually be only a small fraction of your codebase. As I said before, Spring (with Spring Boot) can be considered the . frameworkless framework How does this even work? What is Spring doing behind the scenes to make sure your application needs are met? To understand what Spring is doing, let’s start by looking at the build specification. In the pom.xml file, you declared a dependency on the and starters. These two Web Thymeleaf dependencies transitively brought in a handful of other dependencies, including Spring’s MVC framework Embedded Tomcat Thymeleaf and the Thymeleaf layout dialect It also brought Spring Boot’s autoconfiguration library along for the ride. When the application starts, Spring Boot autoconfiguration detects those libraries and automatically Configures the beans in the Spring application context to enable Spring MVC Configures the embedded Tomcat server in the Spring application context Configures a Thymeleaf view resolver for rendering Spring MVC views with Thymeleaf templates In short, autoconfiguration does all the grunt work, leaving you to focus on writing code that implements your application functionality. That’s a pretty sweet arrangement, if you ask me! Your Spring journey has just begun. The Taco Cloud application only touched on a small portion of what Spring has to offer. Before you take your next step, let’s survey the Spring landscape and see what landmarks you’ll encounter on your journey. 25 ©Manning Publications Co. To comment go to liveBook
  • 33. Another Random Document on Scribd Without Any Related Topics
  • 34. alone is liked—that which sounds an alarm to the unconverted, and bids them prepare for the coming of the Judge. But there are for all Christians frequent calls to a service in which they need the courage of faith and every hope the covenant can give. At the present time no greater mistake is possible than to sit in comfort under the shadow of ancient forms and creeds. We cannot realise the value of the promise given to genuine faith unless we abandon the crumbling walls and meet our assailants in the open ground, where we can see them face to face, and know the spirit with which they fight, the ensigns of their war. There is no brave thinking now in those old shelters, no room to use the armour of light. Christianity is one of the free forces of human life. Its true inspiration is found only when those who stand by it are bent on securing and extending the liberties of men. The trumpets that lift to heaven the prayers of the faithful and fill the soldiers of the Cross with the hope of victory can never be in the hands of those who claim exclusive spiritual authority, nor will they ever again sound the old Hebrew note. They inspire those who are generous, who feel that the more they give the more they are blessed, who would impart to others their own life that God's love to the world may be known. They call us not to defend our own privileges, but to keep the way of salvation open to all, to prevent the Pharisee and the unbeliever from closing against men the door of heavenly grace. Once more; in the days of gladness and solemn feasting the trumpets were to be blown over the burnt offerings and peace offerings. The joy of the Passover, the hope of the new-moon festival, especially in the beginning of the seventh month, were to be sent up to heaven with the sound of these instruments, not as if Jehovah had forgotten His people and His covenant, but for the assurance and comfort of the worshippers. He was a Friend before whom they could rejoice, a King whose forgiveness was abundant, who showed mercy unto the thousands who loved Him and kept His commandments. The music, loud, and clear, and bold, was to carry to all who heard it the conviction that God had been sought in the
  • 35. way of His holy law, and would cause blessing to descend upon Israel. We claim with gentler sounds, those of lowly prayer and pleading, the help of the Most High. Even in the secret chamber when the door is shut we can address our Father, knowing that our claim will be answered for the sake of Christ. Yet there are times when the loud and clear hallelujahs, borne heavenward by human voices and pealing organ, seem alone to express our exultation. Then the instruments and methods of modern art may be said to bind the old Hebrew times, the ancient faith of the wilderness and of Zion, to our own. We carry out ideas that lie at the heart of the race; we realise that human skill, human discovery, find their highest use and delight when they make beautiful and inspiring the service of God. 3. The Order of March Numbers x. 11-28 The difficulties connected with the order of march prescribed in this passage have been often and fully rehearsed. According to the enumeration given in chap. ii., the van of the host formed by the division of Judah, men, women, and children, must have reached some six hundred thousand at least. The second division, headed by Reuben, would number five hundred thousand. The Levites, with their wives and children, according to the same computation would be altogether about seventy thousand. Then came the two remaining camps, about nine hundred thousand souls. At the first signal six hundred thousand would have to get into marching order and move off across the desert. There could be no absolute separation of the fighting men from their families and flocks, and even if there were no narrow passes to confine the vast multitude, it would occupy miles of road. We must not put a day's journey at more than ten miles. The foremost groups would therefore have reached the camping ground, let us say, when the last ranks of the
  • 36. second division were only beginning to move; and the rear would still be on its way when night had long fallen upon the desert. Whatever obstacles were removed for the Israelites, the actual distance to be traversed could not be made less; and the journey is always represented as a stern and serious discipline. When we take into account the innumerable hindrances which so vast a company would certainly have to contend with, it seems impossible that the order of march as detailed in this passage could have been followed for two days together. Suppose we receive the explanation that the numbers have been accidentally increased in the transcription of records. This would relieve the narrative, not only here but at many points, of a burden it can hardly carry. And we remember that according to the Book of Nehemiah less than fifty thousand Jews, returning from Babylon at the close of the captivity, reconstructed the nation, so that it soon showed considerable spirit and energy. If the numbers as they stand in the Pentateuch were reduced, divided by ten, as some propose, the desert journey would appear less of a mere marvel. It would remain one of the most striking and important migrations known to history; it would lose none of its religious significance. No religious idea is affected by the numbers who receive it; nor do the great purposes of God depend on multitudes for their fulfilment. We can view with composure the criticism which touches the record on its numerical side, because we know the prophetic work of Moses and the providential education of Israel to be incontrovertible facts. It has been suggested that the order of march as described did not continue to be kept throughout the whole of the wilderness journey; that in point of fact it may have been followed only so far as Kadesh. Whether this was so or not it must be taken into account that for the greater part of the forty years there was absolutely no travelling; the tribes were settled in the wilderness of Paran. The proofs are incidental but conclusive. From a central point, where the cloud rested (Numb. x. 12), the people spread themselves, we may suppose, in various directions, seeking grass for their cattle, and
  • 37. living for the most part like the other inhabitants of the district. Even if there were but three years of travelling in all, before and after the sojourn in the neighbourhood of Kadesh, there would be ample time for the movement from one place to another mentioned in the records.
  • 38. VIII HOBAB THE KENITE Numbers x. 29-36 The Kenites, an Arab tribe belonging to the region of Midian, and sometimes called Midianites, sometimes Amalekites, were already in close and friendly relation with Israel. Moses, when he went first to Midian, had married a daughter of their chief Jethro, and, as we learn from Exod. xviii., this patriarch, with his daughter Zipporah and the two sons she had borne to Moses, came to the camp of Israel at the mount of God. The meeting was an occasion of great rejoicing; and Jethro, as priest of his tribe, having congratulated the Hebrews on the deliverance Jehovah had wrought for them, "took a burnt offering and sacrifices for God," and was joined by Moses, Aaron, and all the elders of Israel in the sacrificial feast. A union was thus established between Kenites and Israelites of the most solemn and binding kind. The peoples were sworn to continual friendship. While Jethro remained in the camp his counsel was given in regard to the manner of administering justice. In accordance with it rulers of thousands, hundreds, fifties, and tens were chosen, "able men, such as feared God, men of truth, hating covetousness"; and to them matters of minor importance were referred for judgment, the hard causes only being brought before Moses. The sagacity of one long experienced in the details of government came in to supplement the intellectual power and the inspiration of the Hebrew leader.
  • 39. It does not appear that any attempt was made to attach Jethro and the whole of his tribe to the fortunes of Israel. The small company of the Kenites could travel far more swiftly than a great host, and, if they desired, could easily overtake the march. Moses, we are told, let his father-in-law depart, and he went to his own place. But now that the long stay of the Israelites at Sinai is over and they are about to advance to Canaan, the visit of a portion of the Kenite tribe is made the occasion of an appeal to their leader to cast in his lot with the people of God. There is some confusion in regard to the relationship of Hobab with Jethro or Raguel. Whether Hobab was a son or grandson of the chief cannot be made out. The word translated father-in-law (Numb. x. 29), means a relation by marriage. Whatever was the tie between Hobab and Moses, it was at all events so close, and the Kenite had so much sympathy with Israel, that it was natural to make the appeal to him: "Come thou with us, and we will do thee good." Himself assured of the result of the enterprise, anticipating with enthusiasm the high destiny of the tribes of Israel, Moses endeavours to persuade these children of the desert to take the way to Canaan. There was a fascination in the movement of that people who, rescued from bondage by their Heavenly Friend, were on their journey to the land of His promise. This fascination Hobab and his followers appear to have felt; and Moses counted upon it. The Kenites, used to the wandering life, accustomed to strike their tents any day as occasion required, no doubt recoiled from the thought of settling even in a fertile country, still more from dwelling in any walled town. But the south of Canaan was practically a wilderness, and there, keeping to a great extent their ancestral habits, they might have had the liberty they loved, yet kept in touch with their friends of Israel. Some aversion from the Hebrews, who still bore certain marks of slavery, would have to be overcome. Yet, with the bond already established, there needed only some understanding of the law of Jehovah, and some hope in His promise to bring the company of Hobab to decision.
  • 40. And Moses had right in saying, "Come with us, and we will do thee good; for Jehovah hath spoken good concerning Israel." The outlook to a future was something which the Kenites as a people had not, never could have in their desultory life. Unprogressive, out of the way of the great movements of humanity, gaining nothing as generations went by, but simply reproducing the habits and treasuring the beliefs of their fathers, the Arab tribe might maintain itself, might occasionally strike for righteousness in some conflict, but otherwise had no prospect, could have no enthusiasm. They would live their hard life, they would enjoy freedom, they would die —such would be their history. Compared with that poor outlook, how good it would be to share the noble task of establishing on the soil of Canaan a nation devoted to truth and righteousness, in league with the living God, destined to extend His kingdom and make His faith the means of blessing to all. It was the great opportunity of these nomads. As yet, indeed, there was no courage of religion, no brightness of enthusiasm among the Israelites. But there was the ark of the covenant, there were the sacrifices, the law; and Jehovah Himself, always present with His people, was revealing His will and His glory by oracle, by discipline and deliverance. Now these Kenites may be taken as representing a class, in the present day to a certain extent attracted, even fascinated, by the Church, who standing irresolute are appealed to in terms like those addressed by Moses to Hobab. They feel a certain charm, for in the wide organisation and vast activity of the Christian Church, quite apart from the creed on which it is based, there are signs of vigour and purpose which contrast favourably with endeavours directed to mere material gain. In idea and in much of its effort the Church is splendidly humane, and it provides interests, enjoyments, both of an intellectual and artistic kind, in which all can share. Not so much its universality nor its mission of converting the world, nor its spiritual worship, but rather the social advantages and the culture it offers draw towards it those minds and lives. And to them it extends, too often without avail, the invitation to join its march.
  • 41. Is it asked why many, partly fascinated, remain proof against its appeals? why an increasing number prefer, like Hobab, the liberty of the desert, their own unattached, desultory, hopeless way of life? The answer must partly be that, as it is, the Church does not fully commend itself by its temper, its enthusiasm, its sincerity and Christianity. It attracts but is unable to command, because with all its culture of art it does not appear beautiful, with all its claims of spirituality it is not unworldly; because, professing to exist for the redemption of society, its methods and standards are too often human rather than Divine. It is not that the outsider shrinks from the religiousness of the Church as overdone; rather does he detect a lack of that very quality. He could believe in the Divine calling and join the enterprise of the Church if he saw it journeying steadily towards a better country, that is a heavenly. Its earnestness would then command him; faith would compel faith. But social status and temporal aims are not subordinated by the members of the Church, nor even by its leaders. And whatever is done in the way of providing attractions for the pleasure-loving, and schemes of a social kind, these, so far from gaining the undecided, rather make them less disposed to believe. More exciting enjoyments can be found elsewhere. The Church offering pleasures and social reconstruction is attempting to catch those outside by what, from their point of view, must appear to be chaff. It is a question which every body of Christians has need to ask itself —Can we honestly say to those without, Come with us, and we will do you good? In order that there may be certainty on this point, should not every member of the Church be able to testify that the faith he has gives joy and peace, that his fellowship with God is making life pure and strong and free? Should there not be a clear movement of the whole body, year by year, towards finer spirituality, broader and more generous love? The gates of membership are in some cases opened to such only as make very clear and ample profession. It does not, however, appear that those already within have always the Christian spirit corresponding to that high profession. And yet as Moses could invite Hobab and his company
  • 42. without misgiving because Jehovah was the Friend and Guide of Israel and had spoken good concerning her, so because Christ is the Head of the Church, and Captain of her salvation, those outside may well be urged to join her fellowship. If all depended on the earnestness of our faith and the steadfastness of our virtue we should not dare to invite others to join the march. But it is with Christ we ask them to unite. Imperfect in many ways, the Church is His, exists to show His death, to proclaim His Gospel and extend His power. In the whole range of human knowledge and experience there is but one life that is free, pure, hopeful, energetic in every noble sense, and at the same time calm. In the whole range of human existence there is but one region in which the mind and the soul find satisfaction and enlargement, in which men of all sorts and conditions find true harmony. That life and that region of existence are revealed by Christ; into them He only is the Way. The Church, maintaining this, demonstrating this, is to invite all who stand aloof. They who join Christ and follow Him will come to a good land, a heavenly heritage. The first invitation given to Hobab was set aside. "Nay," he said, "I will not go; but I will depart to my own land and to my kindred." The old ties of country and people were strong for him. The true Arab loves his country passionately. The desert is his home, the mountains are his friends. His hard life is a life of liberty. He is strongly attached to his tribe, which has its own traditions, its own glories. There have been feuds, the memory of which must be cherished. There are heirlooms that give dignity to those who possess them. The people of the clan are brothers and sisters. Very little of the commercial mingles with the life of the desert; so perhaps family feeling has the more power. These influences Hobab felt, and this besides deterred him, that if he joined the Israelites he would be under the command of Moses. Hobab was prospective head of his tribe, already in partial authority at least. To obey the word of command instead of giving it was a thing he could not brook. No doubt the leader of Israel had proved himself brave, resolute, wise. He was a man of ardent soul and fitted for royal
  • 43. power. But Hobab preferred the chieftainship of his own small clan to service under Moses; and, brought to the point of deciding, he would not agree. Freedom, habit, the hopes that have become part of life—these in like manner interpose between many and a call which is known to be from God. There is restraint within the circle of faith; old ideas, traditional conceptions of life, and many personal ambitions have to be relinquished by those who enter it. Accustomed to that Midian where every man does according to the bent of his own will, where life is hard but uncontrolled, where all they have learned to care for and desire may be found, many are unwilling to choose the way of religion, subjection to the law of Christ, the life of spiritual conflict and trial, however much may be gained at once and in the eternal future. Yet the liberty of their Midian is illusory. It is simply freedom to spend strength in vain, to roam from place to place where all alike are barren, to climb mountains lightning-riven, swept by interminable storms. And the true liberty is with Christ, who opens the prospect of the soul, and redeems the life from evil, vanity, and fear. The heavenward march appears to involve privation and conflict, which men do not care to face. But is the worldly life free from enemies, hardships, disappointments? The choice is, for many, between a bare life over which death triumphs, and a life moving on over obstacles, through tribulations, to victory and glory. The attractions of land and people, set against those of Christian hope, have no claim. "Every one," says the Lord, "that hath left houses, or brethren, or sisters, or father, or mother, or children, or lands, for My sake, shall receive a hundredfold, and shall inherit eternal life." Passing on, the narrative informs us that Moses used another plea: "Leave us not, I pray thee; forasmuch as thou knowest how we are to encamp in the wilderness, and thou shalt be to us instead of eyes." Hobab did not respond to the promise of advantage to himself; he might be moved by the hope of being useful. Knowing that he had to deal with a man who was proud, and in his way magnanimous, Moses wisely used this appeal. And he used it frankly,
  • 44. without pretence. Hobab might do real and valuable service to the tribes on their march to Canaan. Accustomed to the desert, over which he had often travelled, acquainted with the best methods of disposing a camp in any given position, with the quick eye and habit of observation which the Arab life gives, Hobab would be the very adjutant to whom Moses might commit many details. If he joins the tribes on this footing it will be without pretence. He professes no greater faith either in Israel's destiny or in Jehovah's sole Godhead than he really feels. Wishing Israel well, interested in the great experiment, yet not bound up in it, he may give his counsel and service heartily so far as they avail. We are here introduced to another phase of the relation between the Church and those who do not altogether accept its creed, or acknowledge its mission to be supernatural, Divine. Confessing unwillingness to receive the Christian system as a whole, perhaps openly expressing doubts of the miraculous, for example, many in our day have still so much sympathy with the ethics and culture of Christianity that they would willingly associate themselves with the Church, and render it all the service in their power. Their tastes have led them to subjects of study and modes of self-development not in the proper sense religious. Some are scientific, some have literary talent, some artistic, some financial. The question may be, whether the Church should invite these to join her ranks in any capacity, whether room may be made for them, tasks assigned to them. On the one hand, would it be dangerous to Christian faith? on the other hand, would it involve them in self-deception? Let it be assumed that they are men of honour and integrity, men who aim at a high moral standard and have some belief in the spiritual dignity man may attain. On this footing may their help be sought and cordially accepted by the Church? We cannot say that the example of Moses should be taken as a rule for Christians. It was one thing to invite the co-operation with Israel for a certain specified purpose of an Arab chief who differed somewhat in respect of faith; it would be quite another thing to
  • 45. invite one whose faith, if he has any, is only a vague theism, to give his support to Christianity. Yet the cases are so far parallel that the one illustrates the other. And one point appears to be this, that the Church may show itself at least as sympathetic as Israel. Is there but a single note of unison between a soul and Christianity? Let that be recognised, struck again and again till it is clearly heard. Our Lord rewarded the faith of a Syrophœnician woman, of a Roman centurion. His religion cannot be injured by generosity. Attachment to Himself personally, disposition to hear His words and accept His morality, should be hailed as the possible dawn of faith, not frowned upon as a splendid sin. Every one who helps sound knowledge helps the Church. The enthusiast for true liberty has a point of contact with Him whose truth gives freedom. The Church is a spiritual city with gates that stand wide open day and night towards every region and condition of human life, towards the north and south, the east and west. If the wealthy are disposed to help, let them bring their treasures; if the learned devote themselves reverently and patiently to her literature, let their toil be acknowledged. Science has a tribute that should be highly valued, for it is gathered from the works of God; and art of every kind—of the poet, the musician, the sculptor, the painter—may assist the cause of Divine religion. The powers men have are given by Him who claims all as His own. The vision of Isaiah in which he saw Tarshish and the isles, Sheba and Seba offering gifts to the temple of God, did not assume that the tribute was in all cases that of covenant love. And the Church of Christ has broader human sympathy and better right to the service of the world than Isaiah knew. For the Church's good, and for the good of those who may be willing in any way to aid her work and development, all gifts should be gladly received, and those who stand hesitating should be invited to serve. But the analogy of the invitation to Hobab involves another point which must always be kept in view. It is this, that the Church is not to slacken her march not divert her march in any degree because men not fully in sympathy with her join the company and contribute their service. The Kenite may cast in his lot with the Israelites and
  • 46. aid them with his experience. But Moses will not cease to lead the tribes towards Canaan, will not delay their progress a single day for Hobab's sake. Nor will he less earnestly claim sole Godhead for Jehovah, and insist that every sacrifice shall be made to Him and every life kept holy in His way, for His service. Perhaps the Kenite faith differed little in its elements from that which the Israelites inherited. It may have been monotheistic; and we know that part of the worship was by way of sacrifice not unlike that appointed by the Mosaic law. But it had neither the wide ethical basis nor the spiritual aim and intensity which Moses had been the means of imparting to Israel's religion. And from the ideas revealed to him and embodied in the moral and ceremonial law he could not for the sake of Hobab resile in the least. There should be no adjustment of creed or ritual to meet the views of the new ally. Onward to Canaan, onward also along the lines of religious duty and development, the tribes would hold their way as before. In modern alliances with the Church a danger is involved, sufficiently apparent to all who regard the state of religion. History is full of instances in which, to one company of helpers and another, too much has been conceded; and the march of spiritual Christianity is still greatly impeded by the same thing. Money contributed, by whomsoever, is held to give the donors a right to take their place in councils of the Church, or at least to sway decision now in one direction, now in another. Prestige is offered with the tacit understanding that it shall be repaid with deference. The artist uses his skill, but not in subordination to the ideas of spiritual religion. He assumes the right to give them his own colour, and may even, while professing to serve Christianity, sensualise its teaching. Scholarship offers help, but is not content to submit to Christ. Having been allowed to join itself with the Church, it proceeds, not infrequently, to play the traitor's part, assailing the faith it was invoked to serve. Those who care more for pleasure than for religion may within a certain range find gratification in Christian worship; they are apt to claim more and still more of the element that meets their taste. And those who are bent on social reconstruction would often, without
  • 47. any thought of doing wrong, divert the Church entirely from its spiritual mission. When all these influences are taken into account, it will be seen that Christianity has to go its way amid perils. It must not be unsympathetic. But those to whom its camp is opened, instead of helping the advance, may neutralise the whole enterprise. Every Church has great need at present to consider whether that clear spiritual aim which ought to be the constant guide is not forgotten, at least occasionally, for the sake of this or that alliance supposed to be advantageous. It is difficult to find the mean, difficult to say who serve the Church, who hinder its success. More difficult still is it to distinguish those who are heartily with Christianity from those who are only so in appearance, having some nostrum of their own to promote. Hobab may decide to go with Israel; but the invitation he accepts, perhaps with an air of superiority, of one conferring a favour, is really extended to him for his good, for the saving of his life. Let there be no blowing of the silver trumpets to announce that a prince of the Kenites henceforth journeys with Israel; they were not made for that! Let there be no flaunting of a gay ensign over his tent. We shall find that a day comes when the men who stand by true religion have—perhaps through Kenite influence—the whole congregation to face. So it is in Churches. On the other hand, Pharisaism is a great danger, equally tending to destroy the value of religion; and Providence ever mingles the elements that enter into the counsels of Christianity, challenging the highest wisdom, courage, and charity of the faithful. The closing verses of chap. x. (33-6), belonging, like the passage just considered, to the prophetic narrative, affirm that the ark was borne from Sinai three days' journey before the host to find a halting-place. The reconciliation between this statement and the order which places the ark in the centre of the march, may be that
  • 48. the ideal plan was at the outset not observed, for some sufficient reason. The absolute sincerity of the compilers of the Book of Numbers is shown in their placing almost side by side the two statements without any attempt to harmonise. Both were found in the ancient documents, and both were set down in good faith. The scribes into whose hands the old records came did not assume the rôle of critics. At the beginning of every march Moses is reported to have used the chant: "Rise up, O Jehovah, and let Thine enemies be scattered; and let them that hate Thee flee before Thee." When the ark rested he said: "Return, O Jehovah, unto the ten thousands of the thousands of Israel." The former is the opening strain of Psalm lxviii., and its magnificent strophes move towards the idea of that rest which Israel finds in the protection of her God. Part of the ode returns upon the desert journey, adding some features and incidents omitted in the narrations of the Pentateuch—such as the plentiful rain which refreshed the weary tribes, the publishing by women of some Divine oracle. But on the whole the psalm agrees with the history, making Sinai the scene of the great revelation of God, and indicating the guidance He gave through the wilderness by means of the cloudy pillar. The chants of Moses would be echoed by the people, and would help to maintain the sense of constant relation between the tribes and their unseen Defender. Through the wilderness Israel went, not knowing from what quarter the sudden raid of a desert people might be made. Swiftly, silently, as if springing out of the very sand, the Arab raiders might bear down upon the travellers. They were assured of the guardianship of Him whose eye never slumbered, when they kept His way and held themselves at His command. Here the resemblance to our case in the journey of life is clear; and we are reminded of our need of defence and the only terms on which we may expect it. We may look for protection against those who are the enemies of God. But we have no warrant for assuming that on whatever errand we are bound we have but to invoke the Divine arm in order to be secure.
  • 49. The dreams of those who think their personal claim on God may always be urged have no countenance in the prayer, "Rise up, O Jehovah, and let Thine enemies be scattered." And as Israel settling to rest after some weary march could enjoy the sense of Jehovah's presence only if the duties of the day had been patiently done, and the thought of God's will had made peace in every tribe, and His promise had given courage and hope—so for us, each day will close with the Divine benediction when we have "fought a good fight and kept the faith." Fidelity there must be; or, if it has failed, the deep repentance that subdues wandering desire and rebellious will, bringing the whole of life anew into the way of lowly service.
  • 50. IX THE STRAIN OF THE DESERT JOURNEY Numbers xi The narrative has accompanied the march of Israel but a short way from the mount of God to some spot marked for an encampment by the ark of the covenant, and already complaining has to be told of, and the swift judgment of those who complained. The Israelites have made a reservation in their covenant with God, that though obedience and trust are solemnly promised, yet leave shall be taken to murmur against His providence. They will have God for their Protector, they will worship Him; but let Him make their life smooth. Much has had to be borne which they did not anticipate; and they grumble and speak evil. Generally men do not realise that their murmuring is against God. They have no intention to accuse His providence. It is of other men they complain, who come in their way; of accidents, so called, for which no one seems to be responsible; of regulations, well enough meant, which at some point prove vexatious; the obtuseness and carelessness of those who undertake but do not perform. And there does seem to be a great difference between displeasure with human agents whose follies and failures provoke us, and discontent with our own lot and its trials. At the same time, this has to be kept in view, that while we carefully refrain from criticising Providence, there may be, underlying our complaints, a tacit opinion that the world is not well made nor well ordered. To a certain extent the persons who
  • 51. irritate us are responsible for their mistakes; but just among those who are prone to err our discipline has been appointed. To gird at them is as much a revolt against the Creator as to complain of the heat of summer or the winter cold. With our knowledge of what the world is, of what our fellow-creatures are, should go the perception that God rules everywhere and stands against us when we resent what, in His world, we have to do or to suffer. He is against those who fail in duty also. Yet it is not for us to be angry. Our due will not be withheld. Even when we suffer most it is still offered, still given. While we endeavour to remedy the evils we feel, it must be without a thought that the order appointed by the Great King fails us at any point. The punishment of those who complained is spoken of as swift and terrible. "The fire of the Lord burnt among them, and devoured in the uttermost part of the camp." This judgment falls under a principle assumed throughout the whole book, that disaster must overtake transgressors, and conversely that death by pestilence, earthquake, or lightning is invariably a result of sin. For the Israelites this was one of the convictions that maintained a sense of moral duty and of the danger of offending God. Again and again in the wilderness, where thunderstorms were common and plagues spread rapidly, the impression was strongly confirmed that the Most High observed everything that was done against His will. The journey to Canaan brought in this way a new experience of God to those who had been accustomed to the equable conditions of climate and the comparative health enjoyed in Egypt. The moral education of the people advanced by the quickening of conscience in regard to all that befell Israel. From the disaster at Taberah the narrative passes to another phase of complaint in which the whole camp was involved. The dissatisfaction began amongst the "mixed multitude"—that somewhat lawless crowd of low-caste Egyptians and people of the Delta and the wilderness who attached themselves to the host. Among them first, because they had absolutely no interest in Israel's
  • 52. hope, a disposition to quarrel with their circumstances would naturally arise. But the spirit of dissatisfaction grew apace, and the burden of the new complaint was: "We have nought but this manna to look to." The part of the desert into which the travellers had now penetrated was even more sterile than Midian. Hitherto the food had been varied somewhat by occasional fruits and the abundant milk of kine and goats. But pasturage for the cattle was scanty in the wilderness of Paran, and there were no trees of any kind. Appetite found nothing that was refreshing. Their soul was dried away. It was a common belief in our Lord's time that the manna, falling from heaven, very food of the angels, had been so satisfying, so delicious, that no people could have been more favoured than those who ate of it. When Christ spoke of the meat which endureth unto eternal life, the thought of His hearers immediately turned to the manna as the special gift of God to their fathers, and they conceived an expectation that Jesus would give them that bread of heaven, and so prove Himself worthy of their faith. But He replied, "Moses gave you not that bread out of heaven, but My Father giveth you the true bread out of heaven. I am the Bread of Life." In the course of time the manna had been, so to speak, glorified. It appeared to the later generations one of the most wonderful and impressive things recorded in the whole history of their nation, this provision made for the wandering host. There was the water from the rock, and there was the manna. What a benignant Providence had watched over the tribes! How bountiful God had been to the people in the old days! They longed for a sign of the same kind. To enjoy it would restore their faith and put them again in the high position which had been denied for ages. But these notions are not borne out by the history as we have it in the passage under notice. Nothing is said about angels' food—that is a poetical expression which a psalmist used in his fervour. Here we read, as to the coming of the manna, that when the dew fell upon the camp at night the manna fell upon it, or with it. And so far from the people being satisfied, they complained that instead of the fish
  • 53. and onions, cucumbers and melons of Egypt, they had nothing but manna to eat. The taste of it is described as like that of fresh oil. In Exodus it is said to have resembled wafers mixed with honey. It was not the privilege of the Israelites in the wilderness but their necessity to live on this somewhat cloying food. In no sense can it be called ideal. Nevertheless, complaining about it, they were in serious fault, betraying the foolish expectation that on the way to liberty they should have no privations. And their discontent with the manna soon became alarming to Moses. A sort of hysteria spread through the camp. Not the women only, but the men at the doors of their tents bewailed their hard lot. There was a tempest of tears and cries. God, through His providence, determining for men, carrying out His own designs for their good, does not allow them to keep in the region of the usual and of mere comfort. Something is brought into their life which stirs the soul. In new hope they begin an enterprise the course and end of which they cannot foresee. The conventional, the pleasant, the peace and abundance of Egypt, can be no longer enjoyed if the soul is to have its own. By Moses Jehovah summoned the Israelites from the land of plenty to fulfil a high mission; and when they responded, it was so far a proof that there was in them spirit enough for an uncommon destiny. But for the accomplishment of it they had to be nerved and braced by trial. Their ordeal was that mortifying of the flesh and of sensuous desire which must be undergone if the hopes through which the mind becomes conscious of the will of God are to be fulfilled. In our personal history God, reaching us by His word, enlightening us with regard to the true ends of our being, calls us to begin a journey which has no earthly terminus and promises no earthly reward. We may be quite sure that we have not yet responded to His call if there is nothing of the wilderness in our life, no hardship, no adventure, no giving up of what is good in a temporal sense for what is good in a spiritual sense. The very essence of the design of God concerning a man is that he leave the lower and seek the
  • 54. higher, that he deny himself that which according to the popular view is his life, in order to seek a remote and lofty goal. There will be duty that calls for faith, that needs hope and courage. In doing it he will have recurring trials of his spirit, necessities of self-discipline, stern difficulties of choice and action. Every one of these he must face. What is wrong with many lives is that they have no strain in them as of a desert journey towards a heavenly Canaan, the realisation of spiritual life. Adventure, when it is undertaken, is often for the sake of getting fish and melons and cucumbers by-and-by in greater abundance and of better kinds. Many live hardly just now, not because they are on the way to spiritual freedom and the high destiny of life in God, but because they believe themselves to be on the way to better social position, to wealth or honour. But take the life that has begun its high enterprise at the urgency of a Divine vocation, and that life will find hardness, deprivations, perils, of its own. It is not given to us to be absolutely certain in decision and endeavour. Out in the wilderness, even when manna is provided, and the pillar of cloud seems to show the way, the people of God are in danger of doubting whether they have done wisely, whether they have not taken too much upon themselves or laid too much upon the Lord. The Israelites might have said, We have obeyed God: why, then, should the sun smite us with burning heat, and the dust- storms sweep down upon our march, and the night fall with so bitter a chill? Interminable toil, in travelling, in attending to cattle and domestic duties, in pitching tents and striking them, gathering fuel, searching far and wide through the camp for food, helping the children, carrying the sick and aged, toil that did not cease till far into the night and had to be resumed with early morning—such, no doubt, were the things that made life in the wilderness irksome. And although many now have a lighter burden, yet our social life, adding new difficulties with every improvement, our domestic affairs, the continual struggle necessary in labour and business, furnish not a few causes of irritation and of bitterness. God does not remove annoyances out of the way even of His devoted servants. We
  • 55. remember how Paul was vexed and burdened while carrying the world's thought on into a new day. We remember what a weight the infirmities and treacheries of men laid upon the heart of Christ. Let us thank God if we feel sometimes across the wilderness a breeze from the hills of the heavenly Canaan, and now and then catch glimpses of them far away. But the manna may seem flat and tasteless, nevertheless; the road may seem long; the sun may scorch. Tempted to despond, we need afresh to assure ourselves that God is faithful who has given us His promise. And although we seem to be led not towards the heavenly frontier, but often aside through close defiles into some region more barren and dismal than we have yet crossed, doubt is not for us. He knoweth the way that we take; when He has tried us, we shall come forth where He appoints. From the people we turn to Moses and the strain he had to bear as leader. Partly it was due to his sense of the wrath of God against Israel. To a certain extent he was responsible for those he led, for nothing he had done was apart from his own will. The enterprise was laid on him as a duty certainly; yet he undertook it freely. Such as the Israelites were, with that mixed multitude among them, a dangerous element enough, Moses had personally accepted the leadership of them. And now the murmuring, the lusting, the childish weeping, fall upon him. He feels that he must stand between the people and Jehovah. The behaviour of the multitude vexes him to the soul; yet he must take their part, and avert, if possible, their condemnation. The position is one in which a leader of men often finds himself. Things are done which affront him personally, yet he cannot turn against the wayward and unbelieving, for, if he did, the cause would be lost. The Divine judgment of the transgressors falls on him all the more because they themselves are unaware of it. The burden such an one has to sustain points directly to the sin-bearing of Christ. Wounded to the soul by the wrong-doing of men, He had to interpose between them and the stroke of the law, the judgment of
  • 56. God. And may not Moses be said to be a type of Christ? The parallel may well be drawn; yet the imperfect mediation of Moses fell far short of the perfect mediation of our Lord. The narrative here reflects that partial knowledge of the Divine character which made the mediation of Moses human and erring for all its greatness. For one thing Moses exaggerated his own responsibility. He asked of God: "Why hast Thou evil entreated Thy servant? Why dost Thou lay the burden of all this people upon me? Am I their father? Am I to carry the whole multitude as a father carries his young child in his bosom?" These are ignorant words, foolish words. Moses is responsible, but not to that extent. It is fit that he should be grieved when the Israelites do wrong, but not proper that he should charge God with laying on him the duty of keeping and carrying them like children. He speaks unadvisedly with his lips. Responsibility of those who endeavour to lead others has its limits; and the range of duty is bounded in two ways—on the one hand by the responsibility of men for themselves, on the other hand by God's responsibility for them, God's care of them. Moses should see that no law or ordinance makes him chargeable with the childish lamentations of those who know they should not complain, who ought to be manly and endure with stout hearts. If persons who can go on their own feet want to be carried, no one is responsible for carrying them. It is their own fault when they are left behind. If those who can think and discover duty for themselves, desire constantly to have it pointed out to them, crave daily encouragement in doing their duty, and complain because they are not sufficiently considered, the leader, like Moses, is not responsible. Every man must bear his own burden—that is, must bear the burden of duty, of thought, of effort, so far as his ability goes. Then, on the other side, the power of God is beneath all, His care extends over all. Moses ought not for a moment to doubt Jehovah's mindfulness of His people. Men who hold office in society or the Church are never to think that their effort is commensurate with God's. Proud indeed he would be who said: "The care of all these
  • 57. souls lies on me: if they are to be saved, I must save them; if they perish, I shall be chargeable with their blood." Speaking ignorantly and in haste, Moses went almost that length; but his error is not to be repeated. The charge of the Church and of the world is God's; and He never fails to do for all and for each what is right. The teacher of men, the leader of affairs, with full sympathy and indefatigable love, is to do all he can, yet never trench on the responsibility of men for their own life, or assume to himself the part of Providence. Moses made one mistake and went on to another. He was on the whole a man of rare patience and meekness; yet on this occasion he spoke to Jehovah in terms of daring resentment. His cry was to get rid of the whole enterprise: "If Thou deal thus with me, kill me, I pray Thee, out of hand, and let me not see my wretchedness." He seemed to himself to have this work to do and no other, apparently imagining that if he was not competent for this, he could be of no use in the world. But even if he had failed as a leader, highest in office, he might have been fit enough for a secondary place, under Joshua or some other whom God might inspire: this he failed to see. And although he was bound up in Israel's well-being, so that if the expedition did not prosper he had no wish to live, and was so far sincerely patriotic, yet what good end could his death serve? The desire to die shows wounded pride. Better live on and turn shepherd again. No man is to despise his life, whatever it is, however it may seem to come short of the high ambition he has cherished as a servant of God and men. Discovering that in one line of endeavour he cannot do all he would, let him make trial of others, not pray for death. The narrative represents God as dealing graciously with his erring servant. Help was provided for him by the appointment of seventy elders, who were to share the task of guiding and controlling the tribes. These seventy were to have a portion of the leader's spirit— zeal and enthusiasm like his own. Their influence in the camp would prevent the faithlessness and dejection which threatened to wreck
  • 58. the Hebrew enterprise. Further, the murmuring of the people was to be effectually silenced. Flesh was to be given them till they loathed it. They should learn that the satisfaction of ignorant desire meant punishment rather than pleasure. The promise of flesh was speedily fulfilled by an extraordinary flight of quails, brought up, according to the seventy-eighth Psalm, by a wind which blew from the south and east—that is, from the Elanitic Gulf. These quails cannot sustain themselves long on the wing, and after crossing the desert some thirty or forty miles they would scarcely be able to fly. The enormous numbers of them which fluttered around the camp are not beyond ordinary possibility. Fowls of this kind migrate at certain seasons in such enormous multitudes that in the small island of Capri, near Naples, one hundred and sixty thousand have been netted in one season. When exhausted, they would easily be taken as they flew at a height of about two cubits above the ground. The whole camp was engaged in capturing quails from one morning to the evening of the following day; and the quantity was so great that he who gathered least had ten homers, probably a heap estimated to be of that measure. To keep them for further use the birds were prepared and spread on the ground to dry in the sun. When the epidemic of weeping broke out through the camp, the doubt occurred to Moses whether there was any spiritual quality in the people, any fitness for duty or destiny of a religious kind. They seemed to be all unbelievers on whom the goodness of God and the sacred instruction had been wasted. They were earthly and sensual. How could they ever trust God enough to reach Canaan?—or if they reached it, how would their occupation of it be justified? They would but form another heathen nation, all the worse that they had once known the true God and had abandoned Him. But a different view of things was presented to Moses when the chosen elders, men of worth, were gathered at the tent of meeting, and on a sudden impulse of the Spirit began to prophesy. As these men in loud and ecstatic language proclaimed their faith, Moses found his confidence
  • 59. in Jehovah's power and in the destiny of Israel re-established. His mind was relieved at once of the burden of responsibility and the dread of an extinction of the heavenly light he had been the means of kindling among the tribes. If there were seventy men capable of receiving the Spirit of God, there might be hundreds, even thousands. A spring of new enthusiasm is opened, and Israel's future is again possible. Now there were two men, Eldad and Medad, who were of the seventy, but had not come to the tent of meeting, where the prophetic spirit fell upon the rest. They had not heard the summons, we may suppose. Unaware of what was taking place at the tabernacle, yet realising the honour conferred upon them, they were perhaps engaged in ordinary duties, or, having found some need for their interference, they may have been rebuking murmurers and endeavouring to restore order among the unruly. And suddenly they also, under the same influence as the other sixty-eight, began to prophesy. The spirit of earnestness caught them. With the same ecstasy they declared their faith and praised the God of Israel. There was in one sense a limitation of the spirit of prophecy, whatever it was. Of all the host only the seventy received it. Other good men and true in Israel that day might have seemed as capable of the heavenly endowment as those who prophesied. It was, however, in harmony with a known principle that the men designated to special office alone received the gift. The sense of a choice felt to be that of God does unquestionably exalt the mind and spirit of those chosen. They realise that they stand higher and must do more for God and men than others, that they are inspired to say what otherwise they could not dare to say. The limitation of the Spirit in this sense is not invariable, is not strict. At no time in the world's history has the call to office been indispensable to prophetic fervour and courage. Yet the sequence is sufficiently common to be called a law. But while in a sense there is restriction of the spiritual influence, in another sense there is no restraint. The Divine afflatus is not
  • 60. confined to those who have gathered at the tabernacle. It is not place or occasion that makes the prophets; it is the Spirit, the power from on high entering into life; and out in the camp the two have their portion of the new energy and zeal. Spiritual influence, then, is not confined to any particular place. Neither was the neighbourhood of the tabernacle so holy that there alone the elders could receive their gift; nor is any place of meeting, any church, capable of such consecration and singular identification with the service of God that there alone the power of the Divine Spirit can be manifested or received. Let there be a man chosen of God, ready for the duties of a holy calling, and on that man the Spirit will come, wherever he is, in whatever he is engaged. He may be employed in common work, but in doing it he will be moved to earnest service and testimony. He may be labouring, under great difficulties, to restore the justice that has been impaired by social errors and political chicanery—and his words will be prophetic; he will be a witness for God to those who are without faith, without holy fear. While Eldad and Medad prophesied in the camp, a young man who heard them ran officiously to inform Moses. To this young man as to others—for no doubt there were many who loved and revered the Usual—the two elders were presumptuous fools. The camp was, as we say, secular: was it not? People in the camp looked after ordinary affairs, tended their cattle, chaffered and bargained, quarrelled about trifles, murmured against Moses and against God. Was it right to prophesy there, carrying religious words and ideas into the midst of common life? If Eldad and Medad could prophesy, let them go to the tabernacle. And besides, what right had they to speak for Jehovah, in Jehovah's name? Was not Moses the prophet, the only prophet? Israel was accustomed to think him so, would keep to that opinion. It would be confusing if at any one's tent door a prophet might begin to speak without warning. So the young man thought it his duty to run and tell Moses what was taking place. And Joshua, when he heard, was alarmed, and desired Moses to put an end to the irregular ministry. "My lord Moses, forbid them," he said. He was jealous not for himself and the other elders, but for Moses' sake. So
  • 61. 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