
本指南提供了如何彈簧啟動?幫助您加速應用程序開發。隨著您閱讀更多 Spring 入門指南,您將看到更多 Spring Boot 的用例。本指南旨在讓您快速體驗Spring Boot。如果您想創建自己的基于 Spring 引導的項目,請訪問Spring Initializr,填寫您的項目詳細信息,選擇您的選項,然后將捆綁的項目下載為 zip 文件。
您將使用 Spring Boot 構建一個簡單的 Web 應用程序,并向其添加一些有用的服務。
像大多數春天一樣入門指南,您可以從頭開始并完成每個步驟,也可以繞過您已經熟悉的基本設置步驟。無論哪種方式,您最終都會得到工作代碼。
【資料圖】
要從頭開始,請繼續從 Spring 初始化開始.
要跳過基礎知識,請執行以下操作:
下載并解壓縮本指南的源存儲庫,或使用吉特:git clonehttps://github.com/spring-guides/gs-spring-boot.git
光盤成gs-spring-boot/initial
跳轉到創建簡單的 Web 應用程序.完成后,您可以根據 中的代碼檢查結果。??gs-spring-boot/complete?
?
Spring Boot 提供了一種構建應用程序的快速方法。它會查看您的類路徑和您配置的 bean,對您缺少的內容做出合理的假設,并添加這些項。使用 Spring Boot,您可以更多地關注業務功能,而不是基礎設施。
以下示例顯示了 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 會自動將 a 添加到您的應用程序上下文中。但是,如果您使用自己的設置定義自己的設置,Spring Boot 不會添加一個。這使您無需付出任何努力即可控制。??SpringTemplateEngine?
???SpringTemplateEngine?
?
Spring Boot 不會生成代碼或編輯您的文件。相反,當您啟動應用程序時,Spring Boot 會動態連接 bean 和設置,并將它們應用于您的應用程序上下文。 |
你可以使用這個預初始化項目,然后單擊生成以下載 ZIP 文件。此項目配置為適合本教程中的示例。
手動初始化項目:
導航到https://start.spring.io.此服務拉入應用程序所需的所有依賴項,并為您完成大部分設置。選擇 Gradle 或 Maven 以及您要使用的語言。本指南假定您選擇了 Java。單擊“依賴關系”,然后選擇“Spring Web”。單擊生成。下載生成的 ZIP 文件,該文件是配置了您選擇的 Web 應用程序的存檔。如果您的 IDE 集成了 Spring Initializr,則可以從 IDE 完成此過程。 |
您也可以從 Github 分叉項目,然后在 IDE 或其他編輯器中打開它。 |
現在,您可以為簡單的 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;@RestControllerpublic class HelloController { @GetMapping("/") public String index() { return "Greetings from Spring Boot!"; }}
該類被標記為 ,這意味著它已準備好被 Spring MVC 用于處理 Web 請求。 映射到方法。從瀏覽器調用或在命令行上使用 curl 調用時,該方法返回純文本。這是因為將 和 兩個注釋組合在一起,導致 Web 請求返回數據而不是視圖。??@RestController?
???@GetMapping?
???/?
???index()?
???@RestController?
???@Controller?
???@ResponseBody?
?
Spring 初始化器為您創建一個簡單的應用程序類。但是,在這種情況下,它太簡單了。您需要修改應用程序類以匹配以下清單(來自):??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;@SpringBootApplicationpublic 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 引導根據類路徑設置、其他 bean 和各種屬性設置開始添加 bean。例如,如果 在類路徑上,則此注釋會將應用程序標記為 Web 應用程序并激活關鍵行為,例如設置 .spring-webmvc
DispatcherServlet
??@ComponentScan?
?:告訴 Spring 在包中查找其他組件、配置和服務,讓它找到控制器。com/example
該方法使用 Spring Boot 的方法啟動應用程序。您是否注意到沒有一行 XML?也沒有文件。此 Web 應用程序是 100% 純 Java,您無需處理配置任何管道或基礎結構。??main()?
???SpringApplication.run()?
???web.xml?
?
還有一個標記為 的方法,該方法在啟動時運行。它檢索由您的應用程序創建或由 Spring Boot 自動添加的所有 bean。它對它們進行排序并打印出來。??CommandLineRunner?
???@Bean?
?
To run the application, run the following command in a terminal window (in the) directory:??complete?
?
./gradlew bootRun
If you use Maven, run the following command in a terminal window (in the) directory:??complete?
?
./mvnw spring-boot:run
You should see output similar to the following:
Let"s inspect the beans provided by Spring Boot:applicationbeanNameHandlerMappingdefaultServletHandlerMappingdispatcherServletembeddedServletContainerCustomizerBeanPostProcessorhandlerExceptionResolverhelloControllerhttpRequestHandlerAdaptermessageSourcemvcContentNegotiationManagermvcConversionServicemvcValidatororg.springframework.boot.autoconfigure.MessageSourceAutoConfigurationorg.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfigurationorg.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfigurationorg.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$DispatcherServletConfigurationorg.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration$EmbeddedTomcatorg.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfigurationorg.springframework.boot.context.embedded.properties.ServerPropertiesorg.springframework.context.annotation.ConfigurationClassPostProcessor.enhancedConfigurationProcessororg.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessororg.springframework.context.annotation.internalAutowiredAnnotationProcessororg.springframework.context.annotation.internalCommonAnnotationProcessororg.springframework.context.annotation.internalConfigurationAnnotationProcessororg.springframework.context.annotation.internalRequiredAnnotationProcessororg.springframework.web.servlet.config.annotation.DelegatingWebMvcConfigurationpropertySourcesBinderpropertySourcesPlaceholderConfigurerrequestMappingHandlerAdapterrequestMappingHandlerMappingresourceHandlerMappingsimpleControllerHandlerAdaptertomcatEmbeddedServletContainerFactoryviewControllerHandlerMapping
You can clearly seebeans. There is also a.??org.springframework.boot.autoconfigure?
???tomcatEmbeddedServletContainerFactory?
?
現在使用 curl 運行服務(在單獨的終端窗口中),通過運行以下命令(與其輸出一起顯示):
$ curl localhost:8080Greetings from Spring Boot!
您需要為添加的端點添加測試,Spring Test為此提供了一些機制。
如果您使用 Gradle,請將以下依賴項添加到您的文件中:??build.gradle?
?
testImplementation("org.springframework.boot:spring-boot-starter-test")
如果使用 Maven,請將以下內容添加到文件中:??pom.xml?
?
org.springframework.boot spring-boot-starter-test test
現在編寫一個簡單的單元測試,通過端點模擬 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@AutoConfigureMockMvcpublic 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 引導通過使用 僅創建上下文的 Web 層。無論哪種情況,Spring Boot 都會自動嘗試查找應用程序的主應用程序類,但如果您想構建不同的東西,您可以覆蓋它或縮小它的范圍。??DispatcherServlet?
???@AutoConfigureMockMvc?
???@SpringBootTest?
???MockMvc?
???@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 { ResponseEntityresponse = template.getForEntity("/", String.class); assertThat(response.getBody()).isEqualTo("Greetings from Spring Boot!"); }}
嵌入式服務器由于 而從隨機端口啟動,實際端口在 的基本 URL 中自動配置。??webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT?
???TestRestTemplate?
?
如果您正在為您的企業構建網站,您可能需要添加一些管理服務。Spring Boot 提供了幾種這樣的服務(例如健康、審計、豆類等),其執行器模塊.
如果您使用 Gradle,請將以下依賴項添加到您的文件中:??build.gradle?
?
implementation "org.springframework.boot:spring-boot-starter-actuator"
如果使用 Maven,請將以下依賴項添加到文件中:??pom.xml?
?
org.springframework.boot spring-boot-starter-actuator
然后重新啟動應用程序。如果您使用 Gradle,請在終端窗口(在目錄中)中運行以下命令:??complete?
?
./gradlew bootRun
如果使用 Maven,請在終端窗口(在目錄中)中運行以下命令:??complete?
?
./mvnw spring-boot:run
您應該看到一組新的 RESTful 端點已添加到應用程序中。這些是Spring Boot提供的管理服務。以下清單顯示了典型輸出:
management.endpoint.configprops-org.springframework.boot.actuate.autoconfigure.context.properties.ConfigurationPropertiesReportEndpointPropertiesmanagement.endpoint.env-org.springframework.boot.actuate.autoconfigure.env.EnvironmentEndpointPropertiesmanagement.endpoint.health-org.springframework.boot.actuate.autoconfigure.health.HealthEndpointPropertiesmanagement.endpoint.logfile-org.springframework.boot.actuate.autoconfigure.logging.LogFileWebEndpointPropertiesmanagement.endpoints.jmx-org.springframework.boot.actuate.autoconfigure.endpoint.jmx.JmxEndpointPropertiesmanagement.endpoints.web-org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointPropertiesmanagement.endpoints.web.cors-org.springframework.boot.actuate.autoconfigure.endpoint.web.CorsEndpointPropertiesmanagement.health.diskspace-org.springframework.boot.actuate.autoconfigure.system.DiskSpaceHealthIndicatorPropertiesmanagement.info-org.springframework.boot.actuate.autoconfigure.info.InfoContributorPropertiesmanagement.metrics-org.springframework.boot.actuate.autoconfigure.metrics.MetricsPropertiesmanagement.metrics.export.simple-org.springframework.boot.actuate.autoconfigure.metrics.export.simple.SimplePropertiesmanagement.server-org.springframework.boot.actuate.autoconfigure.web.server.ManagementServerProperties
執行器顯示以下內容:
??執行器/運行狀況????驅動器??還有一個端點,但默認情況下,它只能通過 JMX 可見。自? |
可以通過運行以下命令來檢查應用程序的運行狀況:
$ 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 如何讓您連接您可能不知道需要的 bean。它還展示了如何啟用便捷的管理服務。
然而,Spring Boot的功能遠不止于此。它不僅支持傳統的WAR文件部署,而且還允許您將可執行的JAR放在一起,這要歸功于Spring Boot的加載器模塊。各種指南通過 和 演示了這種雙重支持。??spring-boot-gradle-plugin?
???spring-boot-maven-plugin?
?
最重要的是,Spring Boot 還支持Groovy,讓你只需一個文件就可以構建Spring MVC Web應用程序。
創建一個名為的新文件,并將以下代碼放入其中:??app.groovy?
?
@RestControllerclass ThisWillActuallyRun { @GetMapping("/") String home() { return "Hello, World!" }}
文件在哪里并不重要。您甚至可以將這么小的應用程序安裝在單條推文! |
下一個安裝 Spring Boot 的 CLI.
通過運行以下命令運行 Groovy 應用程序:
$ spring run app.groovy
關閉以前的應用程序,以避免端口沖突。 |
From a different terminal window, run the following curl command (shown with its output):
$ curl localhost:8080Hello, World!
Spring Boot does this by dynamically adding key annotations to your code and usingGroovy Grapeto pull down the libraries that are needed to make the app run.
祝賀!您使用 Spring Boot 構建了一個簡單的 Web 應用程序,并了解了它如何加快您的開發速度。您還打開了一些方便的制作服務。這只是 Spring Boot 可以做的一小部分??碨pring Boot 的在線文檔以獲取更多信息。
以下指南也可能有所幫助:
保護 Web 應用程序使用 Spring MVC 提供 Web 內容想要編寫新指南或為現有指南做出貢獻?查看我們的貢獻準則.