0% found this document useful (0 votes)
14 views

Spring Boot Tutorials Point instant download

The document provides an overview of Spring Boot, an open-source Java framework designed for creating microservices and production-ready applications with minimal configuration. It outlines the tutorial's target audience, prerequisites, and key features of Spring Boot, including auto-configuration and dependency management. Additionally, it includes links to various related eBooks and resources for further learning.

Uploaded by

inalemjerat62
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Spring Boot Tutorials Point instant download

The document provides an overview of Spring Boot, an open-source Java framework designed for creating microservices and production-ready applications with minimal configuration. It outlines the tutorial's target audience, prerequisites, and key features of Spring Boot, including auto-configuration and dependency management. Additionally, it includes links to various related eBooks and resources for further learning.

Uploaded by

inalemjerat62
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 90

Spring Boot Tutorials Point download

https://ebookbell.com/product/spring-boot-tutorials-
point-46528248

Explore and download more ebooks at ebookbell.com


Here are some recommended products that we believe you will be
interested in. You can click the link to download.

Spring Boot Persistence Best Practices Optimize Java Persistence


Performance In Spring Boot Applications 1st Edition Anghel Leonard

https://ebookbell.com/product/spring-boot-persistence-best-practices-
optimize-java-persistence-performance-in-spring-boot-applications-1st-
edition-anghel-leonard-50194838

Spring Boot Cookbook Alex Antonov

https://ebookbell.com/product/spring-boot-cookbook-alex-
antonov-55587912

Spring Boot 3 Recipes A Problemsolution Approach For Java


Microservices And Cloudnative Applications 2nd Marten Deinum

https://ebookbell.com/product/spring-boot-3-recipes-a-problemsolution-
approach-for-java-microservices-and-cloudnative-applications-2nd-
marten-deinum-56416454

Spring Boot 30 Cookbook Proven Recipes For Building Modern And Robust
Java Web Applications With Spring Boot 1st Edition Felip Miguel Puig

https://ebookbell.com/product/spring-boot-30-cookbook-proven-recipes-
for-building-modern-and-robust-java-web-applications-with-spring-
boot-1st-edition-felip-miguel-puig-58534736
Spring Boot 20 Projects Build Productiongrade Reactive Applications
And Microservices With Spring Boot English Edition 1st Edition Mohamed
Shazin Sadakath

https://ebookbell.com/product/spring-boot-20-projects-build-
productiongrade-reactive-applications-and-microservices-with-spring-
boot-english-edition-1st-edition-mohamed-shazin-sadakath-22122616

Spring Boot Up And Running Mark Heckler

https://ebookbell.com/product/spring-boot-up-and-running-mark-
heckler-33190044

Spring Boot With React And Aws Learn To Deploy A Full Stack Spring
Boot React Application To Aws 1st Edition Ravi Kant Soni

https://ebookbell.com/product/spring-boot-with-react-and-aws-learn-to-
deploy-a-full-stack-spring-boot-react-application-to-aws-1st-edition-
ravi-kant-soni-35072896

Spring Boot Con React Marco Perez

https://ebookbell.com/product/spring-boot-con-react-marco-
perez-36078380

Spring Boot In Practice Meap V09 Meap 20211111 Somnath Musib

https://ebookbell.com/product/spring-boot-in-practice-
meap-v09-meap-20211111-somnath-musib-36246368
Spring Boot In Action 1 Itebooks Craig Walls

https://ebookbell.com/product/spring-boot-in-action-1-itebooks-craig-
walls-5474486
Spring Boot
Spring Boot

About the Tutorial


Spring Boot is an open source Java-based framework used to create a Micro Service. It is
developed by Pivotal Team. It is easy to create a stand-alone and production ready spring
applications using Spring Boot. Spring Boot contains a comprehensive infrastructure
support for developing a microservice and enables you to develop enterprise-ready
applications that you can “just run”.

Audience
This tutorial is designed for Java developers to understand and develop production-ready
spring applications with minimum configurations. It explores major features of Spring Boot
such as Starters, Auto-configuration, Beans, Actuator and more.

By the end of this tutorial, you will gain an intermediate level of expertise in Spring Boot.

Prerequisites
This tutorial is written for readers who have a prior experience of Java, Spring, Maven,
and Gradle. You can easily understand the concepts of Spring Boot if you have knowledge
on these concepts. It would be an additional advantage if you have an idea about writing
a RESTful Web Service. If you are a beginner, we suggest you to go through tutorials
related to these concepts before you start with Spring Boot.

Copyright and Disclaimer


 Copyright 2018 by Tutorials Point (I) Pvt. Ltd.

All the content and graphics published in this e-book are the property of Tutorials Point (I)
Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republish
any contents or a part of contents of this e-book in any manner without written consent
of the publisher.

We strive to update the contents of our website and tutorials as timely and as precisely as
possible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.
Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of our
website or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at [email protected]

i
Spring Boot

Table of Contents
About the Tutorial ........................................................................................................................................... i

Audience .................................................................................................................................................... i

Prerequisites .............................................................................................................................................. i

Copyright and Disclaimer ........................................................................................................................... i

Table of Contents ...................................................................................................................................... ii

1. SPRING BOOT – INTRODUCTION ............................................................................................. 1

What is Micro Service?.............................................................................................................................. 1

What is Spring Boot?................................................................................................................................. 1

Why Spring Boot? ..................................................................................................................................... 2

How does it work? .................................................................................................................................... 2

Spring Boot Starters .................................................................................................................................. 2

Auto Configuration ................................................................................................................................... 3

Spring Boot Application ............................................................................................................................ 4

Component Scan ....................................................................................................................................... 4

2. SPRING BOOT – QUICK START ................................................................................................. 6

Prerequisites ............................................................................................................................................. 6

Spring Boot CLI .......................................................................................................................................... 6

3. SPRING BOOT – BOOTSTRAPPING ........................................................................................... 8

Spring Initializer ........................................................................................................................................ 8

Maven....................................................................................................................................................... 9

Gradle ..................................................................................................................................................... 10

Class Path Dependencies ........................................................................................................................ 11

Main Method .......................................................................................................................................... 12

Write a Rest Endpoint ............................................................................................................................. 12

Create an Executable JAR ........................................................................................................................ 13

ii
Spring Boot

Run Hello World with Java ...................................................................................................................... 14

4. SPRING BOOT – TOMCAT DEPLOYMENT ............................................................................... 16

Spring Boot Servlet Initializer .................................................................................................................. 16

Setting Main Class ................................................................................................................................... 17

Update packaging JAR into WAR ............................................................................................................. 17

Packaging your Application ..................................................................................................................... 19

Deploy into Tomcat................................................................................................................................. 20

5. SPRING BOOT – BUILD SYSTEMS ........................................................................................... 25

Dependency Management ...................................................................................................................... 25

Maven Dependency ................................................................................................................................ 25

Gradle Dependency ................................................................................................................................ 26

6. SPRING BOOT – CODE STRUCTURE........................................................................................ 27

Default package ...................................................................................................................................... 27

Typical Layout ......................................................................................................................................... 27

6. SPRING BOOT – CODE STRUCTURE........................................................................................ 27

7. SPRING BOOT – SPRING BEANS AND DEPENDENCY INJECTION ............................................. 28

8. SPRING BOOT – RUNNERS ..................................................................................................... 29

Application Runner ................................................................................................................................. 29

Command Line Runner ............................................................................................................................ 30

9. SPRING BOOT – APPLICATION PROPERTIES ........................................................................... 31

Command Line Properties ....................................................................................................................... 31

Properties File ......................................................................................................................................... 31

YAML File ................................................................................................................................................ 31

Externalized Properties ........................................................................................................................... 32

Use of @Value Annotation ..................................................................................................................... 32

iii
Spring Boot

Spring Boot Active Profile ....................................................................................................................... 33

10. SPRING BOOT – LOGGING ................................................................................................... 37

Log Format .............................................................................................................................................. 37

Console Log Output................................................................................................................................. 37

File Log Output ....................................................................................................................................... 37

Log Levels ............................................................................................................................................... 38

Configure Logback................................................................................................................................... 38

11. SPRING BOOT – BUILDING RESTFUL WEB SERVICES ............................................................ 41

Rest Controller ........................................................................................................................................ 43

Request Mapping .................................................................................................................................... 43

Request Body .......................................................................................................................................... 44

Path Variable .......................................................................................................................................... 44

Request Parameter ................................................................................................................................. 44

GET API ................................................................................................................................................... 44

POST API ................................................................................................................................................. 46

PUT API ................................................................................................................................................... 47

DELETE API .............................................................................................................................................. 48

12. SPRING BOOT – EXCEPTION HANDLING ............................................................................. 54

Controller Advice .................................................................................................................................... 54

Exception Handler ................................................................................................................................... 54

13. SPRING BOOT – INTERCEPTOR ............................................................................................ 62

14. SPRING BOOT – SERVLET FILTER.......................................................................................... 71

15. SPRING BOOT – TOMCAT PORT NUMBER ........................................................................... 77

Custom Port ............................................................................................................................................ 77

Random Port ........................................................................................................................................... 77

iv
Spring Boot

16. SPRING BOOT – REST TEMPLATE ......................................................................................... 78

GET ......................................................................................................................................................... 79

POST ....................................................................................................................................................... 80

PUT ......................................................................................................................................................... 81

DELETE .................................................................................................................................................... 82

17. SPRING BOOT – FILE HANDLING .......................................................................................... 89

File Upload .............................................................................................................................................. 89

File Download ......................................................................................................................................... 90

18. SPRING BOOT – SERVICE COMPONENTS ............................................................................. 96

19. SPRING BOOT – THYMELEAF ............................................................................................. 106

Thymeleaf Templates ............................................................................................................................ 106

Web Application ................................................................................................................................... 106

20. SPRING BOOT – CONSUMING RESTFUL WEB SERVICES ..................................................... 113

Angular JS ............................................................................................................................................. 122

21. SPRING BOOT – CORS SUPPORT ........................................................................................ 124

Enable CORS in Controller Method ....................................................................................................... 124

Global CORS Configuration ................................................................................................................... 124

22. SPRING BOOT – INTERNATIONALIZATION ......................................................................... 126

Dependencies ....................................................................................................................................... 126

LocaleResolver ...................................................................................................................................... 126

LocaleChangeInterceptor ...................................................................................................................... 127

Messages Sources ................................................................................................................................. 127

