详解Spring Boot微框架,目前还没有中文版本For online information and ordering of this and other Manning books, please visitwww.manning.com.ThepublisheroffersdiscountsonthisbookwhenorderedinquantityFor more information, please contactSpecial sales DepartmentManning publications co20 Baldwin roadPOBoⅹ761Shelter island. nY11964Emailorders@manning.com02016 by Manning Publications Co. All rights reservedNo part of this publication may be reproduced, stored in a retrieval system, or transmitted, inany form or by means electronic, mechanical, photocopying, or otherwise, without prior writtenpermission of the publisherMany of the designations used by manufacturers and sellers to distinguish their products areclaimed as trademarks. Where those designations appear in the book, and manningPublications was aware of a trademark claim, the designations have been printed in initial capsOIlIcapsRecognizing the importance of preserving what has been written, it is Mannings policy to havethe books we publish printed on acid-free paper and we exert our best efforts to that endRecognizing also our responsibility to conserve the resources of our planet, Manning books areprinted on paper that is at least 15 percent recycled and processed without the use of elementalchlorineManning Publications CoDevelopment editor: Cynthia Kane20 Baldwin RoadTechnical development editor: Robert casazzaPOBOⅹ761ditor Andy carrollShelter island. ny11964Proofreader: Corbin CollinsTechnical proofreader John GuthrieTypesetter: Gordan salinovicCover designer: Marija TudorISBN9781617292545Printed in the United states of america12345678910-EBM-201918171615contentsforeword viipreface ixabout this book xiiacknowledgments xuBootstarting Spring I1.1 Spring rebooted 2Taking afresh look at spring 2 Examining Spring Bootessentials 4. What Spring Boot isnt 71. 2 Getting started with Spring bootInstalling the spring Boot ClI 8 Initializing a spring Bootproject with spring Initializr 121.3 Summary 22Developing your first Spring Boot application 232.1 Putting Spring Boot to work 24Examining a newly initialized spring Boot project 26. Dissectinga spring boott build 302.2 Using starter dependencies 33Specifying facet-based dependencies 34. Overriding startertransitive dependencies 35CONTENTS2.3 USing automatic configuration 37Focusing on application functionality 37 Running theapplication 43. What just happened? 452.4 Summary 48Customizing configuration 493.1 Overriding Spring Boot auto-configuration 50Securing the application 50. Creating a custom securityconfiguration 51 Taking another peek under the covers ofauto-configuration 558.2 Externalizing configuration with properties 57Fine-tuning auto-configuration 58 Externally configuringapplication beans 64. Configuring with profiles 698.3 Customizing application error pages 713.4 Summary 74Testing with Spring Boot 764.1 Integration testing auto-configuration 774.2 Testing web applications 79Mocking Spring Mvc 80. Testing web security 834.8 Testing a running application 86Starting the server on a random port 87- Testing hTml pageswith selenium 884.4 Summary 90Getting Groovy with the Spring Boot CLI 925.1 Developing a Spring Boot ClI application 98Setting up the cli project 93. Eliminating code noise withGroovy 94. What just happened? 985.2 Grabbing dependencies 100Overriding default dependency versions 101. Adding dependencyrepositories 1025.3 Running tests with the cli 1025.4 Creating a deployable artifact 1055.5 Summary 106CONTENTS6Applying Grails in Spring Boot 1076.1 Using gorm for data persistence 1086.2 Defining views with Groovy Server Pages 1186.3 Mixing spring boot with grails 3 115Creating a new Grails project 116 Defining the domain 118Writing a grails controller 119. Creating the view 1206. Summary 123Taking a peek inside with the Actuator 1247.1 Exploring the Actuator's endpoints 125Viewing configuration details 126. Tapping runtime metrics 133Shutting down the application 139. Fetching applicationinformation 1407.2 Connecting to the Actuator remote shell 141Viewing the autoconfig report 142. Listing application beans 143Watching application metrics 144. Invoking actuator endpoints 1457. 3 Monitoring your application with JMX 1467.4 Customizing the Actuator 148Changing endpoint Ds 148 Enabling and disabling endpoints 149Adding custom metrics and gauges 149- Creating a custom tracerepository 153. Plugging in custom health indicators 1557.5 Securing Actuator endpoints 1567.6 Summary 1598Deploying Spring Boot applications 1608.1 Weighing deployment options 1618.2 Deploying to an application server 162Building a Warfile 162 Creating a production profile 164Enabling database migration 1688.3 Pushing to the cloud 173Deploying to Cloud Foundry 173. Deploying to Heroku 1778.4 Summary 180endix a spring boot Developer Tools 181appendix b spring boot starters 188appendix c Configuration properties 195appendixd spring boot dependencies 232index 243In the spring of 2014, the Delivery Engineering team at Netflix set out to achieve alofty goal: enable end-to-end global continuous delivery via a software platform thatfacilitates both extensibility and resiliency. my team had previously built two differentapplications attempting to address Netflix's delivery and deployment needs, but bothwere beginning to show the telltale signs of monolith-ness and neither met the goalsof flexibility and resiliency. what's more, the most stymieing effect of these monolithicapplications was ultimately that we were unable to keep pace with our partner's inno-vation. Users had begun to move around our tools rather than with themIt became apparent that if we wanted to provide real value to the company and rapidly innovate, we needed to break up the monoliths into small, independent servicesthat could be released at will. Embracing a microservice architecture gave us hope thatwe could also address the twin goals of flexibility and resiliency. But we needed to do iton a credible foundation where we could count on real concurrency, legitimate monitoring, reliable and easy service discovery, and great runtime performanceWith the JVM as our bedrock, we looked for a framework that would give us rapidvelocity and steadfast operationalization out of the box. We zeroed in on Spring Bootpring Boot makes it effortless to create Spring-powered, production-ready ser-vices without a lot of code! Indeed, the fact that a simple Spring Boot Hello worldapplication can fit into a tweet is a radical departure from what the same functionalityrequired on the ivm only a few short years ago. Out-of-the-box nonfunctional featureslike security, metrics, health-checks, embedded servers, and externalized configuration made boot an easy choice for usFOREWORDYet, when we embarked on our Spring boot journey, solid documentation was hardto come by Relying on source code isnt the most joyful manner of figuring out howto properly leverage a frameworks featuresIt's not surprising to see the author of mannings venerable spring in action take onthe challenge of concisely distilling the core aspects of working with Spring Boot intoanother cogent book. Nor is it surprising that Craig and the manning crew have doneanother tremendously wonderful job! Spring Boot in Action is an easily readable book,as we've now come to expect from Craig and manningFrom chapter Is attention-getting introduction to Boot and the now legend-ary gOish-character tweetable Boot application to an in-depth analysis of Boots Actuatorin chapter 7, which enables a host of auto-magical operational features required for anyproduction application, Spring Boot in Action leaves no stone unturned. Indeed, for me,chapter 7's deep dive into the Actuator answered some of the lingering questions I'vehad in the back of my head since picking up boot well over a year ago. Chapter 8s thorough examination of deployment options opened my eyes to the simplicity of cloudFoundry for cloud deployments. One of my favorite chapters is chapter 4, where Craigexplores the many powerful options for easily testing a Boot application. From the get-go, I was pleasantly surprised with some of Springs testing features, and Boot takesadvantage of them nicelyAs I've publicly stated before, Spring Boot is just the kind of framework the javacommunity has been seeking for over a decade. Its easy-to-use development featuresand out-of-the-box operationalization make Java development fun again. I'm pleasedto report that Spring and Spring Boot are the foundation of Netflix's new continuousdelivery platform. What's more, other teams at Netflix are following the same pathbecause they too see the myriad benefits of bootIt's with equal parts excitement and passion that I absolutely endorse craigs bookas the easy-to-digest and fun-to-read Spring Boot documentation the Java communityhas been waiting for since boot took the community by storm. Craigs accessible writ-ing style and sweeping analysis of boot's core features and functionality will surelyleave readers with a solid grasp of boot (along with a joyful sense of awe for it)Keep up the great work Craig, Manning Publications, and all the brilliant developers who have made Spring Boot what it is today! Each one of you has ensured a brightfuture for the JVMANDREW GLOVERANAGER, DELIVERY ENGINEERING AT NETFLIXefaceAt the 1964 New York Worlds Fair, Walt Disney introduced three groundbreakingattractions:“it' s a small world,”“ Great moments with mr. Lincoln,” and the“ Carouselof Progress. All three of these attractions have since moved into disneyland and waltDisney world, and you can still see them todayMy favorite of these is the carousel of Progress. Supposedly it was one of waltDisneys favorites too. It's part ride and part stage show where the seating arearotates around a center area featuring four stages. Each stage tells the story ofa family at different time periods of the 20th century-the early 1900s the 1920sthe 1940s, and recent times--highlighting the technology advances in that timeperiod. The story of innovation is told from a hand- cranked washing machine, toelectric lighting and radio, to automatic dishwashers and television, to computersand voice-activated appliancesIn every act, the father (who is also the narrator of the show) talks about the latestinventions and says It cant get any better, only to discover that, in fact, it does getbetter in the next act as technology progressesAlthough Spring doesn't have quite as long a history as that displayed in the Carousel of Progress, I feel the same way about Spring as"Progress Dad" felt about the20th century. each and every spring application seems to make the lives of developerso much better. Just looking at how Spring components are declared and wiredtogether, we can see the following progression over the history of spring