SpringBoot in Action——初识SpringBoot

现在,我们里利用了整本书的篇幅来介绍Spring。尽管Spring带来的主要益处就是简化Java开发,但本章将会介绍Spring Boot如何让这项任务变得更简单。
Spring Boot在Spring之上,构建了全新的开发模式,移除了开发Spring应用中很多单调乏味的东西。
我们首先整体了解一下Spring Boot,看它是怎么简化Spring的。

Spring Boot简介

在Spring家族中,Spring Boot主要提供了四个特性,能够改变Spring应用程序的方式:

  • Spring Boot Starter:它将常用的依赖分组进行了整合,将其合并到一个依赖中,这样就可以一次性添加到项目的Mvn或Gradle构建中。
  • 自动配置:Spring Boot的自动配置特性利用了Spring4对条件化配置的支持,合理地推测应用所需的bean并自动化配置它们。
  • 命令行接口(Command-line interface,CLI):CLI发挥了Groovy编程语言的优势,并结合自动配置进一步简化Spring应用的开发。
  • Actuator:它为SpringBoot应用添加了一定的管理特性。

添加Starter依赖
有两种制作蛋糕的方式:一种是买好面粉、鸡蛋、糖、发酵粉、奶油等等,自己搅拌成糊状制作;另一种是购买打包好的蛋糕,我们只需要加入一些其他的辅料即可。
Spring boot就是后面一种方法。
Spring Boot Starter 依赖将所需的常见依赖按组聚集在一起,形成单条依赖。

自动配置
Spring boot的Starter减少了pom.xml中依赖的长度。而Spring boot的自动配置功能则能削减Spring配置的数量。它在实现时,会考虑应用中的其他因素并推断你所需要的Spring配置。

CLI
Spring boot CLI充分利用了Spring boot starter和自动配置的魔力,并添加了一些Groovy的功能。它简化了Spring的开发流程,通过CLI,我们能够运行一个或多个Groovy脚本,并查看它是如何运行的。在应用的运行过程中,CLI能够自动导入Spring类型并解析依赖。

用来阐述Spring Boot CLI最有趣的例子就是如下的Groovy脚本:

@RestController
class Hi{
	@RequestMapping("/")
	String hi(){
		"Hi!"
	}
}

很难相信这是一个完整的Spring应用吧?但是它的确是对的。如果你已经安装过Spring Boot CLI,我们可以使用如下的命令行来运行它:
$ spring run Hi.groovy

Actuator
Spring Boot Actuator为Spring Boot项目带来很多游泳的特性,包括:

  • 管理端点
  • 合理的异常处理以及默认的“/error”映射端点
  • 获取应用信息的“/info”端点
  • 当启用Spring Security时,会有一个审计事件框架

之后我们会介绍到。接下来,我们将使用以上4个主要特性构建一个微小但完整的应用程序。

使用SpringBoot构建应用

我们的应用程序是一个简单的联系人列表,它允许用户输入联系人信息(名字、电话、EMail),并且能够列出用户之前输入的所有联系人信息。

你可以使用Mvn或者Gradle来构建。
Gradle:

buildscript {
	repositories {
		mavenCentral()
	}

	dependencies {
		classpath("org.springframework.boot:spring-boot-gradle-plugin:1.1.4.RELEASE")
	}
}

apply plugin: 'java'
apply plugin: 'spring-boot'

//构建Jar文件
jar {
	baseName = 'contacts'
	version  = '0.1.0'
}

repositories {
	mavenCentral()
}

//依赖
dependencies {
	compile("org.springframework.boot:spring-boot-starter-web")
	compile("org.springframework.boot:spring-boot-starter-jdbc")
	compile("org.thymeleaf:thymeleaf-spring4")
	compile("com.h2database:h2")
}

task wrapper(type: Wrapper) {
	gradleVersion = '2.0'
}

Maven

<?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.habuma</groupId>
  <artifactId>contacts</artifactId>
  <version>0.1.0</version>
  <packaging>jar</packaging>
  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.1.4.RELEASE</version>
  </parent>

  <dependencies>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
      <groupId>org.thymeleaf</groupId>
      <artifactId>thymeleaf-spring4</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
      <groupId>com.h2database</groupId>
      <artifactId>h2</artifactId>
    </dependency>
  </dependencies> 

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

</project>

Gradle的好处就在于精简,往往Maven三四行的代码,Gradle一行就能概括。比如maven里面的spring-boot插件,使用<plugin>,在Gradle里面使用一行:apply plugin: 'spring-boot'

处理请求
因为我们要使用SpringMVC来开发应用Web层,因此需要将Spring Mvc作为依赖添加到构建中。我们已经讨论过,Spring Boot的Web Starter能够将Spring MVC需要的所有内容一站式添加到构建中。
gradle:

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

maven:

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

注意为什么这里没有版本号呢?因为Spring Boot parent项目已经制定了版本。

现在我们编写控制器类:

package com.promusician;

import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