HTML file .............................................................................................................................................. 128

23. SPRING BOOT – SCHEDULING ........................................................................................... 134

Java Cron Expression ............................................................................................................................. 134

v
Spring Boot

Fixed Rate ............................................................................................................................................. 135

Fixed Delay ........................................................................................................................................... 136

24. SPRING BOOT – ENABLING HTTPS ..................................................................................... 138

Self-Signed Certificate ........................................................................................................................... 138

Configure HTTPS ................................................................................................................................... 139

25. SPRING BOOT – EUREKA SERVER ....................................................................................... 140

Building a Eureka Server ....................................................................................................................... 140

26. SPRING BOOT – SERVICE REGISTRATION WITH EUREKA .................................................... 146

27. SPRING BOOT – ZUUL PROXY SERVER AND ROUTING........................................................ 153

Creating Zuul Server Application ........................................................................................................... 153

28. SPRING BOOT – SPRING CLOUD CONFIGURATION SERVER ............................................... 160

Creating Spring Cloud Configuration Server .......................................................................................... 160

29. SPRING BOOT – SPRING CLOUD CONFIGURATION CLIENT ................................................ 166

Working with Spring Cloud Configuration Server .................................................................................. 166

30. SPRING BOOT – ACTUATOR ............................................................................................... 169

Enabling Spring Boot Actuator .............................................................................................................. 169

31. SPRING BOOT – ADMIN SERVER ........................................................................................ 171

32. SPRING BOOT – ADMIN CLIENT ......................................................................................... 176

33. SPRING BOOT – ENABLING SWAGGER2............................................................................. 179

34. SPRING BOOT – CREATING DOCKER IMAGE ...................................................................... 186

Create Dockerfile .................................................................................................................................. 186

Maven................................................................................................................................................... 186

Gradle ................................................................................................................................................... 190

35. SPRING BOOT – TRACING MICRO SERVICE LOGS ............................................................... 194

vi
Spring Boot

Spring Cloud Sleuth ............................................................................................................................... 194

Zipkin Server ......................................................................................................................................... 199

36. SPRING BOOT – FLYWAY DATABASE .................................................................................. 206

Configuring Flyway Database ................................................................................................................ 206

37. SPRING BOOT – SENDING EMAIL ....................................................................................... 213

38. SPRING BOOT – HYSTRIX ................................................................................................... 219

39. SPRING BOOT – WEB SOCKET............................................................................................ 226

40. SPRING BOOT – BATCH SERVICE........................................................................................ 235

41. SPRING BOOT – SPRING FOR APACHE KAFKA .................................................................... 244

Producing Messages ............................................................................................................................. 244

Consuming a Message ........................................................................................................................... 245

42. SPRING BOOT – TWILIO..................................................................................................... 252

Sending SMS ......................................................................................................................................... 252

Voice Calls ............................................................................................................................................. 257

43. SPRING BOOT – UNIT TEST CASES ..................................................................................... 262

Mockito ................................................................................................................................................ 262

44. SPRING BOOT – REST CONTROLLER UNIT TEST ................................................................. 269

Writing a Unit Test for REST Controller ................................................................................................. 269

45. SPRING BOOT – DATABASE HANDLING ............................................................................. 276

Connect to H2 database ........................................................................................................................ 276

Connect MySQL..................................................................................................................................... 277

Connect Redis ....................................................................................................................................... 279

JDBCTemplate ....................................................................................................................................... 280

Multiple DataSource ............................................................................................................................. 280

vii
Spring Boot

46. SPRING BOOT – SECURING WEB APPLICATIONS ................................................................ 284

Securing a Web application ................................................................................................................... 284

47. SPRING BOOT SECURITY – OAUTH2 WITH JWT ................................................................. 294

Authorization Server ............................................................................................................................. 294

Resource Server .................................................................................................................................... 294

OAuth2 ................................................................................................................................................. 294

JWT Token ............................................................................................................................................ 294

48. SPRING BOOT – GOOGLE CLOUD PLATFORM .................................................................... 311

Google Cloud SQL .................................................................................................................................. 314

49. SPRING BOOT – GOOGLE OAUTH2 SIGN-IN ....................................................................... 316

viii
1. Spring Boot – Introduction Spring Boot

Spring Boot is an open source Java-based framework used to create a micro Service. It is
developed by Pivotal Team and is used to build stand-alone and production ready spring
applications. This chapter will give you an introduction to Spring Boot and familiarizes you
with its basic concepts.

What is Micro Service?


Micro Service is an architecture that allows the developers to develop and deploy services
independently. Each service running has its own process and this achieves the lightweight
model to support business applications.

Advantages
Micro services offers the following advantages to its developers:

 Easy deployment
 Simple scalability
 Compatible with Containers
 Minimum configuration
 Lesser production time

What is Spring Boot?


Spring Boot provides a good platform for Java developers to develop a stand-alone and
production-grade spring application that you can just run. You can get started with
minimum configurations without the need for an entire Spring configuration setup.

Advantages
Spring Boot offers the following advantages to its developers:

 Easy to understand and develop spring applications


 Increases productivity
 Reduces the development time

Goals
Spring Boot is designed with the following goals:

 To avoid complex XML configuration in Spring


 To develop a production ready Spring applications in an easier way
 To reduce the development time and run the application independently
 Offer an easier way of getting started with the application

1
Spring Boot

Why Spring Boot?


You can choose Spring Boot because of the features and benefits it offers as given here:

 It provides a flexible way to configure Java Beans, XML configurations, and Database
Transactions.
 It provides a powerful batch processing and manages REST endpoints.
 In Spring Boot, everything is auto configured; no manual configurations are needed.
 It offers annotation-based spring application
 Eases dependency management
 It includes Embedded Servlet Container

How does it work?


Spring Boot automatically configures your application based on the dependencies you have
added to the project by using @EnableAutoConfiguration annotation. For example, if
MySQL database is on your classpath, but you have not configured any database
connection, then Spring Boot auto-configures an in-memory database.

The entry point of the spring boot application is the class contains
@SpringBootApplication annotation and the main method.

Spring Boot automatically scans all the components included in the project by using
@ComponentScan annotation.

Spring Boot Starters


Handling dependency management is a difficult task for big projects. Spring Boot resolves
this problem by providing a set of dependencies for developers convenience.

For example, if you want to use Spring and JPA for database access, it is sufficient if you
include spring-boot-starter-data-jpa dependency in your project.

Note that all Spring Boot starters follow the same naming pattern spring-boot-starter-
*, where * indicates that it is a type of the application.

Examples
Look at the following Spring Boot starters explained below for a better understanding:

Spring Boot Starter Actuator dependency is used to monitor and manage your
application. Its code is shown below:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

2
Spring Boot

Spring Boot Starter Security dependency is used for Spring Security. Its code is shown
below:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>

Spring Boot Starter web dependency is used to write a Rest Endpoints. Its code is
shown below:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

Spring Boot Starter Thyme Leaf dependency is used to create a web application. Its
code is shown below:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>

Spring Boot Starter Test dependency is used for writing Test cases. Its code is shown
below:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>

Auto Configuration
Spring Boot Auto Configuration automatically configures your Spring application based on
the JAR dependencies you added in the project. For example, if MySQL database is on your
class path, but you have not configured any database connection, then Spring Boot auto-
configures an in-memory database.

For this purpose, you need to add @EnableAutoConfiguration annotation or


@SpringBootApplication annotation to your main class file. Then, your Spring Boot
application will be automatically configured.

3
Spring Boot

Observe the following code for a better understanding:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

@EnableAutoConfiguration
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

Spring Boot Application


The entry point of the Spring Boot Application is the class contains
@SpringBootApplication annotation. This class should have the main method to run the
Spring Boot application. @SpringBootApplication annotation includes Auto-
Configuration, Component Scan, and Spring Boot Configuration.

If you added @SpringBootApplication annotation to the class, you do not need to add
the @EnableAutoConfiguration, @ComponentScan and @SpringBootConfiguration
annotation. The @SpringBootApplication annotation includes all other annotations.

Observe the following code for a better understanding:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

Component Scan
Spring Boot application scans all the beans and package declarations when the application
initializes. You need to add the @ComponentScan annotation for your class file to scan
your components added in your project.

Observe the following code for a better understanding:

import org.springframework.boot.SpringApplication;

4
Spring Boot

import org.springframework.context.annotation.ComponentScan;

@ComponentScan
public class DemoApplication {

public static void main(String[] args) {


SpringApplication.run(DemoApplication.class, args);
}
}

5
2. Spring Boot – Quick Start Spring Boot

This chapter will teach you how to create a Spring Boot application using Maven and
Gradle.

Prerequisites
Your system need to have the following minimum requirements to create a Spring Boot
application:

 Java 7
 Maven 3.2
 Gradle 2.5

Spring Boot CLI


The Spring Boot CLI is a command line tool and it allows us to run the Groovy scripts. This
is the easiest way to create a Spring Boot application by using the Spring Boot Command
Line Interface. You can create, run and test the application in command prompt itself.

This section explains you the steps involved in manual installation of Spring Boot CLI . For
further help, you can use the following link: https://docs.spring.io/spring-
boot/docs/current-SNAPSHOT/reference/htmlsingle/#getting-started-installing-spring-
boot

You can also download the Spring CLI distribution from the Spring Software repository at:
https://docs.spring.io/spring-boot/docs/current-
SNAPSHOT/reference/htmlsingle/#getting-started-manual-cli-installation

For manual installation, you need to use the following two folders:

 spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin.zip
 spring-boot-cli-2.0.0.BUILD-SNAPSHOT-bin.tar.gz

After the download, unpack the archive file and follow the steps given in the install.txt file.
Not that it does not require any environment setup.

In Windows, go to the Spring Boot CLI bin directory in the command prompt and run the
command spring –-version to make sure spring CLI is installed correctly. After executing
the command, you can see the spring CLI version as shown below:

6
Spring Boot

Run Hello World with Groovy


Create a simple groovy file which contains the Rest Endpoint script and run the groovy file
with spring boot CLI. Observe the code shown here for this purpose:

@Controller
class Example {
@RequestMapping("/")
@ResponseBody
public String hello() {
"Hello Spring Boot"
}
}

Now, save the groovy file with the name hello.groovy. Note that in this example, we
saved the groovy file inside the Spring Boot CLI bin directory. Now run the application by
using the command spring run hello.groovy as shown in the screenshot given below:

Once you run the groovy file, required dependencies will download automatically and it
will start the application in Tomcat 8080 port as shown in the screenshot given below:

Once Tomcat starts, go to the web browser and hit the URL http://localhost:8080/,
and you can see the output as shown.

7
3. Spring Boot – Bootstrapping Spring Boot

This chapter will explain you how to perform bootstrapping on a Spring Boot application.

Spring Initializer
One of the ways to Bootstrapping a Spring Boot application is by using Spring Initializer.
To do this, you will have to visit the Spring Initializer web page http://start.spring.io/ and
choose your Build, Spring Boot Version and platform. Also, you need to provide a Group,
Artifact and required dependencies to run the application.

Observe the following screenshot that shows an example where we added the spring-
boot-starter-web dependency to write REST Endpoints.

Once you provided the Group, Artifact, Dependencies, Build Project, Platform and Version,
click Generate Project button. The zip file will download and the files will be extracted.

This section explains you the examples by using both Maven and Gradle.

8
Spring Boot

Maven
After you download the project, unzip the file. Now, your pom.xml file looks as shown
below:

<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.tutorialspoint</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>

<name>demo</name>
<description>Demo project for Spring Boot</description>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-
8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>

9
Spring Boot

</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>

Gradle
Once you download the project, unzip the file. Now your build.gradle file looks as shown
below:

buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-
plugin:${springBootVersion}")
}
}
apply plugin: 'java'

apply plugin: 'eclipse'

10
Spring Boot

apply plugin: 'org.springframework.boot'

group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8

repositories {
mavenCentral()
}

dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}

Class Path Dependencies


Spring Boot provides a number of Starters to add the jars in our class path. For example,
for writing a Rest Endpoint, we need to add the spring-boot-starter-web dependency
in our class path. Observe the codes shown below for a better understanding:

Maven dependency

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

Gradle dependency

dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
}

11
Spring Boot

Main Method
The main method should be writing the Spring Boot Application class. This class should be
annotated with @SpringBootApplication. This is the entry point of the spring boot
application to start. You can find the main class file under src/java/main directories with
the default package.

In this example, the main class file is located at the src/java/main directories with the
default package com.tutorialspoint.demo. Observe the code shown here for a better
understanding:

package com.tutorialspoint.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

Write a Rest Endpoint


To write a simple Hello World Rest Endpoint in the Spring Boot Application main class file
itself, follow the steps shown below:

 Firstly, add the @RestController annotation at the top of the class.


 Now, write a Request URI method with @RequestMapping annotation.
 Then, the Request URI method should return the Hello World string.
Now, your main Spring Boot Application class file will look like as shown in the code given
below:

package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class DemoApplication {

12
Spring Boot

public static void main(String[] args) {


SpringApplication.run(DemoApplication.class, args);
}

@RequestMapping(value="/")
public String hello() {
return "Hello World";
}
}

Create an Executable JAR


Let us create an executable JAR file to run the Spring Boot application by using Maven and
Gradle commands in the command prompt as shown below:

Use the Maven command mvn clean install as shown below:

After executing the command, you can see the BUILD SUCCESS message at the
command prompt as shown below:

Use the Gradle command gradle clean build as shown below:

13
Spring Boot

After executing the command, you can see the BUILD SUCCESSFUL message in the
command prompt as shown below:

Run Hello World with Java


Once you have created an executable JAR file, you can find it under the following
directories.

For Maven, you can find the JAR file under the target directory as shown below:

14
Spring Boot

For Gradle, you can find the JAR file under the build/libs directory as shown below:

Now, run the JAR file by using the command java –jar <JARFILE>. Observe that in the
above example, the JAR file is named demo-0.0.1-SNAPSHOT.jar

Once you run the jar file, you can see the output in the console window as shown below:

Now, look at the console, Tomcat started on port 8080 (http). Now, go to the web browser
and hit the URL http://localhost:8080/ and you can see the output as shown below:

15
4. Spring Boot – Tomcat Deployment Spring Boot

By using Spring Boot application, we can create a war file to deploy into the web server.
In this chapter, you are going to learn how to create a WAR file and deploy the Spring
Boot application in Tomcat web server.

Spring Boot Servlet Initializer


The traditional way of deployment is making the Spring Boot Application
@SpringBootApplication class extend the SpringBootServletInitializer class. Spring
Boot Servlet Initializer class file allows you to configure the application when it is launched
by using Servlet Container.

The code for Spring Boot Application class file for JAR file deployment is given below:

package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}

We need to extend the class SpringBootServletInitializer to support WAR file


deployment. The code of Spring Boot Application class file is given below:

package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {
@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder
application) {

return application.sources(DemoApplication.class);

16
Spring Boot

public static void main(String[] args) {


SpringApplication.run(DemoApplication.class, args);
}
}

Setting Main Class


In Spring Boot, we need to mention the main class that should start in the build file. For
this purpose, you can use the following pieces of code:

For Maven, add the start class in pom.xml properties as shown below:

<start-class>com.tutorialspoint.demo.DemoApplication</start-class>

For Gradle, add the main class name in build.gradle as shown below:

mainClassName="com.tutorialspoint.demo.DemoApplication"

Update packaging JAR into WAR


We have to update the packaging JAR into WAR using the following pieces of code:

For Maven, add the packaging as WAR in pom.xml as shown below:

<packaging>war</packaging>

For Gradle, add the application plugin and war plugin in the build.gradle as shown below:

apply plugin: ‘war’


apply plugin: ‘application’

Now, let us write a simple Rest Endpoint to return the string “Hello World from Tomcat”.
To write a Rest Endpoint, we need to add the Spring Boot web starter dependency into
our build file.

For Maven, add the Spring Boot starter dependency in pom.xml using the code as shown
below:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

17
Spring Boot

For Gradle, add the Spring Boot starter dependency in build.gradle using the code as
shown below:

dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
}

Now, write a simple Rest Endpoint in Spring Boot Application class file using the code as
shown below:

package com.tutorialspoint.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class DemoApplication extends SpringBootServletInitializer {

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder
application) {
return application.sources(DemoApplication.class);
}

public static void main(String[] args) {


SpringApplication.run(DemoApplication.class, args);
}

@RequestMapping(value="/")
public String hello() {
return "Hello World from Tomcat";
}
}

18
Spring Boot

Packaging your Application


Now, create a WAR file to deploy into the Tomcat server by using Maven and Gradle
commands for packaging your application as given below:

For Maven, use the command mvn package for packaging your application. Then, the
WAR file will be created and you can find it in the target directory as shown in the
screenshots given below:

For Gradle, use the command gradle clean build for packaging your application. Then,
your WAR file will be created and you can find it under build/libs directory. Observe the
screenshots given here for a better understanding:

19
Spring Boot

Deploy into Tomcat


Now, run the Tomcat Server, and deploy the WAR file under the webapps directory.
Observe the screenshots shown here for a better understanding:

20
Spring Boot

After successful deployment, hit the URL in your web browser http://localhost:8080/demo-
0.0.1-SNAPSHOT/ and observe that the output will look as shown in the screenshot given
below:

The full code for this purpose is given below.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.tutorialspoint</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>

<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-
8</project.reporting.outputEncoding>
<java.version>1.8</java.version>

21
Spring Boot

<start-class>com.tutorialspoint.demo.DemoApplication</start-class>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>

build.gradle

buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {

22
Spring Boot

classpath("org.springframework.boot:spring-boot-gradle-
plugin:${springBootVersion}")

}
}

apply plugin: 'java'


apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'war'
apply plugin: 'application'

group = 'com.tutorialspoint'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
mainClassName="com.tutorialspoint.demo.DemoApplication"
repositories {
mavenCentral()
}

dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
testCompile('org.springframework.boot:spring-boot-starter-test')
}

The code for main Spring Boot application class file is given below:

package com.tutorialspoint.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class DemoApplication extends SpringBootServletInitializer {

23
Spring Boot

@Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder
application) {
return application.sources(DemoApplication.class);
}

public static void main(String[] args) {


SpringApplication.run(DemoApplication.class, args);
}

@RequestMapping(value="/")
public String hello() {
return "Hello World from Tomcat";
}
}

24
5. Spring Boot – Build Systems Spring Boot

In Spring Boot, choosing a build system is an important task. We recommend Maven or


Gradle as they provide a good support for dependency management. Spring does not
support well other build systems.

Dependency Management
Spring Boot team provides a list of dependencies to support the Spring Boot version for
its every release. You do not need to provide a version for dependencies in the build
configuration file. Spring Boot automatically configures the dependencies version based
on the release. Remember that when you upgrade the Spring Boot version, dependencies
also will upgrade automatically.

Note: If you want to specify the version for dependency, you can specify it in your
configuration file. However, the Spring Boot team highly recommends that it is not needed
to specify the version for dependency.

Maven Dependency
For Maven configuration, we should inherit the Spring Boot Starter parent project to
manage the Spring Boot Starters dependencies. For this, simply we can inherit the starter
parent in our pom.xml file as shown below.

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
</parent>

We should specify the version number for Spring Boot Parent Starter dependency. Then
for other starter dependencies, we do not need to specify the Spring Boot version number.
Observe the code given below:

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>

25
Spring Boot

Gradle Dependency
We can import the Spring Boot Starters dependencies directly into build.gradle file. We
do not need Spring Boot start Parent dependency like Maven for Gradle. Observe the code
given below:

buildscript {
ext {
springBootVersion = '1.5.8.RELEASE'
}
repositories {
mavenCentral()
}
dependencies {
classpath("org.springframework.boot:spring-boot-gradle-
plugin:${springBootVersion}")
}
}

Similarly, in Gradle, we need not specify the Spring Boot version number for dependencies.
Spring Boot automatically configures the dependency based on the version.

dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
}

26
6. Spring Boot – Code Structure Spring Boot

Spring Boot does not have any code layout to work with. However, there are some best
practices that will help us. This chapter talks about them in detail.

Default package
A class that does not have any package declaration is considered as a default package.
Note that generally a default package declaration is not recommended. Spring Boot will
cause issues such as malfunctioning of Auto Configuration or Component Scan, when you
use default package.

Note: Java’s recommended naming convention for package declaration is reversed domain
name. For example: com.tutorialspoint.myproject

Typical Layout
The typical layout of Spring Boot application is shown in the image given below:

The Application.java file should declare the main method along with
@SpringBootApplication. Observe the code given below for a better understanding:

package com.tutorialspoint.myproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args); }}

