使用 Spring Boot 构建应用程序

本文涉及的产品
轻量应用服务器 2vCPU 4GiB,适用于搭建容器环境
轻量应用服务器 2vCPU 4GiB,适用于搭建Web应用/小程序
轻量应用服务器 2vCPU 1GiB,适用于搭建电商独立站
简介: 本指南提供了 Spring Boot 如何帮助您加速应用程序开发的示例。

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

一、所需条件:

  • 约15分钟
  • 最喜欢的文本编辑器或 IDE
  • Java 17 或更高版本
  • Gradle 7.5+ 或 Maven 3.5+
  • 您也可以将代码直接导入到 IDE 中:

二、如何完成本指南

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

从头开始,请继续从 Spring Initializr 开始

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

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

三、了解 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 会自动将 添加到您的应用程序上下文中。但是,如果您使用自己的设置定义自己的设置,则 Spring Boot 不会添加一个。这使您无需付出任何努力即可进行控制。SpringTemplateEngineSpringTemplateEngine

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

四、从 Spring Initializr 开始

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

要手动初始化项目,请执行以下操作:

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

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

五、创建简单的 Web 应用程序

现在,您可以为简单的 Web 应用程序创建一个 Web 控制器,如下面的清单 (from ) 所示:src/main/java/com/example/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!";
    }
}

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

  1. 创建 Application 类

Spring Initializr 为您创建了一个简单的应用程序类。但是,在这种情况下,它太简单了。您需要修改应用程序类以匹配以下列表(来自):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:告诉 Spring Boot 根据类路径设置、其他 Bean 和各种属性设置开始添加 bean。例如,如果位于类路径上,则此注释会将应用程序标记为 Web 应用程序并激活关键行为,例如设置 .spring-webmvcDispatcherServlet
  • @ComponentScan:告诉 Spring 在包中查找其他组件、配置和服务,让它找到控制器。com/example

该方法使用 Spring Boot 的方法启动应用程序。您是否注意到没有一行 XML?也没有文件。这个 Web 应用程序是 100% 纯 Java,您不必处理配置任何管道或基础设施。main()SpringApplication.run()web.xml

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

  1. 运行应用程序

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

./gradlew bootRun

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

./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.autoconfiguretomcatEmbeddedServletContainerFactory

现在,通过运行以下命令(如其输出所示),使用 curl(在单独的终端窗口中)运行服务:

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

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

如果您使用 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 请求和响应,如以下清单 (from ) 所示: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来自 Spring Test,允许您通过一组方便的构建器类将 HTTP 请求发送到 并对结果进行断言。请注意 和 的用法,以注入实例。使用 后,我们要求创建整个应用程序上下文。另一种方法是要求 Spring Boot 使用 仅创建上下文的 Web 层。无论哪种情况,Spring Boot 都会自动尝试查找应用程序的主应用程序类,但如果您想构建不同的内容,您可以覆盖它或缩小范围。DispatcherServlet@AutoConfigureMockMvc@SpringBootTestMockMvc@SpringBootTest@WebMvcTest

除了模拟 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!");
    }
}

嵌入式服务器在随机端口上启动,因为 ,而实际端口是在 的基 URL 中自动配置的。webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORTTestRestTemplate

  1. 添加生产级服务

如果您正在为您的企业构建网站,您可能需要添加一些管理服务。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,请在终端窗口(在目录中)运行以下命令:complete

./gradlew bootRun

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

./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

执行器公开以下内容:

还有一个端点,但默认情况下,它只能通过 JMX 可见。要将其启用为 HTTP 端点,请添加到您的文件中并使用 .但是,您可能不应为公开可用的应用程序启用关闭终结点。

还有一个端点,但默认情况下,它只能通过 JMX 可见。要将其启用为 HTTP 端点,请添加到您的文件中并使用 .但是,您可能不应为公开可用的应用程序启用关闭终结点。/actuator/shutdownmanagement.endpoint.shutdown.enabled=trueapplication.propertiesmanagement/actuator/shutdownmanagement.endpoint.shutdown.enabled=trueapplication.propertiesmanagement.endpoints.web.exposure.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 端点以及如何使用文件调整其设置的更多详细信息 (in ),请参阅有关端点的文档application.propertiessrc/main/resources

  1. 查看 Spring Boot 的启动器

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

  1. JAR 支持

最后一个示例展示了 Spring Boot 如何让您连接您可能不知道自己需要的 bean。它还展示了如何打开便捷的管理服务。