@Controller
@RequestMapping("/")
public class ContactController {

    private ContactRepository contactRepo;

    @Autowired
    public ContactController(ContactRepository contactRepo) {
        this.contactRepo = contactRepo;
    }

    @RequestMapping(method=RequestMethod.GET)
    public String home(Map<String,Object> model) {
        List<Contact> contacts = contactRepo.findAll();
        model.put("contacts", contacts);
        return "home";
    }

    @RequestMapping(method=RequestMethod.POST)
    public String submit(Contact contact) {
        contactRepo.save(contact);
        return "redirect:/";
    }
}

有了前面的基础,这个程序很好理解,不做赘述。

按照传统方式,Java Web应用会使用JSP作为视图层的技术。但是,正如在第六章所说(不好意思我跳过了)。在这个领域有一个新的参与者。Thymeleaf的原生模版比JSP更加便于使用,而且它能够让我们以HTML的形式编写模版。鉴于此,我们将使用Thymeleaf来定义“home”视图。

    <dependency>
      <groupId>org.thymeleaf</groupId>
      <artifactId>thymeleaf-spring4</artifactId>
    </dependency>

或者import("org.thymeleaf:thymeleaf-spring4")
需要记住的是,只要我们将Thymeleaf添加到项目的类路径下,就启用了Spring Boot的自动配置。当应用运行时,Spring Boot将会探测到类路径中的Thymeleaf,然后会自动配置视图解析器、模版解析器以及模版引擎。因此,在我们的应用中,不需要显示Spring配置的方法来定义Thymeleaf。

现在来定义视图模版:
如下是home.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
  <head>
    <title>Spring Boot Contacts</title>
    <link rel="stylesheet" th:href="@{/style.css}" />
  </head>

  <body>
    <h2>Spring Boot Contacts</h2>
    <form method="POST">
      <label for="firstName">First Name:</label>
      <input type="text" name="firstName"></input><br/>
      <label for="lastName">Last Name:</label>
      <input type="text" name="lastName"></input><br/>
      <label for="phoneNumber">Phone #:</label>
      <input type="text" name="phoneNumber"></input><br/>
      <label for="emailAddress">Email:</label>
      <input type="text" name="emailAddress"></input><br/>
      <input type="submit"></input>
    </form>

    <ul th:each="contact : ${contacts}">
      <li>
        <span th:text="${contact.firstName}">First</span>
        <span th:text="${contact.lastName}">Last</span> :
        <span th:text="${contact.phoneNumber}">phoneNumber</span>,
        <span th:text="${contact.emailAddress}">emailAddress</span>
      </li>
    </ul>
  </body>
</html>

因为ContactController中home()方法所返回的逻辑视图名为home,因此模版应该放在指定位置:"src/main/resources/templates"中。

持久化数据

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>com.h2database</groupId>
			<artifactId>h2</artifactId>
		</dependency>

或者gradle略。
现在编写Repository类:

package com.promusician;

import java.util.List;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

@Repository
public class ContactRepository {

    private JdbcTemplate jdbc;

    @Autowired
    public ContactRepository(JdbcTemplate jdbc) {
        this.jdbc = jdbc;
    }

    public List<Contact> findAll() {
        return jdbc.query(
                "select id, firstName, lastName, phoneNumber, emailAddress " +
                        "from contacts order by lastName",
                new RowMapper<Contact>() {
                    public Contact mapRow(ResultSet rs, int rowNum) throws SQLException {
                        Contact contact = new Contact();
                        contact.setId(rs.getLong(1));
                        contact.setFirstName(rs.getString(2));
                        contact.setLastName(rs.getString(3));
                        contact.setPhoneNumber(rs.getString(4));
                        contact.setEmailAddress(rs.getString(5));
                        return contact;
                    }
                }
        );
    }

    public void save(Contact contact) {
        jdbc.update(
                "insert into contacts " +
                        "(firstName, lastName, phoneNumber, emailAddress) " +
                        "values (?, ?, ?, ?)",
                contact.getFirstName(), contact.getLastName(),
                contact.getPhoneNumber(), contact.getEmailAddress());
    }

}

我们仔细看,这个Repository类非常简单,简单的增删改查。不过JdbcTemplate呢????我们为啥不用去声明一个DataSource,然后在声明一个JdbcTemplate?
这种问题的回答就是,自动配置!

那数据库模式该怎么处理呢?我们必须自己定义contacts表的模式,因为Spring Boot再强大也没法猜测contacts表的样子。于是,我们这样设置:

create table contacts (
	id identity,
	firstName varchar(30) not null,
	lastName varchar(50) not null,
	phoneNumber varchar(13),
	emailAddress varchar(30)
);

现在我们只需要一种方式加载这个"create table"的SQL并将其在H2数据库中执行就行了。

尝试运行
最后不需要配置DispatcherServlet,启用自动配置就行了。

package com.promusician;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan
@EnableAutoConfiguration
public class PromusicianApplication {

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

本书结束,我们换本书。

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.
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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值