本指南提供了有关Spring Boot如何帮助您加速和促进应用程序开发的示例。阅读更多的Spring入门指南时,您将看到更多Spring Boot用例。它旨在使您快速了解Spring Boot。如果要创建自己的基于Spring Boot的项目,请访问Spring Initializr ,填写项目详细信息,选择选项,然后可以下载Maven构建文件或捆绑为zip文件的项目。

你会建立什么

您将使用Spring Boot构建一个简单的Web应用程序,并向其中添加一些有用的服务。

你需要什么

如何完成本指南

像大多数Spring 入门指南一样,您可以从头开始并完成每个步骤,也可以绕过您已经熟悉的基本设置步骤。无论哪种方式,您最终都可以使用工作代码。

从头开始 ,请继续使用Gradle构建

跳过基础知识 ,请执行以下操作:

完成后 ,您可以根据中的代码检查结果gs-spring-boot/complete

用Gradle构建

用Gradle构建

首先,您设置一个基本的构建脚本。在使用Spring构建应用程序时,可以使用任何喜欢的构建系统,但是此处包含使用GradleMaven所需的代码。如果您都不熟悉,请参阅使用Gradle 构建Java项目使用Maven构建Java项目

创建目录结构

在您选择的项目目录中,创建以下子目录结构;例如, mkdir -p src/main/java/hello在* nix系统上:

└── src
    └── main
        └── java
            └── hello

创建一个Gradle构建文件

build.gradle

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:2.1.6.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

bootJar {
    baseName = 'gs-spring-boot'
    version =  '0.1.0'
}

repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

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

Spring Boot gradle插件提供了许多方便的功能:

  • 它收集类路径上的所有jar,并构建一个可运行的单个“über-jar”,这使执行和传输服务更加方便。

  • 它搜索public static void main()标记为可运行类的方法。

  • 它提供了一个内置的依赖项解析器,用于设置版本号以匹配Spring Boot依赖项 。您可以覆盖所需的任何版本,但是它将默认为Boot选择的一组版本。

用Maven构建

用Maven构建

首先,您设置一个基本的构建脚本。使用Spring构建应用程序时,可以使用任何喜欢的构建系统,但是此处包含了使用Maven所需的代码。如果您不熟悉Maven,请参阅使用Maven 构建Java项目

创建目录结构

在您选择的项目目录中,创建以下子目录结构;例如, mkdir -p src/main/java/hello在* nix系统上:

└── src
    └── main
        └── java
            └── hello

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.springframework</groupId>
    <artifactId>gs-spring-boot</artifactId>
    <version>0.1.0</version>

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

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

    <properties>
        <java.version>1.8</java.version>
    </properties>


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

</project>

Spring Boot Maven插件提供了许多方便的功能:

  • 它收集类路径上的所有jar,并构建一个可运行的单个“über-jar”,这使执行和传输服务更加方便。

  • 它搜索public static void main()标记为可运行类的方法。

  • 它提供了一个内置的依赖项解析器,用于设置版本号以匹配Spring Boot依赖项 。您可以覆盖所需的任何版本,但是它将默认为Boot选择的一组版本。

使用您的IDE进行构建

使用您的IDE进行构建

了解使用Spring Boot可以做什么

Spring Boot提供了一种构建应用程序的快速方法。它查看您的类路径和已配置的bean,对丢失的内容做出合理的假设,然后添加它。借助Spring Boot,您可以将更多精力放在业务功能上,而不必在基础架构上。

例如:

  • 有Spring MVC吗?您几乎总是需要几个特定的bean,Spring Boot会自动添加它们。Spring MVC应用程序还需要一个servlet容器,因此Spring Boot会自动配置嵌入式Tomcat。

  • 有码头吗?如果是这样,您可能不希望使用Tomcat,而希望使用嵌入式Jetty。Spring Boot会为您处理该问题。

  • 有胸腺吗?有一些bean必须始终添加到您的应用程序上下文中。 Spring Boot为您添加了它们。

这些只是Spring Boot提供的自动配置的一些示例。同时,Spring Boot不会妨碍您。例如,如果Thymeleaf在您的路径上,则Spring Boot将添加一个SpringTemplateEngine自动添加到您的应用程序上下文中。但是,如果您定义自己的SpringTemplateEngine使用您自己的设置,那么Spring Boot将不会添加一个。这样您就可以毫不费力地控制自己。

Spring Boot不会生成代码或对文件进行编辑。相反,当您启动应用程序时,Spring Boot会动态地连接bean和设置并将它们应用于您的应用程序上下文。

创建一个简单的Web应用程序

现在,您可以为简单的Web应用程序创建Web控制器。

src/main/java/hello/HelloController.java

package hello;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;

@RestController
public class HelloController {

    @RequestMapping("/")
    public String index() {
        return "Greetings from Spring Boot!";
    }

}

