10分钟入门springboot——跟着官网学入门

使用Spring Boot构建应用程序

本指南提供了Spring Boot如何帮助您加速应用程序开发的示例。当您阅读更多的Spring入门指南时,您将看到更多的Spring Boot用例。本指南旨在让您快速体验Spring Boot。如果您想创建自己的基于Spring Boot的项目,请访问Spring Initializer,填写项目详细信息,选择选项,并下载打包的项目作为zip文件。

您将构建的内容

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

您需要什么
如何完成本指南

与大多数Spring入门指南一样,您可以从头开始并完成每个步骤,也可以跳过您已经熟悉的基本设置步骤。无论哪种方式,你都会得到有效的代码。

要从头开始,请转到 从Spring Initializer开始
要跳过基础知识,请执行以下操作:

  • 下载并解压缩本指南的源存储库,或使用Git:
    git clone https://github.com/spring-guides/gs-spring-boot.git
  • cd 进入 gs-spring-boot/initial
  • 跳转到 创建简单的Web应用程序
    完成后,您可以对照 gs-spring-boot/complete 中的代码检查结果。
了解如何使用Spring Boot

Spring Boot提供了一种快速构建应用程序的方法。它查看您的类路径和您配置的bean,对您缺少的内容进行合理的假设,并添加这些项。使用Spring Boot,您可以更多地关注业务功能,而较少关注基础设施。

以下示例显示了Spring Boot可以为您做什么:

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

Jetty在类路径中吗?如果是这样,您可能不希望使用Tomcat,而是希望使用嵌入式Jetty。Spring Boot为您处理此问题。

Thymeleaf 在类路径上吗?如果是这样,那么必须始终将一些bean添加到应用程序上下文中。Spring Boot为您添加了它们。

这些只是Spring Boot提供的自动配置的几个示例。同时,Spring Boot也不会妨碍您。例如,如果Thymeleaf 在您的路径上,Spring Boot会自动将SpringTemplateEngine添加到应用程序上下文中。但如果您使用自己的设置定义自己的SpringTemplateEngine,Spring Boot不会添加一个。这会让你在控制中,你几乎不需要付出任何努力。

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

从Spring Initializer开始

您可以使用这个预初始化的项目,然后单击“生成”下载ZIP文件。此项目配置为适合本教程中的示例。
要手动初始化项目,请执行以下操作:

  1. 进入到 https://start.spring.io .此服务将获取应用程序所需的所有依赖项,并为您完成大部分设置。
  2. 选择Gradle或Maven以及您要使用的语言。本指南假设您选择了Java。
  3. 单击Dependencies并选择SpringWeb。
  4. 单击“生成”。
  5. 下载生成的ZIP文件,该文件是根据您的选择配置的web应用程序的存档。

如果您的IDE集成了SpringInitializer,则可以从IDE完成此过程。
您还可以从Github fork 项目,并在IDE或其他编辑器中打开它。

创建简单的Web应用程序

现在,您可以为一个简单的web应用程序创建一个web控制器,如下列表(来自src/main/java/comple/springboot/HelloController.java)所示:

package com.example.springboot;

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

@RestController
public class HelloController {

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

}

该类被标记为 @RestController,这意味着Spring MVC可以使用它来处理web请求。@GetMapping/映射到index()方法。当从浏览器或通过在命令行上使用curl调用时,该方法返回纯文本。这是因为@RestController结合了@Controller@ResponseBody,这两个注释导致web请求返回数据而不是视图。

创建应用程序类

SpringInitializer为您创建了一个简单的应用程序类。然而,在这种情况下,它太简单了。您需要修改应用程序类以匹配以下列表(来自src/main/java.com/example/springboot/application.java):

package com.example.springboot;

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:告诉SpringBoot开始基于类路径设置、其他bean和各种属性设置添加bean。例如,如果spring-webmvc位于类路径中,则该注释将应用程序标记为web应用程序并激活关键行为,例如设置DispatcherServlet。
  • @ComponentScan:告诉Spring在com/example包中查找其他组件、配置和服务,让它找到控制器。
    main()方法使用Spring Boot的SpringApplication.run()方法启动应用程序。您注意到没有一行XML吗?也没有web.xml文件。这个web应用程序是100%纯Java,您不必处理任何管道或基础设施的配置。
    还有一个标记为@BeanCommandLineRunner方法,它在启动时运行。它检索应用程序创建的或Spring Boot自动添加的所有bean。它将它们分类并打印出来。
运行应用程序

要运行应用程序,请在终端窗口(在完整目录中)中运行以下命令:

./gradlew bootRun

如果使用Maven,请在终端窗口(在完整目录中)中运行以下命令:

./mvnw spring-boot:run

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

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运行服务(在单独的终端窗口中):

$ curl localhost:8080
Greetings from Spring Boot!
添加单元测试

您将需要为您添加的端点添加一个测试,而SpringTest为此提供了一些机制。

如果使用Gradle,请将以下依赖项添加到build.Gradle文件中:

testImplementation('org.springframework.boot:spring-boot-starter-test')

如果使用Maven,请将以下内容添加到pom.xml文件中:

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

现在编写一个简单的单元测试,通过端点模拟servlet请求和响应,如下清单(来自src/test/java.com/example/springboot/HelloControllerTest.java)所示:

package com.example.springboot;

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.jupiter.api.Test;

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.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;

@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来自SpringTest,它允许您通过一组方便的构建器类将HTTP请求发送到DispatcherServlet,并对结果进行断言。注意使用@AutoConfigureMockMvc@SpringBootTest注入MockMvc实例。使用@SpringBootTest后,我们要求创建整个应用程序上下文。另一种方法是让Spring Boot使用@WebMvcTest只创建上下文的web层。无论是哪种情况,Spring Boot都会自动尝试定位应用程序的主应用程序类,但如果您想构建不同的应用程序,则可以覆盖它或缩小它的范围。

