(Ebook PDF) Spring in Action 5th Edition Download
(Ebook PDF) Spring in Action 5th Edition Download
download
https://ebooksecure.com/product/ebook-pdf-spring-in-action-5th-
edition/
http://ebooksecure.com/product/original-pdf-inclusion-in-
action-5th-australia-edition/
https://ebooksecure.com/download/progress-in-heterocyclic-
chemistry-ebook-pdf/
http://ebooksecure.com/product/ebook-pdf-translational-medicine-
in-cns-drug-development-volume-29/
http://ebooksecure.com/product/ebook-pdf-mathematics-in-action-
algebraic-graphical-and-trigonometric-problem-solving-5th-
edition/
Business in Action 8th Edition (eBook PDF)
http://ebooksecure.com/product/business-in-action-8th-edition-
ebook-pdf/
http://ebooksecure.com/product/technology-in-action-
complete-15th-edition-ebook-pdf/
http://ebooksecure.com/product/ebook-pdf-organizational-culture-
in-action-3rd-edition/
http://ebooksecure.com/product/original-pdf-sociology-in-
action-3rd-canadian-edition/
http://ebooksecure.com/product/ebook-pdf-technology-in-action-
complete-13th-edition/
Covers Spring 5.0
FIFTH EDITION
Craig Walls
MANNING
vi CONTENTS
4 Securing Spring 84
4.1 Enabling Spring Security 85
4.2 Configuring Spring Security 86
In-memory user store 88 JDBC-based user store
■
89
LDAP-backed user store 92 Customizing user
■
authentication 96
4.3 Securing web requests 103
Securing requests 104 Creating a custom login page 106
■
modules 230
9.3 Creating an email integration flow 231
10 Introducing Reactor
10.1
241
Understanding reactive programming 242
Defining Reactive Streams 243
10.2 Getting started with Reactor 245
Diagramming reactive flows 246 ■ Adding Reactor
dependencies 247
10.3 Applying common reactive operations 248
Creating reactive types 249 Combining reactive types 253
■
repositories 300
12.2 Working with reactive Cassandra repositories 300
Enabling Spring Data Cassandra 301 Understanding Cassandra■
interfaces 317
xiii
xiv PREFACE
I’m happy to say that this fifth edition of Spring in Action covers all of this and
more! If you’re a seasoned veteran with Spring, Spring in Action, Fifth Edition will be
your guide to everything new that Spring has to offer. On the other hand, if you’re
new to Spring, then there’s no better time than now to get in on the action and the
first few chapters will get you up and running in no time!
It’s been an exciting 15 years of working with Spring. And now that I’ve written this
fifth edition of Spring in Action, I’m eager to share that excitement with you!
acknowledgments
One of the most amazing things that Spring and Spring Boot do is to automatically
provide all of the foundational plumbing for an application, leaving you as a devel-
oper to focus primarily on the logic that’s unique to your application. Unfortunately,
no such magic exists for writing a book. Or does it?
At Manning, there were several people working their magic to make sure that this
book is the best it can possibly be. Many thanks in particular to Jenny Stout, my devel-
opment editor, and to the production team, including project manager Janet Vail,
copyeditors Andy Carroll and Frances Buran, and proofreaders Katie Tennant and
Melody Dolab. Thanks, too, to technical proofer Joshua White who was thorough
and helpful.
Along the way, we got feedback from several peer reviewers who made sure that the
book stayed on target and covered the right stuff. For this, my thanks goes to Andrea
Barisone, Arnaldo Ayala, Bill Fly, Colin Joyce, Daniel Vaughan, David Witherspoon,
Eddu Melendez, Iain Campbell, Jettro Coenradie, John Gunvaldson, Markus Matzker,
Nick Rakochy, Nusry Firdousi, Piotr Kafel, Raphael Villela, Riccardo Noviello, Sergio
Fernandez Gonzalez, Sergiy Pylypets, Thiago Presa, Thorsten Weber, Waldemar
Modzelewski, Yagiz Erkan, and Željko Trogrlić.
As always, there’d be absolutely no point in writing this book if it weren’t for the
amazing work done by the members of the Spring engineering team. I’m amazed at
what you’ve created and how we continue to change how software is developed.
Many thanks to my fellow speakers on the No Fluff/Just Stuff tour. I continue to
learn so much from every one of you. I especially want to thank Brian Sletten, Nate
xv
xvi ACKNOWLEDGMENTS
Schutta, and Ken Kousen for conversations and emails about Spring that have helped
shape this book.
Once again, I’d like to thank the Phoenicians. You know what you did.
Finally, to my beautiful wife Raymie, the love of my life, my sweetest dream, and my
inspiration: Thank you for your encouragement and for putting up with another book
project. And to my sweet and wonderful girls, Maisy and Madi: I am so proud of you
and of the amazing young ladies you are becoming. I love all of you more than you
can imagine or I can possible express.
about this book
Spring in Action, Fifth Edition was written to equip you to build amazing applications
using the Spring Framework, Spring Boot, and a variety of ancillary members of the
Spring ecosystem. It begins by showing you how to develop web-based, database-
backed Java applications with Spring and Spring Boot. It then expands on the essen-
tials by showing how to integrate with other applications, program using reactive
types, and then break an application into discrete microservices. Finally, it discusses
how to ready an application for deployment.
Although all of the projects in the Spring ecosystem provide excellent documenta-
tion, this book does something that none of the reference documents do: provide a
hands-on, project-driven guide to bringing the elements of Spring together to build a
real application.
xvii
xviii ABOUT THIS BOOK
■ Chapter 2 discusses building the web layer of an application using Spring MVC.
In this chapter, you’ll build controllers that handle web requests and views that
render information in the web browser.
■ Chapter 3 delves into the backend of a Spring application where data is per-
sisted to a relational database.
■ In chapter 4, you’ll use Spring Security to authenticate users and prevent unau-
thorized access to an application.
■ Chapter 5 reveals how to configure a Spring application using Spring Boot con-
figuration properties. You’ll also learn how to selectively apply configuration
using profiles.
Part 2 covers topics that help integrate your Spring application with other applications:
■ Chapter 6 expands on the discussion of Spring MVC started in chapter 2 by
looking at how to write REST APIs in Spring.
■ Chapter 7 turns the tables on chapter 6 to show how a Spring application can
consume a REST API.
■ Chapter 8 looks at using asynchronous communication to enable a Spring
application to both send and receive messages using the Java Message Service,
RabbitMQ, or Kafka.
■ Chapter 9 discusses declarative application integration using the Spring Inte-
gration project.
Part 3 explores the exciting new support for reactive programming in Spring:
■ Chapter 10 introduces Project Reactor, the reactive programming library that
underpins Spring 5’s reactive features.
■ Chapter 11 revisits REST API development, introducing Spring WebFlex, a new
web framework that borrows much from Spring MVC while offering a new reac-
tive model for web development.
■ Chapter 12 takes a look at writing reactive data persistence with Spring Data to
read and write data to Cassandra and Mongo databases.
Part 4 breaks down the monolithic application model, introducing you to Spring
Cloud and microservice development:
■ Chapter 13 dives into service discovery, using Spring with Netflix’s Eureka regis-
try to both register and discover Spring-based microservices.
■ Chapter 14 shows how to centralize application configuration in a configura-
tion server that shares configuration across multiple microservices.
■ Chapter 15 introduces the circuit breaker pattern with Hystrix, enabling micro-
services that are resilient in the face of failure.
In part 5, you’ll ready an application for production and see how to deploy it:
■ Chapter 16 introduces the Spring Boot Actuator, an extension to Spring Boot
that exposes the internals of a running Spring application as REST endpoints.
ABOUT THIS BOOK xix
■ In chapter 17 you’ll see how to use the Spring Boot Admin to put a user-friendly
browser-based administrative application on top of the Actuator.
■ Chapter 18 discusses how to expose and consume Spring beans as JMX MBeans.
■ Finally, in chapter 19 you’ll see how to deploy your Spring application in a vari-
ety of production environments.
In general, developers new to Spring should start with chapter 1 and work through
each chapter sequentially. Experienced Spring developers may prefer to jump in at
any point that interests them. Even so, each chapter builds upon the previous chapter,
so there may be some context missing if you dive into the middle of the book.
Book forum
Purchase of Spring in Action, 5th edition, includes free access to a private web forum
run by Manning Publications where you can make comments about the book, ask
technical questions, and receive help from the author and from other users. To access
the forum, go to https://forums.manning.com/forums/spring-in-action-fifth-edition.
You can also learn more about Manning’s forums and the rules of conduct at https://
forums.manning.com/forums/about.
Manning’s commitment to our readers is to provide a venue where a meaningful
dialogue between individual readers and between readers and the author can take
place. It is not a commitment to any specific amount of participation on the part of
the author, whose contribution to the forum remains voluntary (and unpaid). We sug-
gest you try asking the author some challenging questions lest his interest stray! The
forum and the archives of previous discussions will be accessible from the publisher’s
website as long as the book is in print.
xx ABOUT THIS BOOK
Foundational Spring
P art 1 of this book will get you started writing a Spring application, learning
the foundations of Spring along the way.
In chapter 1, I’ll give you a quick overview of Spring and Spring Boot essen-
tials and show you how to initialize a Spring project as you work on building
Taco Cloud, your first Spring application. In chapter 2, you’ll dig deeper into
the Spring MCV and learn how to present model data in the browser and how to
process and validate form input. You’ll also get some tips on choosing a view tem-
plate library. You’ll add data persistence to the Taco Cloud application in chapter
3. There, we’ll cover using Spring’s JDBC template, how to insert data, and how to
declare JPA repositories with Spring Data. Chapter 4 covers security for your
Spring application, including autoconfiguring Spring Security, defining custom
user storage, customizing the login page, and securing against cross-site request
forgery (CSRF) attacks. To close out part 1, we'll look at configuration properties
in chapter 5. You’ll learn how to fine-tune autoconfigured beans, apply configura-
tion properties to application components, and work with Spring profiles.
Getting started
with Spring
Although the Greek philosopher Heraclitus wasn’t well known as a software devel-
oper, he seemed to have a good handle on the subject. He has been quoted as say-
ing, “The only constant is change.” That statement captures a foundational truth of
software development.
The way we develop applications today is different than it was a year ago, 5 years
ago, 10 years ago, and certainly 15 years ago, when an initial form of the Spring
Framework was introduced in Rod Johnson’s book, Expert One-on-One J2EE Design
and Development (Wrox, 2002, http://mng.bz/oVjy).
Back then, the most common types of applications developed were browser-
based web applications, backed by relational databases. While that type of develop-
ment is still relevant, and Spring is well equipped for those kinds of applications,
we’re now also interested in developing applications composed of microservices
destined for the cloud that persist data in a variety of databases. And a new interest
in reactive programming aims to provide greater scalability and improved perfor-
mance with non-blocking operations.
3
Discovering Diverse Content Through
Random Scribd Documents
whilst the purchasers, in consequence of the clashing and
interference between their rights, were exposed to tedious,
vexatious, and ruinous litigation. Kentucky suffered long and
severely from this cause; and is just emerging from the troubles
brought upon her by improvident land legislation. Western Virginia
has also suffered greatly, though not to the same extent.
The state of Georgia had large bodies of waste lands, which she
disposed of in a manner satisfactory, no doubt, to herself, but
astonishing to every one out of that commonwealth. According to
her system, waste lands are distributed in lotteries, among the
people of the state, in conformity with the enactments of the
legislature. And when one district of country is disposed of, as there
are many who do not draw prizes, the unsuccessful call out for fresh
distributions. These are made from time to time, as lands are
acquired from the Indians; and hence one of the causes of the
avidity with which the Indian lands are sought. It is manifest, that
neither the present generation, nor posterity, can derive much
advantage from this mode of alienating public lands. On the
contrary, I should think, it cannot fail to engender speculation and a
spirit of gambling.
It has been only within a few years, that restless men have
thrown before the public their visionary plans for squandering the
public domain. With the existing laws, the great state of the west is
satisfied and contented. She has felt their benefit, and grown great
and powerful under their sway. She knows and testifies to the
liberality of the general government, in the administration of the
public lands, extended alike to her and to the other new states.
There are no petitions from, no movements in Ohio, proposing vital
and radical changes in the system. During the long period, in the
house of representatives, and in the senate, that her upright and
unambitious citizen, the first representative of that state, and
afterwards successively senator and governor, presided over the
committee of public lands, we heard of none of these chimerical
schemes. All went on smoothly, and quietly, and safely. No man, in
the sphere within which he acted, ever commanded or deserved the
implicit confidence of congress, more than Jeremiah Morrow. There
existed a perfect persuasion of his entire impartiality and justice
between the old states and the new. A few artless but sensible
words, pronounced in his plain Scotch Irish dialect, were always
sufficient to insure the passage of any bill or resolution which he
reported. For about twenty-five years, there was no essential change
in the system; and that which was at last made, varying the price of
the public lands from two dollars, at which it had all that time
remained, to one dollar and a quarter, at which it has been fixed
only about ten or twelve years, was founded mainly on the
consideration of abolishing the previous credits.
‘Resolved, that it is expedient for the United States to cede and surrender to
the several states, within whose limits the same may be situated, all the right,
title, and interest of the United States, to any lands lying and being within the
boundaries of such states, respectively, upon such terms and conditions as may be
consistent with the due observance of the public faith, and with the general
interest of the United States.’
‘The bill to graduate the price of the public lands, to make donations thereof
to actual settlers, and to cede the refuse to the states in which they lie, being
under consideration—
‘That the lands which shall have been subject to sale under the provisions of
this act, and shall remain unsold for two years, after having been offered at
twenty-five cents per acre, shall be, and the same is, ceded to the state in which
the same may lie, to be applied by the legislature thereof in support of education,
and the internal improvement of the state.’]
Thus it appears not only that the honorable senator proposed the
cession, but showed himself the friend of education and internal
improvements, by means derived from the general government. For
this liberal disposition on his part, I believe it was, that the state of
Missouri honored a new county with his name. If he had carried his
proposition, that state might well have granted a principality to him.
This right of the whole was stamped upon the face of the new
states at the very instant of their parturition. They admitted and
recognised it with their first breath. They hold their stations, as
members of the confederacy, in virtue of that admission. The
senators who sit here and the members in the house of
representatives from the new states, deliberate in congress with
other senators and representatives, under that admission. And since
the new states came into being, they have recognised this right of
the general government by innumerable acts—
By their concurrence in the passage of hundreds of laws
respecting the public domain, founded upon the incontestable right
of the whole of the states;
The equality contended for between all the states now exists.
The public lands are now held, and ought to be held and
administered for the common benefit of all. I hope our fellow-
citizens of Illinois, Indiana, and Missouri, will reconsider the matter;
that they will cease to take counsel from demagogues who would
deceive them, and instil erroneous principles into their ears; and that
they will feel and acknowledge that their brethren of Kentucky and
of Ohio, and of all the states in the union, have an equal right with
the citizens of those three states, in the public lands. If the
possibility of an event so direful as a severance of this union were
for a moment contemplated, what would be the probable
consequence of such an unspeakable calamity; if three confederacies
were formed out of its fragments, do you imagine that the western
confederacy would consent to have the states including the public
lands hold them exclusively for themselves? Can you imagine that
the states of Ohio, Kentucky, and Tennessee, would quietly renounce
their right in all the public lands west of them? No, sir! No, sir! They
would wade to their knees in blood, before they would make such an
unjust and ignominious surrender.
Second. ‘Because the public debt being now paid, the public lands are entirely
released from the pledge they were under to that object, and are free to receive a
new and liberal destination, for the relief of the states in which they lie.’
Third. ‘Because nearly one hundred millions of acres of the land now in market
are the refuse of sales and donations, through a long series of years, and are of
very little actual value, and only fit to be given to settlers, or abandoned to the
states in which they lie.’
‘Fourth. Because the speedy extinction of the federal title within their limits is
necessary to the independence of the new states, to their equality with the elder
states; to the development of their resources; to the subjection of their soil to
taxation, cultivation, and settlement, and to the proper enjoyment of their
jurisdiction and sovereignty.’
‘Sixth. Because the ramified machinery of the land-office department, and the
ownership of so much soil, extends the patronage and authority of the general
government into the heart and corners of the new states, and subjects their policy
to the danger of a foreign and powerful influence.’
‘Because the sum of four hundred and twenty-five millions of dollars, proposed
to be drawn from the new states and territories, by the sale of their soil, at one
dollar and twenty-five cents per acre, is unconscionable and impracticable—such
as never can be paid—and the bare attempt to raise which, must drain, exhaust,
and impoverish these states, and give birth to the feelings, which a sense of
injustice and oppression never fail to excite, and the excitement of which should
be so carefully avoided in a confederacy of free states.’
The manufacturing committee did not state what the public lands
would, in fact, produce. They could not state it. It is hardly a subject
of approximate estimate. The committee stated what would be the
proceeds, estimated by the minimum price of the public lands; what,
at one half of that price; and added, that, although there might be
much land that would never sell at one dollar and a quarter per acre,
‘as fresh lands are brought into market and exposed to sale at
auction, many of them sell at prices exceeding one dollar and a
quarter per acre.’ They concluded by remarking, that the least
favorable view of regarding them, was to consider them a capital
yielding an annuity of three millions of dollars at this time; that, in a
few years, that annuity would probably be doubled, and that the
capital might then be assumed as equal to one hundred millions of
dollars.
Whatever may be the sum drawn from the sales of the public
lands, it will be contributed, not by citizens of the states alone in
which they are situated, but by emigrants from all the states. And it
will be raised, not in a single year, but in a long series of years. It
would have been impossible for the state of Ohio to have paid, in
one year, the millions that have been raised in that state, by the sale
of public lands; but in a period of upwards of thirty years, the
payment has been made, not only without impoverishing, but with
the constantly increasing prosperity of the state.
Such, Mr. President, are the reasons of the land committee, for
the reduction of the price of the public lands. Some of them had
been anticipated and refuted in the report of the manufacturing
committee; and I hope that I have now shown the insolidity of the
residue.
England has too little land, and too many people. America has
too much land, for the present population of the country, and wants
people. The British crown had owned, for many generations, large
bodies of land, preserved for game and forest, from which but small
revenues were derived. It was proposed to sell out the crown lands,
that they might be peopled and cultivated, and that the royal family
should be placed on the civil list. Mr. Burke supported the proposition
by convincing arguments. But what analogy is there between the
crown lands of the British sovereign, and the public lands of the
United States? Are they here locked up from the people, and, for the
sake of their game or timber, excluded from sale? Are not they freely
exposed in market, to all who want them, at moderate prices? The
complaint is, that they are not sold fast enough, in other words, that
people are not multiplied rapidly enough to buy them. Patience,
gentlemen of the land committee, patience! The new states are daily
rising in power and importance. Some of them are already great and
flourishing members of the confederacy. And, if you will only
acquiesce in the certain and quiet operation of the laws of God and
man, the wilderness will quickly teem with people, and be filled with
the monuments of civilization.
‘The manner in which the remote lands of the United States are selling and
settling, whilst it possibly may tend to increase more quickly the aggregate
population of the country, and the mere means of subsistence, does not increase
capital in the same proportion. * * * * Anything that may serve to hold
back this tendency to diffusion from running too far and too long into an extreme,
can scarcely prove otherwise than salutary * * * * If the population of
these, (a majority of the states, including some western states,) not yet redundant
in fact, though appearing to be so, under this legislative incitement to emigrate,
remain fixed in more instances, as it probably would be by extending the motives
to manufacturing labor, it is believed that the nation would gain in two ways: first,
by the more rapid accumulation of capital, and next, by the gradual reduction of
the excess of its agricultural population over that engaged in other vocations. It is
not imagined that it ever would be practicable, even if it were desirable, to turn
this stream of emigration aside; but resources, opened through the influence of
the laws, in new fields of industry, to the inhabitants of the states already
sufficiently peopled to enter upon them, might operate to lessen, in some degree,
and usefully lessen, its absorbing force.’
Mr. Rush knew that there were thousands of the poorer classes
who never would emigrate; and that emigration, under the best
auspices, was far from being unattended with evil. There are moral,
physical, pecuniary obstacles to all emigration; and these will
increase, as the good vacant lands of the west are removed, by
intervening settlements further and further from society, as it is now
located. It is, I believe, Dr. Johnson who pronounces, that of all
vegetable and animal creation, man is the most difficult to be
uprooted and transferred to a distant country; and he was right.
Space itself, mountains, and seas, and rivers, are impediments. The
want of pecuniary means, the expenses of the outfit, subsistence
and transportation of a family, is no slight circumstance. When all
these difficulties are overcome, (and how few, comparatively, can
surmount them!) the greatest of all remains—that of being torn from
one’s natal spot—separated, for ever, from the roof under which the
companions of his childhood were sheltered, from the trees which
have shaded him from summer’s heats, the spring from whose
gushing fountain he has drunk in his youth, the tombs that hold the
precious relic of his venerated ancestors!