前言
??Spring Boot 設計之初就是為了用最少的配置,以最快的速度來啟動和運行 Spring 專案,Spring Boot使用特定的配置來構建生產就緒型的專案,
Hello World
- 可以在 Spring Initializr上面添加,也可以手動在 pom.xml中添加如下代碼∶
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>Spring-boot-starter-web</artifactId>
</dependency>
pom.xml 檔案中默認有個模塊∶
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<scope>test</scope>表示依賴的組件僅僅參與測驗相關的作業,包括測驗代碼的編譯和執行,不會被打包包含進去;spring-boot-starter-test 是 Spring Boot 提供專案測驗的工具包,內置了多種測驗工具,方便我們在專案中做單元測驗、集成測驗,
2. 撰寫 Controller 內容
在目錄 src\main\java\下新建一個包:com.reminis.web,然后在該包下創建 HelloController∶
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(){
return "hello world";
}
}
- @RestControler 的意思是 Contoller 里面的方法都以JSON格式輸出,不需要有其他額外的配置;如果配置為@Controller,代表輸出內容到頁面,
- @RequestMapping("hello")提供路由資訊,"hello"路徑的HTTP Request 都會被映射到hello()方法上進行處理,
- 啟動主程式
右鍵單擊專案中的 DemoAppicationrun命令,就可以啟動專案了,若出現以下內容表示啟動成功∶

如果啟動程序中出現javaClassNotFoundException 例外,請檢查 M aven 配置是否正確,具體如下:- 檢查 Maven 的 settigs.xml檔案是否引入正確,
- 檢查 IDE 工具中的 Maven插件是否配置為本機的 Maven地址,如下圖

Spring Boot 還提供了另外兩種啟動專案的方式∶ - 在專案路徑下,使用命令列mvnspring-boot∶run來啟動,其效果和上面"啟動主程式"的效果是一致的;
- 或者將專案打包,打包后以Jar 包的形式來啟動,
# 進行專案根目錄 cd ../demo # 執行打包命令 mvn clean package # 以 Jar 包的形式啟動 java -jar target/hello-0.0.1-SNAPSHOT.jar
啟動成功后,打開瀏覽器輸入網址∶http∶//localhost:8080/hello, 就可以看到以下內容了∶

開發階段建議使用第一種方式啟動,便于開發程序中除錯,
4. 如果我們想傳入引數怎么辦?
??請求傳參一般分為URL地址傳參和表單傳參兩種方式,兩者各有優缺點,但基本都以鍵值對的方式將引數傳遞到后端,作為后端程式不用關注前端采用的那種方式,只需要根據引數的鍵來獲取值,Spring提供了很多種引數接收方式,本章我們了解最簡單的方式∶通過 URL傳參,只要后端處理請求的方法中存在引數鍵相同名稱的屬性,在請求的程序中Spring會自動將引數值賦值到屬性中,最后在方法中直接使用即可,下面我們以 hello()為例進行演示,
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello(String name) {
System.out.println("name..." + name);
return "hello world, " + name;
}
}
重新啟動專案,打開瀏覽器輸入網址 http∶//localhost8080/hello?name=reminis,回傳如下內容:

到這里,我們的第一個 Spring Boot專案就開發完成了,有沒有感覺很簡單?經過測驗發現,修改Controllr內相關的代碼,需要重新啟動專案才能生效,這樣做很麻煩是不是?別著急,Spring Boot又給我們提供了另外一個組件來解決,
熱部署
??熱啟動就需要用到一個組件∶spring-boot-devtools,它是 Spring Boot 提供的一組開發工具包,其中就包含我們需要的熱部署功能,在使用這個功能之前還需要再做一些配置,
- 添加依賴
在 pom.xml檔案中添加 spring-boot-devtools 組件,
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
在 plugin 中配置另外一個屬性 fork,并且配置為 true,
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<fork>true</fork>
</configuration>
</plugin>
</plugins>
</build>
OK,以上的配置就完成了,如果你使用的是 Eclipse 集成開發環境,那么恭喜你大功告成了;如果你使用的是 IDEA 集成開發環境,那么還需要做以下配置,配置 IDEA
選擇 File-Settings-Compiler 命令,然后勾選 Build project automati cally復選框,低版本的 IDEA請勾選make project automatically 復選框,

使用快捷鍵Ctrl+Shift+A,在輸入框中輸入 Registry,勾選 復選框∶