但是,Spring Boot 的功能远不止于此。它不仅支持传统的 WAR 文件部署,还允许您将可执行的 JAR 放在一起,这要归功于 Spring Boot 的加载器模块。各种指南通过 和 演示了这种双重支持。spring-boot-gradle-pluginspring-boot-maven-plugin

参考

以下是本文参考的详细链接:

wukaipeng.notion.site/3c2bf227dab…

好啦!小弹的分享到此为止。我们更欢迎您分享您对阿里云产品的设想、对功能的建议或者各种吐槽,请扫描提交问卷并获得社区积分或精美礼品一份。https://survey.aliyun.com/apps/zhiliao/P4y44bm_8

【扫码填写上方调研问卷】

欢迎每位来到弹性计算的开发者们来反馈问题哦~


相关文章
|
18天前
|
存储 NoSQL Java
使用Java和Spring Data构建数据访问层
本文介绍了如何使用 Java 和 Spring Data 构建数据访问层的完整过程。通过创建实体类、存储库接口、服务类和控制器类,实现了对数据库的基本操作。这种方法不仅简化了数据访问层的开发,还提高了代码的可维护性和可读性。通过合理使用 Spring Data 提供的功能,可以大幅提升开发效率。
61 21
|
30天前
|
监控 Java API
【潜意识Java】使用SpringBoot构建高效的RESTfulAPI
本文介绍了使用Spring Boot构建RESTful API的完整流程,涵盖从项目创建到API测试的各个步骤。
49 1
|
2月前
|
人工智能 前端开发 Java
Spring AI Alibaba + 通义千问,开发AI应用如此简单!!!
本文介绍了如何使用Spring AI Alibaba开发一个简单的AI对话应用。通过引入`spring-ai-alibaba-starter`依赖和配置API密钥,结合Spring Boot项目,只需几行代码即可实现与AI模型的交互。具体步骤包括创建Spring Boot项目、编写Controller处理对话请求以及前端页面展示对话内容。此外,文章还介绍了如何通过添加对话记忆功能,使AI能够理解上下文并进行连贯对话。最后,总结了Spring AI为Java开发者带来的便利,简化了AI应用的开发流程。
909 0
|
2月前
|
前端开发 Java 开发者
这款免费 IDEA 插件让你开发 Spring 程序更简单
Feign-Helper 是一款支持 Spring 框架的 IDEA 免费插件,提供 URL 快速搜索、Spring Web Controller 路径一键复制及 Feign 与 Controller 接口互相导航等功能,极大提升了开发效率。
|
2月前
|
XML 前端开发 安全
Spring MVC:深入理解与应用实践
Spring MVC是Spring框架提供的一个用于构建Web应用程序的Model-View-Controller(MVC)实现。它通过分离业务逻辑、数据、显示来组织代码,使得Web应用程序的开发变得更加简洁和高效。本文将从概述、功能点、背景、业务点、底层原理等多个方面深入剖析Spring MVC,并通过多个Java示例展示其应用实践,同时指出对应实践的优缺点。
129 2
|
2月前
|
XML Java 数据格式
Spring Core核心类库的功能与应用实践分析
【12月更文挑战第1天】大家好,今天我们来聊聊Spring Core这个强大的核心类库。Spring Core作为Spring框架的基础,提供了控制反转(IOC)和依赖注入(DI)等核心功能,以及企业级功能,如JNDI和定时任务等。通过本文,我们将从概述、功能点、背景、业务点、底层原理等多个方面深入剖析Spring Core,并通过多个Java示例展示其应用实践,同时指出对应实践的优缺点。
75 14
|
2月前
|
Java 应用服务中间件 Docker
将基于 Spring 的 WAR 应用程序部署到 Docker:详尽指南
将基于 Spring 的 WAR 应用程序部署到 Docker:详尽指南
55 2
|
2月前
|
消息中间件 监控 Java
如何将Spring Boot + RabbitMQ应用程序部署到Pivotal Cloud Foundry (PCF)
如何将Spring Boot + RabbitMQ应用程序部署到Pivotal Cloud Foundry (PCF)
48 6
|
2月前
|
Java 关系型数据库 MySQL
如何将Spring Boot + MySQL应用程序部署到Pivotal Cloud Foundry (PCF)
如何将Spring Boot + MySQL应用程序部署到Pivotal Cloud Foundry (PCF)
81 5
|
2月前
|
缓存 监控 Java
如何将Spring Boot应用程序部署到Pivotal Cloud Foundry (PCF)
如何将Spring Boot应用程序部署到Pivotal Cloud Foundry (PCF)
60 5