该类被标记为@RestController ,这意味着Spring MVC已准备好使用它来处理Web请求。 @RequestMapping地图/index()方法。从浏览器调用或在命令行上使用curl时,该方法返回纯文本。那是因为@RestController结合@Controller@ResponseBody ,这两个注释会导致Web请求返回数据而不是视图。

创建一个应用程序类

在这里您创建一个Application类的组成部分:

src/main/java/hello/Application.java

package hello;

import java.util.Arrays;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
public class Application {

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

    @Bean
    public CommandLineRunner commandLineRunner(ApplicationContext ctx) {
        return args -> {

            System.out.println("Let's inspect the beans provided by Spring Boot:");

            String[] beanNames = ctx.getBeanDefinitionNames();
            Arrays.sort(beanNames);
            for (String beanName : beanNames) {
                System.out.println(beanName);
            }

        };
    }

}

@SpringBootApplication是一个方便注释,它添加了以下所有内容:

  • @Configuration :将类标记为应用程序上下文的Bean定义的源。

  • @EnableAutoConfiguration :告诉Spring Boot根据类路径设置,其他bean和各种属性设置开始添加bean。例如,如果spring-webmvc在类路径上,此注释将应用程序标记为Web应用程序并激活关键行为,例如设置DispatcherServlet

  • @ComponentScan :告诉Spring在其中寻找其他组件,配置和服务hello包,让它找到控制器。

main()方法使用Spring Boot的SpringApplication.run()启动应用程序的方法。您是否注意到没有一行XML?没有web.xml文件。该Web应用程序是100%纯Java,因此您无需处理任何管道或基础结构。

还有一个CommandLineRunner方法标记为@Bean并在启动时运行。它检索由您的应用程序创建或由于Spring Boot而自动添加的所有bean。它对它们进行排序并打印出来。

运行应用程序

要运行该应用程序,执行:

./gradlew build && java -jar build/libs/gs-spring-boot-0.1.0.jar

如果您使用的是Maven,请执行:

mvn package && java -jar target/gs-spring-boot-0.1.0.jar

您应该看到类似以下的输出:

Let's inspect the beans provided by Spring Boot:
application
beanNameHandlerMapping
defaultServletHandlerMapping
dispatcherServlet
embeddedServletContainerCustomizerBeanPostProcessor
handlerExceptionResolver
helloController
httpRequestHandlerAdapter
messageSource
mvcContentNegotiationManager
mvcConversionService
mvcValidator
org.springframework.boot.autoconfigure.MessageSourceAutoConfiguration
org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$DispatcherServletConfiguration
org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$EmbeddedTomcat
org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration
org.springframework.boot.context.embedded.properties.ServerProperties
org.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessor
org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalRequiredAnnotationProcessor
org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration
propertySourcesBinder
propertySourcesPlaceholderConfigurer
requestMappingHandlerAdapter
requestMappingHandlerMapping
resourceHandlerMapping
simpleControllerHandlerAdapter
tomcatEmbeddedServletContainerFactory
viewControllerHandlerMapping

您可以清楚地看到org.springframework.boot.autoconfigure bean。还有一个tomcatEmbeddedServletContainerFactory

签出服务。

$ curl localhost:8080
Greetings from Spring Boot!

添加单元测试

您将要为添加的端点添加一个测试,Spring Test已经为此提供了一些机制,并且很容易包含在您的项目中。

将此添加到您的构建文件的依赖项列表中:

    testCompile("org.springframework.boot:spring-boot-starter-test")

如果使用的是Maven,请将其添加到依赖项列表中:

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

现在编写一个简单的单元测试,以模拟通过您的端点的servlet请求和响应:

src/test/java/hello/HelloControllerTest.java

package hello;