27
7. Spring Boot – Spring Beans and Dependency Spring Boot

Injection

In Spring Boot, we can use Spring Framework to define our beans and their dependency
injection. The @ComponentScan annotation is used to find beans and the corresponding
injected with @Autowired annotation.

If you followed the Spring Boot typical layout, no need to specify any arguments for
@ComponentScan annotation. All component class files are automatically registered with
Spring Beans.

The following example provides an idea about Auto wiring the Rest Template object and
creating a Bean for the same:

@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate();
}

The following code shows the code for auto wired Rest Template object and Bean creation
object in main Spring Boot Application class file:

package com.tutorialspoint.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;
@SpringBootApplication
public class DemoApplication {
@Autowired
RestTemplate restTemplate;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public RestTemplate getRestTemplate() {
return new RestTemplate(); }
}

28
8. Spring Boot – Runners Spring Boot

Application Runner and Command Line Runner interfaces lets you to execute the code
after the Spring Boot application is started. You can use these interfaces to perform any
actions immediately after the application has started. This chapter talks about them in
detail.

Application Runner
Application Runner is an interface used to execute the code after the Spring Boot
application started. The example given below shows how to implement the Application
Runner interface on the main class file.

package com.tutorialspoint.demo;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication implements ApplicationRunner {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(ApplicationArguments arg0) throws Exception {
System.out.println("Hello World from Application Runner");
}
}

Now, if you observe the console window below Hello World from Application Runner,
the println statement is executed after the Tomcat started. Is the following screenshot
relevant?

29
Spring Boot

Command Line Runner


Command Line Runner is an interface. It is used to execute the code after the Spring Boot
application started. The example given below shows how to implement the Command Line
Runner interface on the main class file.

package com.tutorialspoint.demo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication implements CommandLineRunner {

public static void main(String[] args) {


SpringApplication.run(DemoApplication.class, args);
}
@Override
public void run(String... arg0) throws Exception {
System.out.println("Hello world from Command Line Runner");
}
}

Look at the console window below “Hello world from Command Line Runner” println
statement is executed after the Tomcat started.

30
9. Spring Boot – Application Properties Spring Boot

Application Properties support us to work in different environments. In this chapter, you


are going to learn how to configure and specify the properties to a Spring Boot application.

Command Line Properties


Spring Boot application converts the command line properties into Spring Boot
Environment properties. Command line properties take precedence over the other
property sources. By default, Spring Boot uses the 8080 port number to start the Tomcat.
Let us learn how change the port number by using command line properties.

Step 1: After creating an executable JAR file, run it by using the command java –jar
<JARFILE>.

Step 2: Use the command given in the screenshot given below to change the port number
for Spring Boot application by using command line properties.

Note: You can provide more than one application properties by using the delimiter --.

Properties File
Properties files are used to keep ‘N’ number of properties in a single file to run the
application in a different environment. In Spring Boot, properties are kept in the
application.properties file under the classpath.

The application.properties file is located in the src/main/resources directory. The code


for sample application.properties file is given below:

server.port=9090
spring.application.name=demoservice

Note that in the code shown above the Spring Boot application demoservice starts on the
port 9090.

YAML File
Spring Boot supports YAML based properties configurations to run the application. Instead
of application.properties, we can use application.yml file. This YAML file also should
be kept inside the classpath. The sample application.yml file is given below:

31
Spring Boot

spring:
application:
name: demoservice
server:
port: 9090

Externalized Properties
Instead of keeping the properties file under classpath, we can keep the properties in
different location or path. While running the JAR file, we can specify the properties file
path. You can use the following command to specify the location of properties file while
running the JAR:

-Dspring.config.location=C:\application.properties

Use of @Value Annotation


The @Value annotation is used to read the environment or application property value in
Java code. The syntax to read the property value is shown below:

@Value("${property_key_name}")

Look at the following example that shows the syntax to read the
spring.application.name property value in Java variable by using @Value annotation.

@Value("${spring.application.name}")

Observe the code given below for a better understanding:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class DemoApplication {

@Value("${spring.application.name}")

32
Spring Boot

private String name;


public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}

@RequestMapping(value="/")
public String name() {
return name;
}

Note: If the property is not found while running the application, Spring Boot throws the
Illegal Argument exception as Could not resolve placeholder
'spring.application.name' in value "${spring.application.name}".

To resolve the placeholder issue, we can set the default value for the property using thr
syntax given below:

@Value("${property_key_name:default_value}")
@Value("${spring.application.name:demoservice}")

Spring Boot Active Profile


Spring Boot supports different properties based on the Spring active profile. For example,
we can keep two separate files for development and production to run the Spring Boot
application.

Spring active profile in application.properties


Let us understand how to have Spring active profile in application.properties. By default,
application. properties will be used to run the Spring Boot application. If you want to use
profile based properties, we can keep separate properties file for each profile as shown
below:

application.properties

server.port=8080
spring.application.name=demoservice

application-dev.properties

server.port=9090
spring.application.name=demoservice

33
Spring Boot

application-prod.properties

server.port=4431
spring.application.name=demoservice

While running the JAR file, we need to specify the spring active profile based on each
properties file. By default, Spring Boot application uses the application.properties file. The
command to set the spring active profile is shown below:

You can see active profile name on the console log as shown below:

2017-11-26 08:13:16.322 INFO 14028 --- [ main]


com.tutorialspoint.demo.DemoApplication : The following profiles are active:
dev

Now, Tomcat has started on the port 9090 (http) as shown below:

2017-11-26 08:13:20.185 INFO 14028 --- [ main]


s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 9090
(http)

You can set the Production active profile as shown below:

You can see active profile name on the console log as shown below:

2017-11-26 08:13:16.322 INFO 14028 --- [ main]


com.tutorialspoint.demo.DemoApplication : The following profiles are active:
prod

Now, Tomcat started on the port 4431 (http) as shown below:

2017-11-26 08:13:20.185 INFO 14028 --- [ main]


s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 4431
(http)

Spring active profile for application.yml


Let us understand how to keep Spring active profile for application.yml. We can keep the
Spring active profile properties in the single application.yml file. No need to use the
separate file like application.properties.

The following is an example code to keep the Spring active profiles in application.yml file.
Note that the delimiter (---) is used to separate each profile in application.yml file.

34
Spring Boot

spring:
application:
name: demoservice
server:
port: 8080

---
spring:
profiles: dev
application:
name: demoservice
server:
port: 9090

---
spring:
profiles: prod
application:
name: demoservice
server:
port: 4431

To command to set development active profile is given below:

You can see active profile name on the console log as shown below:

2017-11-26 08:41:37.202 INFO 14104 --- [ main]


com.tutorialspoint.demo.DemoApplication : The following profiles are active:
dev

Now, Tomcat started on the port 9090 (http) as shown below:

2017-11-26 08:41:46.650 INFO 14104 --- [ main]


s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 9090
(http)

35
Spring Boot

The command to set Production active profile is given below:

You can see active profile name on the console log as shown below:

2017-11-26 08:43:10.743 INFO 13400 --- [ main]


com.tutorialspoint.demo.DemoApplication : The following profiles are active:
prod

This will start Tomcat on the port 4431 (http) as shown below:

2017-11-26 08:43:14.473 INFO 13400 --- [ main]


s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 4431
(http)

36
10. Spring Boot – Logging Spring Boot

Spring Boot uses Apache Commons logging for all internal logging. Spring Boot’s default
configurations provides a support for the use of Java Util Logging, Log4j2, and Logback.
Using these, we can configure the console logging as well as file logging.

If you are using Spring Boot Starters, Logback will provide a good support for logging.
Besides, Logback also provides a use of good support for Common Logging, Util Logging,
Log4J, and SLF4J.

Log Format
The default Spring Boot Log format is shown in the screenshot given below.

which gives you the following information:

 Date and Time that gives the date and time of the log
 Log level shows INFO, ERROR or WARN
 Process ID

 The --- which is a separator


 Thread name is enclosed within the square brackets []
 Logger Name that shows the Source class name
 The Log message

Console Log Output


The default log messages will print to the console window. By default, “INFO”, “ERROR”
and “WARN” log messages will print in the log file.

If you have to enable the debug level log, add the debug flag on starting your application
using the command shown below:

java –jar demo.jar --debug

You can also add the debug mode to your application.properties file as shown here:

debug=true

File Log Output


By default, all logs will print on the console window and not in the files. If you want to
print the logs in a file, you need to set the property logging.file or logging.path in the
application.properties file.

37
Spring Boot

You can specify the log file path using the property shown below. Note that the log file
name is spring.log.

logging.path=/var/tmp/

You can specify the own log file name using the property shown below:

logging.file=/var/tmp/mylog.log

Note: Log files will rotate automatically after reaching the size 10 MB.

Log Levels
Spring Boot supports all logger levels such as “TRACE”, “DEBUG”, “INFO”, “WARN”,
“ERROR”, “FATAL”, “OFF”. You can define Root logger in the application.properties file as
shown below:

logging.level.root=WARN

Note: Logback does not support “FATAL” level log. It is mapped to the “ERROR” level log.

Configure Logback
Logback supports XML based configuration to handle Spring Boot Log configurations.
Logging configuration details are configured in logback.xml file. The logback.xml file
should be placed under the classpath.

You can configure the ROOT level log in Logback.xml file using the code given below:

<?xml version="1.0" encoding="UTF-8"?>


<configuration>
<root level="INFO">
</root>
</configuration>

You can configure the console appender in Logback.xml file given below.

<?xml version="1.0" encoding="UTF-8"?>


<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
</appender>
<root level="INFO">
<appender-ref ref="STDOUT"/>
</root>
</configuration>

You can configure the file appender in Logback.xml file using the code given below. Note
that you need to specify the Log file path insider the file appender.

38
Spring Boot

<?xml version="1.0" encoding="UTF-8"?>


<configuration>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<File>/var/tmp/mylog.log</File>
</appender>
<root level="INFO">
<appender-ref ref="FILE"/>
</root>
</configuration>

You can define the Log pattern in logback.xml file using the code given below. You can
also define the set of supported log patterns inside the console or file log appender using
the code given below:

<pattern>[%d{yyyy-MM-dd'T'HH:mm:ss.sss'Z'}] [%C] [%t] [%L] [%-5p]


%m%n</pattern>

The code for complete logback.xml file is given below. You have to place this in the class
path.

<?xml version="1.0" encoding="UTF-8"?>