除了模拟HTTP请求周期,您还可以使用Spring Boot编写一个简单的全栈集成测试。例如,我们可以创建以下测试(从src/test/java/com/example/springboot/HelloControllerIT.java),而不是(或)前面显示的模拟测试:

package com.example.springboot;

import org.junit.jupiter.api.Test;

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.http.ResponseEntity;

import static org.assertj.core.api.Assertions.assertThat;

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

	@Autowired
	private TestRestTemplate template;

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

由于webEnvironment = SpringBootTest.webEnvironment.random_port,嵌入式服务器在随机端口上启动,实际端口在TestRestTemplate的基本URL中自动配置。

添加生产服务

如果您正在为您的企业构建网站,您可能需要添加一些管理服务。Spring Boot通过其执行器模块提供了几个这样的服务(如健康、审计、bean等)。

如果使用Gradle,请将以下依赖项添加到build.Gradle文件中:

implementation 'org.springframework.boot:spring-boot-starter-actuator'

如果使用Maven,请将以下依赖项添加到pom.xml文件中:

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

然后重新启动应用程序。如果使用Gradle,请在终端窗口中(在完整目录中)运行以下命令:

./gradlew bootRun

如果使用Maven,请在终端窗口中(在完整目录中)运行以下命令:

./mvnw spring-boot:run

您应该看到,一组新的RESTful端点已添加到应用程序中。这些是Spring Boot提供的管理服务。以下列表显示了典型输出:

management.endpoint.configprops-org.springframework.boot.actuate.autoconfigure.context.properties.ConfigurationPropertiesReportEndpointProperties
management.endpoint.env-org.springframework.boot.actuate.autoconfigure.env.EnvironmentEndpointProperties
management.endpoint.health-org.springframework.boot.actuate.autoconfigure.health.HealthEndpointProperties
management.endpoint.logfile-org.springframework.boot.actuate.autoconfigure.logging.LogFileWebEndpointProperties
management.endpoints.jmx-org.springframework.boot.actuate.autoconfigure.endpoint.jmx.JmxEndpointProperties
management.endpoints.web-org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties
management.endpoints.web.cors-org.springframework.boot.actuate.autoconfigure.endpoint.web.CorsEndpointProperties
management.health.diskspace-org.springframework.boot.actuate.autoconfigure.system.DiskSpaceHealthIndicatorProperties
management.info-org.springframework.boot.actuate.autoconfigure.info.InfoContributorProperties
management.metrics-org.springframework.boot.actuate.autoconfigure.metrics.MetricsProperties
management.metrics.export.simple-org.springframework.boot.actuate.autoconfigure.metrics.export.simple.SimpleProperties
management.server-org.springframework.boot.actuate.autoconfigure.web.server.ManagementServerProperties

监控器会提供以下服务

  • actuator/health (http://localhost:8080/actuator/health)
  • actuator (http://localhost:8080/actuator)

还有一个/actuator/shutdown端点,但默认情况下,它仅通过JMX可见。要将其作为HTTP端点启用,请将management.endpoint.shutdown.enabled=true添加到您的application.properties文件中,并使用management.rendpoints.web.exposion.include=health,info,shutdown将其公开。但是,您可能不应为公共可用的应用程序启用关闭端点。

您可以通过运行以下命令检查应用程序的运行状况:

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

您还可以尝试通过curl调用shutdown,以查看未向application.properties添加必要的行(如前一注释所示)时发生的情况:

$ curl -X POST localhost:8080/actuator/shutdown
{"timestamp":1401820343710,"error":"Not Found","status":404,"message":"","path":"/actuator/shutdown"}

因为我们没有启用它,所以请求的端点不可用(因为端点不存在)。
有关每个REST端点以及如何使用application.properties文件(在src/main/resources中)调整其设置的更多详细信息,请参阅有关端点的文档

查看Spring Boot的启动器

您已经看到了一些Spring Boot的“开胃菜”。您可以在源代码中看到它们。

JAR支持和Groovy支持

最后一个示例显示了Spring Boot如何让您连接您可能不知道需要的bean。它还展示了如何开启便捷的管理服务。
然而,Spring Boot的作用不止于此。由于Spring Boot的加载器模块,它不仅支持传统的WAR文件部署,还允许您将可执行JAR放在一起。各种指南通过spring-boot-gradle-plugin插件和spring-boot-maven-plugin 插件演示了这种双重支持。
除此之外,Spring Boot还支持Groovy,允许您使用一个文件来构建Spring MVC web应用程序。
创建一个名为app.groovy的新文件,并将以下代码放入其中:

@RestController
class ThisWillActuallyRun {

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

}

文件在哪里并不重要。你甚至可以在一条推文中放入这么小的应用程序!

接下来,安装Spring Boot的CLI
通过运行以下命令运行Groovy应用程序:

$ spring run app.groovy

关闭上一个应用程序,以避免端口冲突。

在不同的终端窗口中,运行以下curl命令(显示其输出):

$ curl localhost:8080
Hello, World!

Spring Boot通过向代码中动态添加关键注释,并使用Groovy Grape下拉运行应用程序所需的库来实现这一点。

总结

祝贺您使用Spring Boot构建了一个简单的web应用程序,并学习了如何加快开发速度。您还打开了一些方便的生产服务。这只是Spring Boot所能做的一小部分。更多信息请参阅Spring Boot的在线文档。

另请参见

以下指南也可能有帮助:

想编写新的指南或对现有指南做出贡献?查看我们的 投稿指南

所有指南都附有代码的ASLv2许可证和写作的署名、NoDerivatives创作共用许可证。


官网原文地址:https://spring.io/guides/gs/spring-boot/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值