《Spring Boot in Action》【1. 起步】

1 起步

  • Spring 1.0,改变了企业级Java应用开发。依赖注入和声明式事务。
  • Spring 2.0,自定义XML命名空间。
  • Spring 2.5,面向注解的依赖注入模型,@Component和@Autowired,以及Spring MVC编程模型。无需显式声明组件,无需继承一些基础控制器类。
  • Spring 3.0,全新的基于Java的配置方式,从Spring 3.1开始的@Enable打头的注解,去XML化。
  • Spring 4.0,条件配置,运行过程中可以根据类路径,环境等因素觉得哪些配置生效,哪些配置忽略。

1.1 魔力

假设我们要写一个非常简单的Hello World Web应用,至少需要以下这些东西:

  • 项目结构,Maven或者Gradle,至少需要依赖Spring MVC和Servlet API
  • 在web.xml(或者WebApplicationInitializer实现)中声明Spring的DispatcherServlet
  • Spring MVC配置
  • 一个Controller,响应“Hello World”
  • 一个Web服务器,如Tomcat

以上这么多点中,其实只有Controller才是我们关心的代码,其他的都是一些无聊的模板式的代码,多数Web应用都会用到。

看看Spring Boot怎么写:

@RestController
class HelloController {

  @RequestMapping("/")
  def hello() {
    return "Hello World"
  }
}

没有配置,没有web.xml,也没有构建脚本,甚至没有server,如果你安装了CLI,你就可以这么运行:

spring run HelloController.groovy

1.2 特性

Spring Boot并非一种全新的框架,而是在Spring的基础之上,提供了开发Spring应用程序的更便捷的方法。

1.2.1 Auto Configuration

如果你要用JDBC访问关系型数据库,就需要配置一个JdbcTemplate,像这样:

@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
  return new JdbcTemplate(dataSource);
}

@Bean
public DataSource dataSource() {
  return new EmbeddedDatabaseBuilder()
          .setType(EmbeddedDatabaseType.H2)
          .addScripts('schema.sql', 'data.sql')
          .build();
}

为了访问个数据库,每次都要自己配置这样的Bean,太烦了,Spring Boot的自动配置机制非常棒,当它发现项目中有H2依赖包,它自动给你配置一个H2的DataSource,当它发现JdbcTemplate在类路径下,自动给你配置一个JdbcTemplate,并且会帮你自动注入,你就不用自己配置上面两个Bean了,直接拿来用就好了。

1.2.2 Starter Dependencies

每次写代码,依赖是个很头疼的事情,我需要什么包?group和artifact是啥?该用哪个版本?会不会与别的包不兼容?

通过Spring Boot的starter包,借助于Maven或Gradle的传递性依赖特性,你想实现某些功能,直接引入对应功能的starter包就行了,相关的依赖都会引入进来,而且这些starter包的依赖版本都是经过严格测试的,保证版本兼容性不会出现问题。

比如你想写一个web应用,直接引入“web” starter(org.springframework .boot:spring-boot-starter-web),如果你需要security,直接引入“security” starter,所有相关的依赖都会引入进来。

1.2.3 The Command-Line Interface(CLI)

上面1.1中的HelloController都没有import语句,那是因为CLI检测到RequestMapping和RestController,它知道它们来自哪些starter,CLI就会引入这些starter,并且自动配置会生效,所以就可以如此简单。

1.2.4 The Actuator

如果说前面的三个特性都是方便开发的,那么这个东西就是方便监控应用运行的了,通过Actuator,可以看到比如下面这些信息:

  • 配置了哪些Bean以及它们之间的依赖关系
  • 自动配置做了哪些决策
  • 环境变量,系统属性,配置属性,命令行参数等
  • 当前各种线程的状态
  • 近期的HTTP请求
  • 各种指标比如内存使用,垃圾回收,网络请求,数据源使用情况等

可以通过web路径或者shell命令查看(SSH)。

1.3 误解

Spring Boot不是一个应用服务器,虽然通过Spring Boot你可以构建一个可执行的jar包(web应用),那是通过内置Servlet容器来实现的(Tomcat,Jetty,Undertow),而不是Spring Boot本身提供的。