<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>[%d{yyyy-MM-dd'T'HH:mm:ss.sss'Z'}] [%C] [%t] [%L] [%-5p]
%m%n</pattern>
</encoder>
</appender>
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
<File>/var/tmp/mylog.log</File>
<encoder>
<pattern>[%d{yyyy-MM-dd'T'HH:mm:ss.sss'Z'}] [%C] [%t] [%L] [%-5p]
%m%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="FILE"/>
<appender-ref ref="STDOUT"/>
</root>
</configuration>

39
Spring Boot

The code given below shows how to add the slf4j logger in Spring Boot main class file.

package com.tutorialspoint.demo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DemoApplication {
private static final Logger logger =
LoggerFactory.getLogger(DemoApplication.class);
public static void main(String[] args) {
logger.info("this is a info message");
logger.warn("this is a warn message");
logger.error("this is a error message");
SpringApplication.run(DemoApplication.class, args);
}
}

The output that you can see in the console window is shown here:

The output that you can see in the log file is shown here:

40
11. Spring Boot – Building RESTful Web Services Spring Boot

Spring Boot provides a very good support to building RESTful Web Services for enterprise
applications. This chapter will explain in detail about building RESTful web services using
Spring Boot.

Note: For building a RESTful Web Services, we need to add the Spring Boot Starter Web
dependency into the build configuration file.

If you are a Maven user, use the following code to add the below dependency in your
pom.xml file:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

If you are a Gradle user, use the following code to add the below dependency in your
build.gradle file.

compile('org.springframework.boot:spring-boot-starter-web')

The code for complete build configuration file Maven build – pom.xml is given below:

<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath/>

41
Random documents with unrelated
content Scribd suggests to you:
The two Sioux watched the Pawnees until a bend in the 118
valley hid them from view. Angry Wolf started to crawl
away, but Little Eagle touched his arm to stop him. It
wasn’t long until a party of Pawnee warriors rode into
sight. Angry Wolf turned an admiring glance on Little
Eagle.

“How did you know a party of warriors would follow


those two Pawnee scouts?” he asked.

“You told me that was the way Pawnees followed a


trail,” Little Eagle reminded him. “It is because you are
so tired that you didn’t think of it,” he added. “Go back
and sleep while I watch.”

Angry Wolf obeyed without protesting. Little Eagle kept


his eyes on the bend in the valley where the Pawnees
had disappeared. Little Eagle smiled to himself as he
thought how surprised the Pawnee scouts would be
when they reached the beaver dam and couldn’t find
their enemies’ trail. He and Angry Wolf had certainly
made a crooked trail.

The warm sun had wiped away the frost and dried the 119
grass. For a while its heat made Little Eagle drowsy.
Now some clouds rolled up and hid the sun. The wind
was rising and it had a chilly edge. Little Eagle raised his
eyes to study the clouds. He saw that it wouldn’t be
long before rain started to fall.

His attention was drawn back to the trail by the faint


drumming sound made by the hoofs of fast-running
horses. The sound rapidly became plainer. Little Eagle
picked up a small stone and tossed it back over his
shoulder.
By the time Angry Wolf had crawled to Little Eagle’s
side, the Pawnees were flying back down the trail.
Three riderless horses raced ahead of the warriors. Little
Eagle saw that the Pawnees were whipping their horses,
trying to get them to go still faster. When he saw the
big band of Crows come into sight around the bend, he
understood why the Pawnees were fleeing.

There must have been fifty warriors in that band of


pursuing Crows. The Crows were lashing their ponies as
furiously as were the Pawnees. Three or four Crows
were outdistancing the rest of the pursuers and drawing
closer to the Pawnees.

Most of the Pawnees leaned low over their horses’ 120


necks. One, at the rear of the group, suddenly
straightened up. He half turned and, seemingly without
taking aim, let an arrow fly. The leading Crow dropped
from his horse as though he had been jerked off by an
invisible, giant hand.

The other Crows pulled their horses to a stop around


the fallen man. They hesitated for only a moment
before they raced on, but it was long enough to allow
the Pawnees to gain a considerable distance.

Little Eagle and Angry Wolf watched the chase until


both parties were out of sight. They continued to watch
the fallen Crow where his companions had left him, with
his horse grazing a few paces away. The sun was almost
down when the party of Crows returned. They weren’t
leading any riderless ponies so it was plain that the
Pawnees had escaped. The Crows stopped and picked
up the slain warrior. They laid him across the back of his
own horse and slowly rode out of sight.
“That is a lesson we must remember,” Little Eagle said. 121
“The Pawnees were so anxious to catch us that they
forgot to watch for other dangers.”

“But they did kill a Crow,” Angry Wolf replied.

“There were three Pawnee horses without riders,” Little


Eagle reminded him.

“It was a high price to pay for one enemy,” Angry Wolf
agreed.

Both boys were silent for a while. Little Eagle’s thoughts


were following the band of Crows. It could have been
the same band which had planned to attack their camp.

“The Crows have powerful medicine.” Angry Wolf spoke


almost as if his thoughts were following those of Little
Eagle. “It is fortunate that we were able to get horses
from the Pawnees. If we had tried to take horses from
the Crows, we would have failed again.”

Little Eagle turned Angry Wolf’s words over in his mind.


It was true that fortune had seemed to be with the
Crows. They hadn’t been punished for the treachery
they had planned against the Sioux. Even though he
and Angry Wolf had kept the Crow plan from
succeeding, it was still an almost-victory for the Crows.

“The Crows should be punished,” Little Eagle said 122


angrily.

Angry Wolf nodded. He rubbed his hand along the side


of his head where the Crow arrow had struck him.

“They will be,” he answered. “With the horses we have,


we can reach the winter camp. Next spring a war party
will be sent to punish the Crows.”

Next spring seemed far away to Little Eagle. In his mind


he could picture the party of Crows sitting around their
campfires. They would tell of how they had tricked the
Sioux chiefs. While they hadn’t succeeded in making an
attack, they had forced the Sioux to run. Now they had
won a victory over the Pawnees too. Truly there would
be boasting around the Crow campfires this winter.

“We ought to find a better place to make camp,” Angry


Wolf interrupted Little Eagle’s thoughts. “We will want
shelter against this rain.”

Little Eagle had been so wrapped in his thoughts that he 123


hadn’t noticed the rain. It was only a sprinkle, but the
heavy clouds in the northwest gave promise of more to
come. Little Eagle arose and went to bring the horses.

He caught the horses and led them to the place where


he had left the deerskin. He rolled their belongings into
a bundle with the deerskin around it. He mounted his
horse and led the other to Angry Wolf.

Little Eagle led the way across the valley to the trail by
which the Pawnees had fled from the Crows. He turned
down the trail in the direction the Pawnees had gone.
He rode across one stream but, at the second, left the
trail and rode to a thick grove of trees.

“We’ll make camp here,” he said.

They turned their horses loose and set to work to build


a shelter. They found a clump of small trees. By lacing
the branches together, they made a sort of lean-to to
protect them from the rain. They found a big pile of
leaves and dug into them until they came to dry ones.
These they carried to the shelter to make a bed.

Before they went to sleep, the two boys ate some of the 124
cooked meat.

“In the morning we’ll have fresh meat,” Angry Wolf


vowed.

125
CHAPTER SIX

When Little Eagle awoke the next morning, he was


surprised to find the ground covered with a light blanket
of snow.

“Old-man-of-the-north sent snow early,” Angry Wolf


said, as he crawled out of the shelter.

“It isn’t much,” Little Eagle pointed out.

“It’s enough to be a warning to us,” Angry Wolf


answered. “Old-man-of-the-north sent it to warn us that
we should hurry to the winter camp.”

“Maybe he sent it to tell us that he would send more to 126


cover our tracks, if we take horses from the Crows,”
Little Eagle suggested.

Angry Wolf looked at him questioningly. Little Eagle


wondered if that was fear he saw in his friend’s eyes.
Since he had been wounded by the Crows, Angry Wolf
had acted strangely every time the Crows were
mentioned.

“If I can lead him in a successful raid against the Crows,


he will be as brave as he has always been,” Little Eagle
thought to himself, but he said nothing more to Angry
Wolf.
“I’ll try to get fresh meat while you build a fire,” Angry
Wolf offered.

Little Eagle watched as Angry Wolf left camp. It was


surprising how much better Angry Wolf had become in
the last two days. He seemed as strong as he had ever
been. It was hard to believe that less than a moon ago
he had been seriously wounded.

By the time Little Eagle had a cheerful fire going, Angry


Wolf returned to camp with an antelope on his shoulder.

“Hunting is good,” Angry Wolf said, with a pleased 127


smile. “This will be food enough until we get a buffalo.”

As soon as they had finished eating, Little Eagle brought


the horses into camp. The sun had risen in a clear sky
and already was melting the snow. Angry Wolf had
made two packages of the meat. One he had wrapped
in the hide of the antelope he had shot and the other in
Little Eagle’s deer hide. He handed one of the packages
to Little Eagle.

Little Eagle led the way. At first the route was up and
down wooded hills, but soon the hills became smaller
and the trees fewer. When they stopped to rest at
midday, Little Eagle could see the open prairie ahead of
them.

“We’re really started for our winter camp now,” Angry


Wolf said cheerfully.

“It will be good to be in camp with the rest of our


people,” Little Eagle replied, trying to forget how
disappointed he was that the Crows would go so long
unpunished.
Several times during the afternoon the two boys sighted 128
small herds of buffaloes. Little Eagle’s mouth watered at
the sight of them. Antelope and deer steaks were good
food, but not so good as buffalo. Every herd of
buffaloes that they sighted lumbered away before the
riders were within bowshot. Little Eagle knew that
although the buffaloes could not see far, their keen
noses quickly caught the scent of enemies. If the wind
had been blowing from the other direction, he and
Angry Wolf would have had a chance to get one of the
animals.

The sun was sliding down behind some clouds in the


west when Little Eagle and Angry Wolf reached a small
stream. There were a few trees along its banks. The
trees would provide shelter and their branches could be
used for fuel.

“Shall I start building a shelter?” Angry Wolf asked.

As Little Eagle looked at the clouds climbing in the


western sky, he thought how much Angry Wolf had
come to depend upon him to make all of the decisions.

“The trees will protect us,” he replied. “With my


deerskin over us, we’ll be dry even if it should snow.”