全部配置完成后,IDEA 就支持熱部署了,大家可以試著去改動一下代碼,等待5秒就會發現 Spring Boot會自動重新加載,再也不需要手動單擊重新啟動了,
為什么 IDEA需要多配置后面這一步呢?因為 IDEA默認不是自動編譯的,需要我們手動去配置后才會自動編譯,而熱部署依賴于專案的自動編譯功能,
該模塊在完整的打包環境下運行的時候會被禁用,如果你使用 java-jar 啟動應用或者用一個特定的classloader 啟動,它會認為這是一個"生產環境",
單元測驗
??單元測驗在我們日常開發中必不可少,一個優秀的程式員,單元測驗開發也非常完善,下面我們看下 Spring Boot 對單元測驗又做了哪些支持?
如果我們只想運行一個hello world,只需要一個@Test 注解就可以了,在src/test 目錄下新建一個 HelloTest類,代碼如下∶
public class HelloTest {
@Test
private void hello() {
System.out.println("hello world");
}
}
右鍵單擊"運行"按鈕,發現控制臺會輸出∶hello world,如果需要測驗 Web 層的請求呢? Spring Boot 也給出了支持,
以往我們在測驗 Web 請求的時候,需要手動輸入相關引數在頁面測驗查看效果,或者自己寫post 請求,在 Spring Boot體系中,Spring 給出了一個簡單的解決方案,使用 MockMVC進行 Web測驗, MockMVC內置了很多工具類和方法,可以模擬 post、get 請求,并且判斷回傳的結果是否正確等,也可以利用 print()列印執行結果,
@SpringBootTest(classes = DemoApplication.class)
class DemoApplicationTests {
private MockMvc mockMvc;
@BeforeEach
public void setUp() {
mockMvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
}
@Test
public void getHello() throws Exception {
mockMvc.perform(MockMvcRequestBuilders
.post("/hello?name=reminis")
.accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultHandlers.print());
}
}
-
@BeforeEach注解的方法表示在測驗啟動的時候優先執行,一般用作資源初始化,由于我的SpringBoot專案版本是2.4.3,集成的是Junit5,JUnit5的環境下, @BeforeEach 和@AfterEach去替代@Before和@After注解,Junit4是使用@Before和@After注解.
-
在類的上面添加@SpringBootTest,系統會自動加載 Spring Boot 容器,在日常測驗中,可以注入bean 來做一些區域的業務測驗,MockMvcRequestBuilders 可以支持 post、get 請求,使用 MockMvcResultHandlers.print() 方法會將請求和相應的程序都列印出來,具體如下∶
MockHttpServletRequest:
HTTP Method = POST
Request URI = /hello
Parameters = {name=[reminis]}
Headers = [Accept:"application/json"]
Body = <no character encoding set>
Session Attrs = {}
Handler:
Type = com.reminis.demo.controller.HelloController
Method = com.reminis.demo.controller.HelloController#hello(String)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Type:"application/json", Content-Length:"20"]
Content type = application/json
Body = hello world, reminis
Forwarded URL = null
Redirected URL = null
Cookies = []
Type = null
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 200
Error message = null
Headers = [Content-Type:"application/json", Content-Length:"20"]
Content type = application/json
Body = hello world, reminis
Forwarded URL = null
Redirected URL = null
Cookies = []
從回傳的Body= hello world ,reminis可以看出請求成功了,當然每次請求都看這么多回傳結果,不太容易識別,MockMVC提供了更多方法來判斷回傳結果,其中就有判斷回傳值,我們將上面的 getHello()方法稍稍進行改造,具體如下所示∶
@Test
public void getHello() throws Exception {
mockMvc.perform(MockMvcRequestBuilders
.post("/hello?name=reminis")
.accept(MediaType.APPLICATION_JSON))
/*.andDo(MockMvcResultHandlers.print())*/
.andExpect(MockMvcResultMatchers.content(). string(Matchers.containsString("reminis")));
}
MockMvcResultMatchers.content()這段代碼的意思是獲取到 Wceb 請求執行后的結果;Matchers.contansString("reminis"),判斷回傳的結果集中是否包含"reminis"這個字串.
我們簡單做一下對比,使用Spring Boot之前和使用之后,使用 Spring Boot 前∶
- 配置 web.xml,加載Spring和 Spring MVC
- 配置資料庫連接、配置 Spring 事務
- 配置加載組態檔的讀取,開啟注解
- 配置日志檔案
- 配置完成之后部署 Tomcat 除錯
- 使用Spring Boot之后,僅僅三步即可快速搭建起一個Web專案∶
- 頁面配置匯入到開發工具中
- 進行代碼撰寫
- 運行
通過對比可以發現Spring Boot在開發階段做了大量優化,非常容易快速構建一個專案,
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/266925.html
標籤:其他
上一篇:JavaSE總結