Spring Boot不实现任何的Java标准,比如JPA或JMS,它只是通过自动配置实现这些标准的Bean来实现这些功能的。

Spring Boot不生成任何代码。

Spring Boot就是Spring,它只是帮你做了本来需要你手工去做的事情。

1.4 动手

1.4.1 安装CLI

1. 手工安装

下载下面任意一个

下完解压,把bin路径加到环境变量PATH中即可(需要注销再登录),然后命令行运行:

spring --version

检查是否安装成功。对于Windows用户貌似就这一种方法。

2. SDKMAN安装(推荐)

安装SDKMAN(The Software Development Kit Manager)

curl -s get.sdkman.io | bash
source ~/.sdkman/bin/sdkman-init.sh

安装CLI

sdk install springboot

列出所有版本

sdk list springboot

安装特定版本

sdk install springboot 1.3.5.RELEASE

指定使用某版本

sdk use springboot 1.3.5.RELEASE

设置默认版本

sdk default springboot 1.3.5.RELEASE

3. OS X Homebrew安装

brew tap pivotal/tap
brew install springboot

Homebrew会把CLI安装到/usr/local/bin路径下面。

4. OS X MacPorts安装

sudo port install spring-boot-cli

MacPorts会把CLI安装到/opt/local/share/java/spring-boot-cli路径下面,并在/opt/local/bin下面创建符号链接。

1.4.2 Spring Initializer

Spring Initializer就是一个Web应用,你可以用它生成一个Spring Boot项目的骨架(Maven或Gradle),有几种使用方法:

  • 通过网页(很简单,略)
  • Spring Tool Suite(基于Eclipse,还是用IDEA吧)
  • IntelliJ IDEA(推荐)
  • Spring Boot CLI

通过IDEA

打开IDEA,选择File > New > Project,出来下图

这里写图片描述

点击Next,

这里写图片描述

这里做一些基本配置,点击Next,

这里写图片描述

这里选择你要的功能(依赖),其实就是starter依赖包,常用的比如Security、Web、JPA、MySQL等,点击Next,

这里写图片描述

最后填写项目名称和路径,点击Finish,一个项目骨架就生成并导入IDEA了。

通过Spring Boot CLI

可以用spring init命令来生成项目:

获得使用帮助

spring help init

获得所有参数、项目类型和依赖列表