While Angry Wolf cooked meat for their meal, Little 129
Eagle made a pile of dry leaves for their bed. Both of
them were so tired that as soon as they had eaten they
put out the fire, crawled into the bed of leaves, and
pulled the deerskin over them.

When Little Eagle awoke the next morning, he saw that


the branches of the tree were wet and the ground
around was, too. However, he and Angry Wolf had been
warm and dry in their bed. He was pleased that there
was no snow. Perhaps Old-man-of-the-north would let
them cross the prairie before he blew snow with his icy
breath.

Little Eagle led the way across the open prairie. At


midday he and Angry Wolf stopped for their usual rest.
They had come a long distance that morning, but they
had seen only one clump of trees. While they were
resting, Little Eagle watched a bank of clouds forming in
the northwest.

“Will we be rained on again this afternoon?” Angry Wolf


asked.

“Rain will not matter,” Little Eagle answered uneasily. 130


“To me, the air has a feel as if Old-man-of-the-north’s
cold wind was behind that cloud. It may be a long way
to the next camping place. It would not be good to be
on the prairie if there is much snow.”

Angry Wolf looked doubtfully around the prairie where


they were resting.

“It couldn’t catch us in a much poorer place than this,”


he said.

“That’s true,” Little Eagle agreed. “We’ll keep going.”

When they started again, Little Eagle wondered what


caused his feeling of uneasiness. The air was warmer.
There didn’t seem to be any reason for thinking that
snow would fall. Even when the rain started, Little Eagle
was not too uncomfortable. Later in the afternoon the
rain felt colder. However, when the boys were chilled,
they jumped from their horses and trotted beside them.
As soon as they were warm, they remounted. There
was still some daylight left when they reached a small,
tree-lined stream.

“This is the place for us to camp,” Little Eagle called


cheerfully.

The two boys made camp quickly. As soon as they had 131
a fire going, they built a shelter. It was dark by the time
they had the shelter finished. It was while they were
eating that the drops of rain began to change to flakes
of snow. In a short time the northwest wind was driving
the snow with stinging force.

“It is fortunate that we found this place,” Little Eagle


said. “We may have to stay here several days.”

The next morning it looked as though Little Eagle’s


prediction would come true. The wind was still driving
the snow before it. A drift had buried the boys’ fire and
the pile of wood. They had to scrape the snow from the
wood and work carefully to get dry shavings to start a
new fire. Little Eagle noticed that Angry Wolf was
restless and disturbed because of the delay.

“Old-man-of-the-north may send much snow,” Little


Eagle told him, “but it won’t matter. In a few days much
of it will melt. Then we can travel easily.”

“If Old-man-of-the-north sends one snow, he will send 132


others,” Angry Wolf protested. “We may be caught on
the prairie.”

“This will be the last snow of this moon,” Little Eagle


stated with certainty.

Angry Wolf seemed much encouraged by Little Eagle’s


words. He took his quiver of arrows and began
smoothing some of the arrows. Little Eagle spent his
time rewrapping the hand grip on his bow. About
midday the snow slackened, and soon afterward it
almost stopped. Little Eagle stood up and looked about.
In some places drifts of snow had been piled high. In
others, the ground had been swept almost bare.
Although the wind was cold, rays of sunshine filtered
through the clouds.

“I’m going to see about our horses,” Little Eagle


announced.

“I’ll finish scraping my arrows unless you want me to go


with you,” Angry Wolf decided.

“I’ll go alone,” Little Eagle answered. “They aren’t far


away.”
However, Little Eagle walked a considerable distance 133
from camp without finding a trace of the horses. He
couldn’t even find the trail they had left when they
wandered away. When the sun was getting low in the
western sky, Little Eagle turned back toward camp. On
the way back, he wondered what words he would use to
tell Angry Wolf so that the other boy would not be too
alarmed at the danger of their situation. Little Eagle
didn’t try to hide from himself the fact that they were in
grave danger. Here in the middle of the prairie, with no
horses, they might not be able to get enough game to
keep them alive through the winter.

Oddly enough, Angry Wolf was not greatly disturbed


when Little Eagle announced that he hadn’t been able
to find the horses.

“They probably drifted ahead of the storm,” Angry Wolf


said calmly. “In the morning we’ll both look for them.”

The next morning the two boys left camp together.


When they had gone about a third of the distance Little
Eagle had covered the day before, they halted.

“You’d better go south here,” Little Eagle suggested. “I’ll


go farther east and then I’ll turn south.”

Little Eagle went almost as far east as he had gone 134


yesterday before he turned south. He plodded slowly
through the deep snow. He climbed and crossed many
low hills without finding the horses. As he climbed to
the top of another hill, he decided he would turn back
toward Angry Wolf and search the ground between
them. From the top of the hill Little Eagle could see a
clump of trees below him. It was possible that the
horses were crowded into the shelter of the trees and
were hidden from his sight. He decided to look behind
the trees.

When Little Eagle circled the trees, he saw the tracks of


the horses leading south. He hurried forward to get a
better look at the trail they had left. He saw that the
horses had left the grove while snow was still falling.
Their tracks were partly covered with snow. He stopped
in dismay when he saw that the tracks had been made
by three horses.

Little Eagle made a quick search under the trees. He 135


found where someone had camped during the worst of
the storm. He was not good enough at tracking to read
all of the signs, but he could read enough of them to tell
that someone had been camping here and that the
horses had wandered to the shelter of the trees during
the storm. Whoever had been here had taken the
horses and ridden on while the snow was still falling.

It didn’t take any sign reading for Little Eagle to realize


how great a misfortune had befallen Angry Wolf and
himself. There was no hope that they could get the
horses back. It would be equally hopeless to try to cross
the prairie on foot. They would have to turn back to
where there were more trees. He and Angry Wolf would
have to spend the winter by themselves.

Little Eagle turned west to find Angry Wolf’s trail. When


he reached it, he followed it south. He went as swiftly
as he could go. Angry Wolf glanced back and saw him.
The other boy turned back to meet Little Eagle.

“Where are the horses?” Angry Wolf asked.

“Someone took them,” Little Eagle answered.


As Little Eagle told of the trail he had found, he closely 136
watched Angry Wolf’s face. He saw fear in the other
boy’s eyes, and he tried to make his voice cheerful.

“It was a Crow warrior who took our horses,” Angry


Wolf said hopelessly when Little Eagle had finished.
“The Crows have powerful medicine.”

“We have to get those horses back,” Little Eagle urged.

Little Eagle spoke with a confidence he didn’t feel. He


had no plan for getting the horses, yet he knew he must
say something to encourage Angry Wolf.

“The Crows have powerful medicine,” Angry Wolf


repeated.

“Old-man-of-the-north might send another snow to


keep the Crow in camp until we get our horses back
from him,” Little Eagle suggested.

Angry Wolf glanced around the sky.

“There’ll be no more snow this moon,” he said. “We may


as well return to our camp.”

Without a word, Little Eagle turned back toward their 137


own camp. While Angry Wolf was in this mood, it would
do no good to argue with him. Perhaps when he had
eaten and rested, he would see that their best hope to
escape would be to get their horses back from the
Crow.

As soon as they reached camp, Angry Wolf began to


slice thin pieces of meat and put them on a stick. Little
Eagle saw that Angry Wolf was cooking enough food for
a trip.
“It would be foolish for us to try to cross the prairie on
foot,” he said quietly.

Angry Wolf nodded agreement.

“Our best plan is to return to the camp we had on the


creek,” he said. “I’m preparing extra food in case we
have trouble reaching the place.”

While Little Eagle busied himself with work around the


camp, he turned the problem over in his mind. He knew
Angry Wolf would agree to wait until morning to start
the return trip. In the meantime he had to think of a
plan to get their horses from the Crow. It would have to
be a good plan if it convinced Angry Wolf. Angry Wolf
had said that the Crows had powerful medicine. Yet the
two of them had spoiled the Crow plan to attack the
Sioux camp. Perhaps their own medicine was as strong
as that of the Crows.

Little Eagle sat down a few paces from the fire. He 138
wanted to think more about this problem. He tried to
imagine what advice Clawing Bear would give. When
the answer came, it was almost as if Clawing Bear were
speaking to him. He had the deer hide. It was powerful
medicine. He should take the hide and go away from
camp. If he rolled himself up in the deer hide and slept,
he might have a dream which would tell him what to do.
He told his thoughts to Angry Wolf.

“You have studied under the great medicine man,


Clawing Bear,” Angry Wolf said thoughtfully. “You should
know more about these matters than I. Yet, if you don’t
get a clear dream, we ought to start back to the old
camp at daylight.”
As soon as darkness fell, Little Eagle carried his deer 139
hide to the top of a high hill. He was so far from camp
that he couldn’t see the twinkle of the fire. When he
had thought of the plan, Little Eagle hadn’t thought of
the danger. As he pulled the deer hide over him, he felt
uneasy. He had never had a visit from a spirit. Suppose
he was frightened? It would be a disgrace for a Sioux
boy to show fear.

At first he moved about restlessly. The wind seemed to


creep under the hide and keep him cold. After a time he
had the deer hide arranged so that the wind didn’t get
under it. As soon as he was warm, he grew drowsy. He
had almost fallen asleep when a faint sighing noise
aroused him. He listened tensely. After a few minutes he
realized the sound was made by the wind sifting snow
against the deer hide. He closed his eyes and fell
asleep.

Afterward Little Eagle was never sure whether he woke


up, as he seemed to do, or whether the whole thing
was a dream. At least it was so real that it seemed to
happen. He felt cold. When he opened his eyes he saw
that it was still dark. He realized that the deer hide had
slipped off his shoulder. He reached his hand out to
grasp it and pull it back over his shoulder. He stopped
when a soft voice spoke to him.

“Get up, Little Eagle,” the voice said. “I’ll show you how 140
you can get horses from the Crows. They are my
enemies too.”

Little Eagle sat up. It wasn’t as dark as he had thought.


The eastern sky was beginning to lighten. It wouldn’t be
long until the sun came up. Little Eagle looked around,
but he could see no one. The only living thing near was
a small bird which sat huddled on his deerskin. When
the voice spoke again, Little Eagle saw that it was the
bird speaking.

“The Crows have killed many buffaloes,” the bird said.


“They are gorged with food. It will be easy to take
horses from them.”

Little Eagle scrambled to his feet. He could dash back to


camp and get Angry Wolf. Together they would follow
the bird and get horses. He reached down to pick up
the deer hide to carry it back to camp.