import static org.hamcrest.Matchers.equalTo;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HelloControllerTest {

    @Autowired
    private MockMvc mvc;

    @Test
    public void getHello() throws Exception {
        mvc.perform(MockMvcRequestBuilders.get("/").accept(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(content().string(equalTo("Greetings from Spring Boot!")));
    }
}

MockMvc来自Spring Test,它允许您通过一组便捷的构建器类将HTTP请求发送到DispatcherServlet并对结果进行断言。注意使用@AutoConfigureMockMvc和...一起@SpringBootTest注入MockMvc实例。使用过@SpringBootTest我们要求创建整个应用程序上下文。一种替代方法是要求Spring Boot使用以下命令仅创建上下文的Web层: @WebMvcTest 。在任何一种情况下,Spring Boot都会自动尝试找到应用程序的主应用程序类,但是如果您要构建其他内容,则可以覆盖它或缩小它的范围。

除了模拟HTTP请求周期外,我们还可以使用Spring Boot编写一个非常简单的全栈集成测试。例如,除了(或同时)上面的模拟测试,我们可以这样做:

src/test/java/hello/HelloControllerIT.java

package hello;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.net.URL;

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.web.client.TestRestTemplate;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.http.ResponseEntity;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class HelloControllerIT {

    @LocalServerPort
    private int port;

    private URL base;

    @Autowired
    private TestRestTemplate template;

    @Before
    public void setUp() throws Exception {
        this.base = new URL("http://localhost:" + port + "/");
    }

    @Test
    public void getHello() throws Exception {
        ResponseEntity<String> response = template.getForEntity(base.toString(),
                String.class);
        assertThat(response.getBody(), equalTo("Greetings from Spring Boot!"));
    }
}

嵌入式服务器通过以下方式在随机端口上启动: webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT并在运行时使用@LocalServerPort

添加生产级服务

如果要为您的企业构建网站,则可能需要添加一些管理服务。Spring Boot提供了一些开箱即用的执行器模块 ,例如运行状况,审计,bean等。

将此添加到您的构建文件的依赖项列表中:

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

如果使用的是Maven,请将其添加到依赖项列表中:

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

然后重新启动应用程序:

./gradlew build && java -jar build/libs/gs-spring-boot-0.1.0.jar

如果您使用的是Maven,请执行:

mvn package && java -jar target/gs-spring-boot-0.1.0.jar

您将看到一组新的RESTful端点添加到了应用程序。这些是Spring Boot提供的管理服务。

2018-03-17 15:42:20.088  ... : Mapped "{[/error],produces=[text/html]}" onto public org.s...
2018-03-17 15:42:20.089  ... : Mapped "{[/error]}" onto public org.springframework.http.R...
2018-03-17 15:42:20.121  ... : Mapped URL path [/webjars/**] onto handler of type [class ...
2018-03-17 15:42:20.121  ... : Mapped URL path [/**] onto handler of type [class org.spri...
2018-03-17 15:42:20.157  ... : Mapped URL path [/**/favicon.ico] onto handler of type [cl...
2018-03-17 15:42:20.488  ... : Mapped "{[/actuator/health],methods=[GET],produces=[application/vnd...
2018-03-17 15:42:20.490  ... : Mapped "{[/actuator/info],methods=[GET],produces=[application/vnd.s...
2018-03-17 15:42:20.491  ... : Mapped "{[/actuator],methods=[GET],produces=[application/vnd.spring...

它们包括:错误, 执行器/运行状况执行器/信息执行器

还有一个/actuator/shutdown端点,但默认情况下仅通过JMX可见。要将其启用为HTTP端点 ,请添加management.endpoints.shutdown.enabled=true给你application.properties文件。

检查应用程序的运行状况很容易。

$ curl localhost:8080/actuator/health
{"status":"UP"}

您可以尝试通过curl调用关闭。

$ curl -X POST localhost:8080/actuator/shutdown
{"timestamp":1401820343710,"error":"Method Not Allowed","status":405,"message":"Request method 'POST' not supported"}

因为我们没有启用它,所以该请求由于不存在而被阻止。

有关这些REST点中的每一个的更多详细信息,以及如何使用application.properties文件(在src/main/resources ),您可以阅读有关端点的详细文档

查看Spring Boot的启动器

您已经看到了Spring Boot的一些“启动器” 。您可以在源代码中看到它们。

JAR支持和Groovy支持

最后一个示例显示了Spring Boot如何使您可能不知道不需要的bean接线变得容易。它展示了如何打开便捷的管理服务。

但是Spring Boot还有更多功能。它不仅支持传统的WAR文件部署,而且借助Spring Boot的加载程序模块,还可以轻松地将可执行的JAR放在一起。各种指南通过以下方式展示了这种双重支持: spring-boot-gradle-pluginspring-boot-maven-plugin

最重要的是,Spring Boot还具有Groovy支持,使您仅用一个文件就可以构建Spring MVC Web应用程序。

创建一个名为app.groovy的新文件,并将以下代码放入其中:

@RestController
class ThisWillActuallyRun {

    @RequestMapping("/")
    String home() {
        return "Hello World!"
    }

}
文件在哪里都没有关系。您甚至可以在一个推文中包含一个很小的应用程序!

接下来, 安装Spring Boot的CLI

如下运行:

$ spring run app.groovy
假设您关闭了先前的应用程序,以避免端口冲突。

在另一个终端窗口中:

$ curl localhost:8080
Hello World!

Spring Boot通过在代码中动态添加关键注释并使用Groovy Grape来拉低使应用程序运行所需的库来实现此目的。

摘要

恭喜你!您使用Spring Boot构建了一个简单的Web应用程序,并了解了它如何加快您的开发速度。您还打开了一些便捷的生产服务。这只是Spring Boot可以做的一小部分。如果您想深入了解,请查阅Spring Boot的在线文档

也可以看看

以下指南也可能会有所帮助:

是否要编写新指南或为现有指南做出贡献?查看我们的贡献准则

所有指南均以代码的ASLv2许可证和写作的Attribution,NoDerivatives创作共用许可证发布