spring init --list
Spring.Boot.in.Action.2015.12.pdfFor online information and ordering of this and other manning books, please visit www.manning.com.thepublisheroffersdiscountsonthisbookwhenorderedinquantity For more information, please contact Special sales department Manning publications co 20 Baldwin Road PO BoX 761 Shelter island. ny11964 Emailorders@manning.com @2016 by manning Publications Co. All rights reserved No part of this publication may be reproduced, stored in a retrieval system, or transmitted,in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and manning Publications was aware of a trademark claim, the designations have been printed in initial caps ll Recognizing the importance of preserving what has been written, it is Mannings policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine Manning publications co Development editor: Cynthia Kane 20 Baldwin Road Technical development editor: Robert casazza PO BoX 761 Copyeditor: Andy Carroll Shelter island. ny11964 Proofreader: Corbin Collins Technical p der John Guthrie Typesetter: Gordan Salinovic Cover designer: Marija Tudor ISBN9781617292545 Printed in the united states of america 12345678910-EBM-201918171615 contents reword vii pre eface 2x about this book xii acknowledgments xu Bootstarting Spring I 1. 1 Spring rebooted Taking a fresh look at spring 2. Examining spring Boot essentials 4 What Spring Boot isn't 7 1.2 Getting started with Spring boot 8 Installing the spring boot cli 8 Initializing a spring boot project with Spring Initializr 12 3 Summary 22 Developing your first Spring Boot application 23 2.1 Putting spring boot to work 24 Examining a newly initialized spring boot project 26 Dissecting Bc iect build 30 2.2 USing starter dependencies 33 Specifying facet-based dependencies 34. Overriding starter transitive dependencies 35 CONTENTS 2.8 USing automatic configuration 37 Focusing on application functionality 37. Running the application 45. What just happened? 45 2.4 Summary 48 Customizing configuration 49 8.1 Overriding Spring Boot auto-configuration 50 Securing the application 50. Creating a custom security configuration 51. Taking another peek under the covers of auto-configuration55 8.2 Externalizing configuration with properties 57 Fine-tuning auto-configuration 58. Externally configuring application beans 64. Configuring with profiles 69 8.8 Customizing application error pages 71 3.4 Summary 74 Testing with Spring Boot 76 4.1 Integration testing auto-configuration 77 4.2 Testing web applications 79 Mocking spring MvC 80- Testing web security 83 4.3 Testing a running application 86 Starting the server on a random port 87. Testing HTML pages with selenium 88 4.4 Summary 90 Getting Groovy with the spring Boot CLI 92 5.1 Developing a Spring Boot CLI application 93 Setting up the cli project 93 Eliminating code noise with Groovy 94. What just happened? 98 5.2 Grabbing dependencies 100 Overriding default dependency versions 101. Adding dependency repositories 102 5.8 Running tests with the CLI 102 5.4 Creating a deployable artifact 105 5.5 Summary 106 CONTENTS 6 Applying Grails in Spring Boot 107 1 Using gorm for data persistence 108 2 Defining views with groovy server pages 113 6.3 Mixing spring boot with grails 3 115 Creating a new grails project 116 Defining the domain 118 Writing a grails controller 119. Creating the view 120 6.4 Summary 123 Taking a peek inside with the Actuator 124 7.1 Exploring the actuator's endpoints 125 Viewing configuration details 126. Tapping runtime metrics 133 Shutting down the application 139. Fetching application information 140 7.2 Connecting to the Actuator remote shell 141 Viewing the autoconfig report 142. Listing application beans 143 Watching application metrics 144.Invoking actuator endpoints 145 7. 3 Monitoring your application with JMX 146 7.4 Customizing the Actuator 148 Changing endpoint Ds 148 Enabling and disabling endpoints 149 Adding custom metrics and gauges 149- Creating a custom trace repository 153 Plugging in custom health indicators 155 7.5 Securing Actuator endpoints 156 7.6 Summary 159 8 Deploying Spring Boot applications 160 8.1 Weighing deployment options 161 8.2 Deploying to an application server 162 Building a WaRfile 162 Creating a production profile Enabling database migration 168 8.3 Pushing to the cloud 173 Deploying to Cloud Foundry 173 Deploying to Heroku 177 8. Summary 180 appendix a spring Boot developer Tools 187 appendix b spring Boot starters 188 appendix c Configuration properties 195 appendix d spring boot dependencies 232 index 243 In the spring of 2014, the Delivery Engineering team at Netflix set out to achieve a lofty goal: enable end-to-end global continuous delivery via a software platform that facilitates both extensibility and resiliency. my team had previously built two different applications attempting to address Netflix's delivery and deployment needs, but both were beginning to show the telltale signs of monolith-ness and neither met the goals of flexibility and resiliency. What's more, the most stymieing effect of these monolithic applications 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 them It became apparent that if we wanted to provide real value to the company and rap- idly innovate, we needed to break up the monoliths into small, independent services that could be released at will. Embracing a microservice architecture gave us hope that we could also address the twin goals of flexibility and resiliency. but we needed to do it on a credible foundation where we could count on real concurrency, legitimate moni- toring, reliable and easy service discovery, and great runtime performance With the jVM as our bedrock, we looked for a framework that would give us rapid velocity and steadfast operationalization out of the box. We zeroed in on Spring Boot Spring 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 World application can fit into a tweet is a radical departure from what the same functionality required on the vm only a few short years ago. Out-of-the-box nonfunctional features like security, metrics, health-checks, embedded servers, and externalized configura tion made boot an easy choice for us FOREWORD Yet, when we embarked on our Spring boot journey solid documentation was hard to come by. Relying on source code isnt the most joyful manner of figuring out how to properly leverage a frameworks features It's not surprising to see the author of mannings venerable Spring in Action take on the challenge of concisely distilling the core aspects of working with Spring Boot into another cogent book. Nor is it surprising that Craig and the Manning crew have done another tremendously wonderful job! Spring Boot in Action is an easily readable book, as weve now come to expect from Craig and manning From chapter Is attention-getting introduction to Boot and the now legend ary 9Oish-character tweetable Boot application to an in-depth analysis of Boots Actuator in chapter 7, which enables a host of auto-magical operational features required for any production 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've had in the back of my head since picking up Boot well over a year ago. Chapter 8s thor- ough examination of deployment options opened my eyes to the simplicity of cloud Foundry for cloud deployments. One of my favorite chapters is chapter 4, where Craig explores the many powerful options for easily testing a Boot application. From the get- o, I was pleasantly surprised with some of Springs testing features, and boot takes g advantage of them nicely As I've publicly stated before, Spring Boot is just the kind of framework the Java community has been seeking for over a decade. Its easy-to-use development features and out-of-the-box operationalization make java development fun again I,m pleased to report that Spring and spring boot are the foundation of Netflix's new continuous delivery platform. What's more, other teams at Netflix are following the same path because they too see the myriad benefits of boot It's with equal parts excitement and passion that I absolutely endorse craigs book as the easy-to-digest and fun-to-read Spring boot documentation the Java community has 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 surely leave 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 develop ers who have made spring boot what it is today each one of you has ensured a bright future for the JV ANDREW GLOVER MANAGER, DELIVERY ENGINEERING AT NETFLIX preface At the 1964 New York World's Fair, Walt Disney introduced three groundbreaking attractions:"“it' s a small world,”“ Great Moments with mr. Lincoln," and the“ Carouse of Progress " All three of these attractions have since moved into disneyland and walt Disney world, and you can still see them today My favorite of these is the Carousel of Progress. Supposedly, it was one of Walt Disneys favorites too. It's part ride and part stage show where the seating area rotates around a center area featuring four stages. Each stage tells the story of a family at different time periods of the 20th century-the early 1900s, the 1920s the 1940s, and recent times-highlighting the technology advances in that time period The story of innovation is told from a hand-cranked washing machine, to electric lighting and radio, to automatic dishwashers and television, to computers and voice-activated appliances In every act, the father (who is also the narrator of the show)talks about the latest inventions and says "It cant get any better only to discover that in fact, it does get better in the next act as technology progresses Although Spring doesn't have quite as long a history as that displayed in the Car- ousel of Progress, I feel the same way about Spring as"Progress Dad felt about the 20th century. Each and every Spring application seems to make the lives of developers so much better. Just looking at how Spring components are declared and wired together, we can see the following progression over the history of Spring
Summary A developer-focused guide to writing applications using Spring Boot. You'll learn how to bypass the tedious configuration steps so that you can concentrate on your application's behavior. Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications. About the Technology The Spring Framework simplifies enterprise Java development, but it does require lots of tedious configuration work. Spring Boot radically streamlines spinning up a Spring application. You get automatic configuration and a model with established conventions for build-time and runtime dependencies. You also get a handy command-line interface you can use to write scripts in Groovy. Developers who use Spring Boot often say that they can't imagine going back to hand configuring their applications. About the Book Spring Boot in Action is a developer-focused guide to writing applications using Spring Boot. In it, you'll learn how to bypass configuration steps so you can focus on your application's behavior. Spring expert Craig Walls uses interesting and practical examples to teach you both how to use the default settings effectively and how to override and customize Spring Boot for your unique environment. Along the way, you'll pick up insights from Craig's years of Spring development experience. What's Inside Develop Spring apps more efficiently Minimal to no configuration Runtime metrics with the Actuator Covers Spring Boot 1.3 About the Reader Written for readers familiar with the Spring Framework. About the Author Craig Walls is a software developer, author of the popular book Spring in Action, Fourth Edition, and a frequent speaker at conferences.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值