“Put it under that tree,” the bird said, nodding his head
toward a tree in the direction away from the camp. “My
family will use it to build warm nests for the winter
which is almost here.”

Little Eagle folded the skin neatly. The bird flew ahead 141
and perched on a limb while Little Eagle placed the hide
at the foot of the tree. The bird flew off to the west. He
went so quickly that Little Eagle didn’t have time to ask
for permission to get Angry Wolf. He had to run to keep
the bird in sight.

While it didn’t seem that they had traveled long, the sun
was down and darkness had fallen when they reached
the Crow camp. The camp had been set up on the
sheltered side of a grove of trees. The smell of roasting
buffalo meat made Little Eagle’s mouth water. A few
Crows were feasting on the fresh buffalo meat. Little
Eagle knew that most of the band had stuffed
themselves with fresh meat and had crawled into their
tepees to sleep.

The bird flew around the Crow camp, and Little Eagle
followed him. In a short time they came to the herd of
horses. Little Eagle saw the ones that belonged to Angry
Wolf and him. He guessed that the warrior who had
taken them had gone south until the storm stopped and
then had circled to join the Crows in this camp.

“See how easily you can take all the horses you want,” 142
the bird whispered.

Little Eagle looked around. What the bird said was true.
There were no guards. Most of the horses were out of
sight of the camp. Anyone who used reasonable care
could take horses from this herd.

Little Eagle didn’t know what happened after that. He


was chilly and he awoke to find that the deer hide had
slipped from his shoulder. He sat up. The sun was just
rising over the eastern hills. His dream had been so
plain that for a moment he couldn’t believe it had been
a dream.

Little Eagle’s first feeling was of disappointment. It had


been a dream and he didn’t actually have the horses.
The feeling of disappointment passed quickly. He had
heard Clawing Bear tell of the messages that came to a
medicine man in dreams. This was a message for him.
He had learned how he and Angry Wolf could get
horses. He jumped to his feet and raced to camp.

Angry Wolf had already risen. He was cooking more 143


meat at the fire. He looked sad and dejected as Little
Eagle ran into camp.

“You had a message?” he asked doubtfully when he saw


Little Eagle’s excitement.

Little Eagle nodded. Eagerly, he related what had


happened in his dream. When he had finished, he saw
that Angry Wolf was still unconvinced.

“Was the messenger a blackbird?” Angry Wolf


demanded.

“No,” Little Eagle answered. “It was—”

He stopped. In his excitement he hadn’t noticed what


kind of a bird it had been. He was sure it wasn’t a
blackbird. He would have known better than to follow
one of those bringers of misfortune, even in a dream.
Then he remembered that the bird had said, “The
Crows are my enemies too.”

“It was a mud swallow,” Little Eagle exclaimed. “It told


me that the Crows were its enemies too.”

“That is better,” Angry Wolf admitted. “The Crows shoot


the swallows, and we never do.”

“Then you are ready to accept the sign and try to get 144
horses from the Crows?” Little Eagle demanded.

“I’m not sure it is a sign,” Angry Wolf answered slowly.


“It may just be a dream with no meaning.” He stood up.
“We have to have horses, though. I am willing to try.”

In spite of Angry Wolf’s doubts, Little Eagle was so


excited that he could hardly eat. He reminded himself
that it had been a long journey in his dream. He would
need all of his strength, so he forced himself to eat as
much as if he were hungry.

As soon as Angry Wolf was ready, Little Eagle led the


way. He went to the hill where he had spent the night.
He picked up the deerskin, folded it carefully, and put it
under the tree, as he had done in his dream. In his
dream Little Eagle had gone so swiftly that he hadn’t
noticed the landmarks. Now there was nothing to guide
him. He remembered that he had gone west and a little
south. He tried to take the same direction.

As the sun began to sink low in the west, Angry Wolf


watched anxiously ahead.

“We should be nearing the place,” he said. 145

“It was almost dark when the bird and I got there,”
Little Eagle answered. “We can go many paces before
darkness falls.”

“You said the Crows were camped near trees,” Angry


Wolf reminded him. “We have seen no trees since we
started.”

The same fear had been nagging at Little Eagle. In his


dream the Crows had been camped behind a grove of
trees. Yet he and Angry Wolf had traveled all day
without seeing trees and there seemed to be none
ahead.

The two of them came to the top of a high hill. Far


ahead of them they saw a grove of trees.

“That must be the place,” Little Eagle exclaimed.

“We’d better rest and eat,” Angry Wolf suggested. “We


can’t take horses until after darkness falls.”

They found a place where the sun had melted the snow 146
and dried the ground. Here they ate the cold meat they
had brought with them. For the first time since they had
started, Angry Wolf seemed to think they had a chance
to succeed.
“When we have horses again, we’ll hunt buffaloes,”
Angry Wolf said.

“No other meat is so good,” Little Eagle answered.

They rested until the darkness was heavy enough to


hide their movements. It didn’t take them long to reach
the grove of trees. They could see the gleam of
campfires on the other side of the grove.

The two Sioux slipped among the trees until they


reached a place where they could see the Crow camp.
There were several campfires, and chunks of buffalo
meat were roasting over each of them. Some warriors
were sitting around, gorging on fresh meat. Others had
evidently stuffed themselves and crawled into their
tepees to sleep. As Little Eagle and Angry Wolf watched,
one of the warriors got to his feet and staggered to a
tepee.

Little Eagle knew that sometimes warriors, who had 147


been without food for several days, would stuff
themselves with fresh meat when they had the chance.
Warriors who did that would sleep soundly. He and
Angry Wolf should be able to take horses without
trouble.

Little Eagle touched Angry Wolf’s arm. He began to


circle the camp, with Angry Wolf following him. They
went around the west side of the camp and continued
south until they came to the herd of horses. Even in the
darkness they located the two that had been taken from
them.

Angry Wolf took a careful look around. He motioned for


Little Eagle to stay where he was. Little Eagle waited
patiently as Angry Wolf slipped away in the darkness.
While he was sure there were no guards watching the
herd, Little Eagle realized that Angry Wolf was doing
what should be done. A warrior should look for his
enemies even when he didn’t expect to find them.

“There are no guards,” Angry Wolf whispered when he


returned.

The two boys went straight to their own horses. The


horses stood quietly while their riders mounted. Angry
Wolf wanted to take at least ten horses apiece, but Little
Eagle objected.

“We’ll have a better chance to get away if we pick a few 148


good horses,” he pointed out.

“The more horses we take, the greater our victory,”


Angry Wolf whispered urgently.

After a few minutes of whispering together, Angry Wolf


agreed to accept Little Eagle’s plan to take five horses
apiece. When the horses had been selected, Angry Wolf
took the halter ropes of two of them and started away
from the camp. Little Eagle rode behind, herding the
others. Now the wisdom of Little Eagle’s plan was plain,
for even the few horses were hard to get started. Little
Eagle’s horse was kept turning and plunging to hold the
horses in a bunch.

Angry Wolf rode straight west until he saw that Little


Eagle had the herd under control. Then he turned north,
as they had decided to do. There was no chance to pick
a route where they wouldn’t leave a trail. Even in the
places where there was no snow, the tracks of the
horses could easily be seen.
After they had ridden for what seemed a long time, 149
Little Eagle called for Angry Wolf to stop. Little Eagle
circled the herd and rode to his friend’s side.

“We’ll turn east here,” Little Eagle ordered. “We may be


able to fool the Crows into thinking we are Pawnees. If
we do, they’ll turn south to cut us off. We will soon turn
north again.”

“We have won a great victory over the Crows,” Angry


Wolf gloated.

“We will win a great victory if we get away,” Little Eagle


answered grimly. “The Crows will follow us when they
learn of their loss.”

“By that time we shall have escaped,” Angry Wolf said


hopefully.

Little Eagle looked at his friend in wonder. For days,


Angry Wolf had been downhearted and gloomy. He had
thought they had no chance against the Crows. Now
that they had made this little start, Angry Wolf had
completely changed. He already counted the victory
won.

“We won’t sing the Victory Song until we are sure we


have escaped,” Little Eagle said quietly.

151
CHAPTER SEVEN

As he rode east, Little Eagle felt more and more uneasy.


This plan of his might not be so good. If the Crows
guessed that it was Sioux and not Pawnees they were
chasing, they would take a more direct route. Or they
might send one party to follow the trail and the other to
take a shorter route. It might well be that his plan
would actually make it easier for the Crows to catch
them.

Little Eagle felt easier in his mind when he turned north.


As the eastern sky began to light up, he felt still better.
He and Angry Wolf had come a long way from the Crow
camp. It might be that the Crows hadn’t yet learned of
their loss.

As the sun came up, Little Eagle called a halt. He 152


noticed Angry Wolf’s anxious look as the horses
scattered to graze. Little Eagle unwrapped the last of
their supply of meat.

“For our next meal we’ll have buffalo meat,” he said,


trying to rouse Angry Wolf from his gloom.

“If the Crows catch us, we won’t have a next meal,”


Angry Wolf answered.

“The Crows won’t catch us,” Little Eagle insisted. “We


took the horses easily, just as the mud swallow in my
dream told me we could.”
“We did,” Angry Wolf agreed. “But the swallow didn’t
show you how we were to escape after we had the
horses.”

Little Eagle frowned. A short time ago Angry Wolf had


been full of confidence. He had wanted to sing the
Victory Song. Now he was sure that they couldn’t
succeed. It was true that his dream had ended without
the swallow showing him how to escape with the
horses. Suddenly Little Eagle’s frown changed to a smile
of relief.

“The mud swallow is an enemy of the Crows,” Little 153


Eagle reminded his friend. “He won’t let them catch us.”

“I hope you’re right,” Angry Wolf replied doubtfully.


“Anyway I think we should sleep before we start on. We
need rest.”

Little Eagle wondered if Angry Wolf’s plan was good.


The Crows would soon be on their trail. Every step he
and Angry Wolf went now would be another step away
from their enemies. If the Crows started while he and
Angry Wolf slept, they would be cutting down the
distance between them. But they did need the rest.
Besides, Angry Wolf should make some of the decisions.
He stretched out on the ground and fell asleep.

Little Eagle sat up sleepily when Angry Wolf touched his


arm. He felt as though he had just closed his eyes, yet
when he looked to the east, he saw the sun high above
the hills.

“We must start,” Angry Wolf urged.

It took the two of them a long time to catch horses to 154


