使用 Spring Boot 建置應用程式

本指南提供如何使用 Spring Boot 加速應用程式開發的範例。當您閱讀更多 Spring 入門指南時,您將會看到更多 Spring Boot 的使用案例。本指南旨在讓您快速體驗 Spring Boot。如果您想建立自己的 Spring Boot 專案,請造訪 Spring Initializr,填寫您的專案詳細資訊,選擇您的選項,並下載捆綁好的專案作為 zip 檔案。

您將建置的內容

您將使用 Spring Boot 建置一個簡單的 Web 應用程式,並向其添加一些有用的服務。

您需要的東西

如何完成本指南

與大多數 Spring 入門指南一樣,您可以從頭開始並完成每個步驟,或者您可以跳過您已經熟悉的基本設定步驟。無論哪種方式,您最終都會得到可運作的程式碼。

若要從頭開始,請移至 從 Spring Initializr 開始

若要跳過基礎知識,請執行以下操作

當您完成時,您可以對照 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 Initializr 開始

您可以使用這個 預先初始化的專案,然後點擊 Generate 以下載 ZIP 檔案。此專案已設定為符合本教學課程中的範例。

若要手動初始化專案

  1. 導航至 https://start.spring.io。此服務會提取應用程式所需的所有依賴項,並為您完成大部分設定。

  2. 選擇 Gradle 或 Maven 以及您要使用的語言。本指南假設您選擇了 Java。

  3. 點擊 Dependencies 並選擇 Spring Web

  4. 點擊 Generate

  5. 下載產生的 ZIP 檔案,這是一個使用您的選擇設定的 Web 應用程式的封存檔。

如果您的 IDE 具有 Spring Initializr 整合,您可以從您的 IDE 完成此流程。
您也可以從 Github 分支專案,並在您的 IDE 或其他編輯器中開啟它。
對於 Spring 3.0,無論您是否使用 Spring Initializr,您都需要 Java 17 或更高版本。

建立簡單的 Web 應用程式

現在您可以為簡單的 Web 應用程式建立 Web 控制器,如下列清單(來自 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!";
	}

}

該類別被標記為 @RestController,表示它已準備好供 Spring MVC 使用以處理 Web 請求。@GetMapping/ 映射到 index() 方法。當從瀏覽器或使用命令列上的 curl 調用時,該方法會傳回純文字。這是因為 @RestController 結合了 @Controller@ResponseBody,這兩個註解會導致 Web 請求傳回資料而不是視圖。

建立應用程式類別

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。例如,如果 spring-webmvc 在類別路徑上,則此註解會將應用程式標記為 Web 應用程式,並啟動關鍵行為,例如設定 DispatcherServlet

  • @ComponentScan:告訴 Spring 在 com/example 套件中尋找其他組件、組態和服務,使其能夠找到控制器。

main() 方法使用 Spring Boot 的 SpringApplication.run() 方法來啟動應用程式。您是否注意到沒有單行 XML?也沒有 web.xml 檔案。此 Web 應用程式是 100% 純 Java,您不必處理設定任何管道或基礎架構。

還有一個標記為 @BeanCommandLineRunner 方法,它會在啟動時執行。它會檢索由您的應用程式建立或由 Spring Boot 自動新增的所有 bean。它會對它們進行排序並列印出來。

執行應用程式

若要執行應用程式,請在終端機視窗(在 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.autoconfigure bean。還有一個 tomcatEmbeddedServletContainerFactory

現在使用 curl 執行服務(在單獨的終端機視窗中),方法是執行以下命令(顯示其輸出)

$ curl http://localhost:8080
Greetings from Spring Boot!

新增單元測試

您會想要為您新增的端點新增測試,而 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 請求和回應,如下列清單(來自 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 請求傳送到 DispatcherServlet 中,並對結果做出斷言。請注意使用 @AutoConfigureMockMvc@SpringBootTest 來注入 MockMvc 實例。使用 @SpringBootTest 後,我們要求建立整個應用程式內容。另一種方法是要求 Spring Boot 僅使用 @WebMvcTest 建立內容的 Web 層。在任一種情況下,Spring Boot 都會自動嘗試定位應用程式的主要應用程式類別,但如果您想建置不同的內容,您可以覆寫或縮小它。

除了模擬 HTTP 請求週期之外,您還可以使用 Spring Boot 來編寫簡單的完整堆疊整合測試。例如,我們可以建立以下測試(來自 src/test/java/com/example/springboot/HelloControllerITest.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 HelloControllerITest {

	@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 透過其 actuator 模組提供了多種此類服務(例如健康檢查、稽核、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

actuator 公開了以下內容

還有一個 /actuator/shutdown 端點,但預設情況下,它僅透過 JMX 可見。若要 將其啟用為 HTTP 端點,請將 management.endpoint.shutdown.enabled=true 新增到您的 application.properties 檔案中,並使用 management.endpoints.web.exposure.include=health,info,shutdown 公開它。但是,您可能不應該為公開可用的應用程式啟用關閉端點。

您可以透過執行以下命令來檢查應用程式的健康狀況

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

您也可以嘗試透過 curl 調用 shutdown,以查看當您沒有將必要的行(在前述註釋中顯示)新增到 application.properties 時會發生什麼情況

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

由於我們沒有啟用它,因此請求的端點不可用(因為該端點不存在)。

有關這些 REST 端點中的每一個的更多詳細資訊,以及如何使用 application.properties 檔案(在 src/main/resources 中)調整其設定,請參閱 有關端點的文件

檢視 Spring Boot 的 Starters

您已經看過一些 Spring Boot 的「starters」。您可以在 此處的原始碼中查看所有這些 starter。

JAR 支援

最後一個範例展示了 Spring Boot 如何讓您連接您可能不知道自己需要的 bean。它還展示了如何開啟方便的管理服務。

但是,Spring Boot 不僅僅做到這些。它不僅支援傳統的 WAR 檔案部署,還讓您可以將可執行 JAR 組合在一起,這要歸功於 Spring Boot 的 loader 模組。各種指南透過 spring-boot-gradle-pluginspring-boot-maven-plugin 展示了這種雙重支援。

摘要

恭喜!您使用 Spring Boot 建置了一個簡單的 Web 應用程式,並了解了它如何加速您的開發步調。您還啟用了某些方便的生產服務。這只是 Spring Boot 功能的一小部分範例。有關更多資訊,請參閱 Spring Boot 的線上文件

另請參閱

以下指南也可能有所幫助

想要編寫新的指南或貢獻現有指南嗎?請查看我們的 貢獻指南

所有指南均以 ASLv2 授權發布程式碼,並以 署名-禁止改作創用 CC 授權條款 發布寫作內容。

取得程式碼

免費

在雲端中工作

在 Spring Academy 的雲端中完成本指南。

前往 Spring Academy