ride and drive the others into a herd. When they were
ready to start, Little Eagle again took the lead.

They had trouble keeping the herd moving fast.


Sometimes the horses would trot, but most of the time
they plodded along at a walk. Often one of the horses
tried to turn back. Angry Wolf had to be constantly
alert.

When the sun was straight overhead, Little Eagle didn’t


stop for their usual rest. He did signal for Angry Wolf to
take the lead, and he rode behind the horses.

Whenever they crossed a hill, Little Eagle stopped to


look back. As the day wore on and he saw no signs of
Crows, he began to feel more confident. It was nearly
dark by the time they stopped beside a small stream.
Little Eagle felt almost safe. He was even more
encouraged by Angry Wolf’s growing cheerfulness.

“We seem to have escaped,” Angry Wolf said.

“You could hunt for fresh meat while I build a fire,” Little 155
Eagle suggested, hoping that by keeping Angry Wolf
busy, he could keep him in good spirits.

Angry Wolf was gone only a short time. He came back


with one rabbit.

“It’s too dark to hunt,” Angry Wolf said gloomily.

“I’m so hungry that rabbit will taste as good as roasted


buffalo tongue,” Little Eagle assured him.

As soon as the rabbit was cooked, Little Eagle covered


the fire with dirt.
“There’s no need to give the Crows a signal if they are
following us,” he said.

Little Eagle was glad that there were no clouds in the


sky. Since he had left the deer hide for the swallows,
they had no cover. As long as there was no snow or
rain, he and Angry Wolf could sleep comfortably by
burrowing into a pile of leaves.

When Little Eagle awoke the next morning, he felt like 156
jumping and shouting. It seemed that he ought to
dance the Victory Dance. He and Angry Wolf had
escaped the Crows. The horses they had taken were
proof of a great victory. Because Angry Wolf was
already rounding up the horses, Little Eagle delayed his
celebration. He hurried to help the other boy.

“I’ll try to get a buffalo,” Angry Wolf said when they had
the horses driven together in a herd.

“While you’re hunting, I’ll ride back to the top of the


first hill,” Little Eagle told him. “From there I can see a
long way. If there are no Crows in sight, we can feel
safe.”

Little Eagle would much rather have gone with Angry


Wolf to hunt buffaloes. It was almost certain that they
had escaped the Crows. Yet he had been taught that a
warrior must always guard against surprise.

The hill rose to a high, pointed peak. Little Eagle rode


half way up it. Here he dismounted. He crept up the last
few paces to the top as carefully as though he expected
to see Crows coming up the other side. He took a long
time to study the trail. Nothing moved along it. At last
he returned to his horse, mounted, and rode back to
camp.
Little Eagle had been in camp only a short time when 157
Angry Wolf rode in, carrying a piece of buffalo meat.
Angry Wolf rode triumphantly. All of his gloom of the
evening before was gone.

“We’ll bring in the rest of the buffalo meat as soon as


we have eaten,” he said cheerfully.

“We have done well,” Little Eagle said.

“Well!” Angry Wolf exclaimed. “We have won victories


over the Pawnees and Crows. Hunting has been good.
We ought to sing the Victory Song.”

Only a short time ago, Little Eagle had thought they


should sing the Victory Song. Now, as Angry Wolf
became surer that they had escaped, Little Eagle began
to feel new doubts.

“We’d better wait another day,” he said. “I think we


have escaped the Crows, but surely after one more day
there can be no doubt.”

Angry Wolf didn’t act greatly disappointed. He seemed


to feel that one more day before they sang the Victory
Song would make little difference.

Before they started on, Little Eagle helped Angry Wolf 158
bring in the rest of the buffalo meat. They cut the
buffalo hide into two pieces. They placed the meat on
the pieces of hide, then wrapped the hide around the
meat so that each piece of hide made a big bundle.
They tied the two bundles on one of the horses. This
time Angry Wolf led the way, while Little Eagle rode
behind to keep the herd moving.
The prairie here was different from that they had been
crossing. The hills were higher and closer together. It
seemed to Little Eagle that they were always either
going up a hill or down one. He was glad that they
seemed to be safely away from the Crows. Here a party
of enemies might have ridden close before he or Angry
Wolf discovered them.

All morning they seldom saw a tree. They crossed a few 159
spring-fed streams, but even beside these there was
hardly ever a tree. Little Eagle and Angry Wolf
continually traded places so that part of the time Little
Eagle rode ahead and led the way, while at other times
he rode behind. About the middle of the afternoon he
was riding behind. The horses had given so little trouble
that he paid them scant attention. He was humming the
Victory Song under his breath when, for some reason,
he glanced back. A lone Crow warrior was charging
toward him!

Little Eagle acted swiftly. He shouted a warning to Angry


Wolf and at the same time jabbed his right knee against
his horse’s side to whirl it around to face the Crow. As
his horse whirled, Little Eagle brought up his bow. There
was no time to take aim. The Crow was almost upon
him. Little Eagle let his arrow fly just as the Crow’s
arrow struck him. Little Eagle felt a cutting, tearing pain
in his right arm or shoulder, and the force of the arrow
almost tore him from his horse. He clutched the horse’s
mane to keep from falling.

In a half daze Little Eagle realized that he had dropped


his own bow. He heard the pound of hoofs as the Crow
circled and came back. Little Eagle tried to sit erectly on
his horse. He could do nothing to defend himself, but he
would meet death like a Sioux warrior. The Crow swept
past without taking another shot. It was then that Little
Eagle saw the Crow had been struck with an arrow too.

Angry Wolf dashed past in pursuit of the Crow, but he 160


couldn’t get near the wounded warrior. He fired two
arrows, but both of them went wide of the mark. Little
Eagle dimly realized that Angry Wolf pulled his horse to
a stop at the top of the hill.

Little Eagle didn’t know how long Angry Wolf was gone.
He felt himself falling. He braced himself with the hand
that held the horse’s mane and fought against the
darkness that was closing in on him. The wave of
darkness passed, and Little Eagle was still on his horse.

When he felt stronger, Little Eagle took his hand from


his horse’s mane and felt of the wound. His fingers
touched a shaft of wood. The arrow was stuck in his
arm. The head had gone through the flesh, but the
shaft hadn’t. Little Eagle felt the darkness closing in
again, but he fought it off.

It took a long time for Little Eagle to get up enough 161


courage to try to pull the arrow out. When he reached
for it, he heard a horse approaching. He looked up and
saw Angry Wolf returning.

“I thought the Crow’s arrow had killed you,” Angry Wolf


said as he came near Little Eagle.

Angry Wolf’s eyes widened, and a look of fear came into


them when he saw the arrow stuck through Little
Eagle’s arm and the blood running down from the
wound.

“Help me off my horse,” Little Eagle ordered.


Angry Wolf jumped from his horse to obey. Little Eagle
clamped his teeth together. He held out his good hand
to Angry Wolf. With the other boy’s help he got off his
horse.

“You’ll have to take the arrow out of my wound,” he told


Angry Wolf.

Angry Wolf looked at the arrow. His face was drawn and
he was gritting his teeth.

“How can I get it out?” he asked.

“Take a careful hold of it with both hands,” Little Eagle


answered. “Snap it in two and pull the rest out.”

Little Eagle took a deep breath as Angry Wolf took hold 162
of the arrow. He felt a stab of hot pain as Angry Wolf
broke the arrow. In spite of himself, Little Eagle gasped
as Angry Wolf drew the rest of the arrow from the
wound. Little Eagle kept his head turned aside until he
was able to smile. When he looked toward his friend, he
saw that Angry Wolf’s face had the same sickly color it
had had when he had been wounded.

“Did a Crow arrow hit you too?” Little Eagle demanded.

Angry Wolf shook his head.

“I was afraid the Crow’s arrow had taken you to the


Happy Hunting Grounds,” he replied.

Then, as though afraid he had shown too much feeling,


Angry Wolf spoke sharply.

“Tell me how to take care of your wound,” he snapped.


“You have studied under Clawing Bear.”
Little Eagle forced himself to look at his wound. It was a
ragged hole, and blood was oozing down both sides of
his arm.

“I have the material for another poultice,” he answered.


“But it must be cooked. There is no fuel here.”

Angry Wolf looked around. There was grass that he 163


could gather and twist into knots. Although it would be
slow work, they could build a cooking fire with it. He
raised his eyes and looked ahead. As far ahead as he
could see, the prairie looked the same. Yet it might not
be far to a stream that had trees growing beside it. That
would be a safer place to camp than this open ground.

“Can you ride?” Angry Wolf asked, turning toward Little


Eagle.

“Of course,” Little Eagle answered.

Little Eagle spoke stoutly, but when he tried to mount


his horse, he wasn’t able. He had to have Angry Wolf’s
help.

“You ride in front,” Angry Wolf directed. “Go as straight


north as you can.”

A new thought suddenly struck Little Eagle.

“Did the Crow get away?” he asked.

“He was still on his horse when it went out of sight,”


Angry Wolf answered. “But your arrow has wounded
him badly. I don’t think he will get back to the Crow
camp.”
“There might be other Crows near who would come to 164
avenge him,” Little Eagle pointed out.

“There are no other Crows near,” Angry Wolf answered


positively. “If there had been, they would have joined in
the attack on us.”

Little Eagle nodded. No warrior would have been foolish


enough to make an attack alone when other warriors
were near who could help him. He turned his horse and
started off.

At first Little Eagle was able to ride without too much


trouble. It wasn’t long, though, until the journey
became a torture. The wound in his arm made his
whole body hurt. He had lost so much blood that he
was weak and lightheaded. It took all of his remaining
strength to stay on his horse. Weary step after weary
step he held on, but at last he could hold on no longer.
He slid from his horse.

Although Little Eagle didn’t know about it, Angry Wolf


lifted him onto his own horse. He mounted behind Little
Eagle and held him. Angry Wolf rode off without a look
at the herd of horses. He hoped they would follow, but
if they didn’t, it couldn’t be helped.

165
He added the powdered herbs and the bear’s grease

There was still daylight when Angry Wolf sighted trees 166
ahead. Before he reached the grove of trees, he saw
that they were growing along a stream. When he
reached the grove, he gently lifted Little Eagle to the
ground. He dug the bowl from one of the packs and
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.

More than just a book-buying platform, we strive to be a bridge


connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.

Join us on a journey of knowledge exploration, passion nurturing, and


personal growth every day!

ebookbell.com

You might also like