你們要的乾貨來了——實戰 Spring Boot

摘星不想說話發表於2019-05-13

什麼是 Spring Boot

Spring 在官方首頁這樣介紹:

BUILD ANYTHING . Spring Boot is designed to get you up and running as quickly as possible, with minimal upfront configuration of Spring. Spring Boot takes an opinionated view of building production ready applications.

解釋一下:Spring Boot 可以構建一切。Spring Boot 設計之初就是為了最少的配置,最快的速度來啟動和執行 Spring 專案。Spring Boot 使用特定的配置來構建生產就緒型的專案。

使用 Spring Boot 有什麼好處

其實就是簡單、快速、方便!如果搭建一個 Spring Web 專案的時候需要怎麼做呢?

  • 配置 web.xml,載入 Spring 和 Spring MVC
  • 配置資料庫連線、配置 Spring 事務
  • 載入配置檔案的讀取,開啟註解
  • 配置日誌檔案
  • 配置完成之後部署 Tomcat 除錯

現在非常流行微服務,如果我這個專案僅僅只是需要傳送一個郵件,如果我的專案僅僅是生產一個積分;我都需要這樣折騰一遍!

但是如果使用 Spring Boot 呢?很簡單,僅僅只需要三步就可以快速的搭建起一個 Web 專案!

使用 Spring Boot 到底有多爽,用下面這幅圖來表達:

你們要的乾貨來了——實戰 Spring Boot

快速入門

說了那麼多,手癢癢的很,馬上來一發試試!

構建專案

(1)訪問 http://start.spring.io/。

(2)選擇構建工具 Maven Project、Spring Boot 版本 1.5.8 及一些工程基本資訊,可參考下圖:

你們要的乾貨來了——實戰 Spring Boot

(3)單擊 Generate Project 按鈕並下載專案壓縮包。

(4)解壓後,單擊 Eclipse,Import | Existing Maven Projects | Next | 選擇解壓後的資料夾 | Finsh 命令,OK Done!

(5)如果使用的是 Idea,單擊 File | New | Model from Existing Source.. | 選擇解壓後的資料夾 | OK 命令, 選擇 Maven ,一路 Next,OK Done!

如果讀者使用的是 Idea 工具,也可以這樣:

(1)單擊 File | New | Project… 命令,彈出新建專案框。

(2)選擇 Spring Initializr 選項,單擊 Next 按鈕,也會出現上述類似的配置介面,Idea 幫我們做了整合。

(3)填寫相關內容後,單擊 Next 按鈕,選擇依賴的包再單擊 Next 按鈕,最後確定資訊無誤單擊 Finish 按鈕。

對上面的配置做一個解釋:

  • 第一個選擇框選擇建立以 Maven 構建專案,還是以 Gradle 構建專案,這是兩種不同的構建方式,其中 Gradel 配置內容更簡潔一些,並且包含了 Maven 的使用,不過日常使用 Maven 居多。
  • 第二個選擇框選擇程式語言,現在支援 Java、Kotlin 和 Groovy。
  • 第三個選擇框選擇 Spring Boot 版本,可以看出 Spring Boot 2.0 已經到了第五個里程碑了。在實際使用中,我們會優先使用穩定版本,1.0 的最新穩定版本是 1.5.8,也是我們演示使用的版本。

下面就是專案的配置資訊了。

  • Group:一般填寫公司域名,比如百度公司填 com.baidu,演示使用 com.neo。
  • Artifact:可以理解為專案的名稱,可以根據實際情況來填,本次演示填寫 helloWorld。
  • Dependencies:在這塊新增我們專案所依賴的 Spring Boot 元件,可以多選。本次選擇 Web、devtools 兩個模組。

專案結構介紹

你們要的乾貨來了——實戰 Spring Boot

如上圖所示,Spring Boot 的基礎結構共三個檔案:

  • src/main/java:程式開發以及主程式入口
  • src/main/resources:配置檔案
  • src/test/java:測試程式

另外,Sping Boot 建議的目錄結果如下:

root package 結構:com.example.myproject

``` xml myproject +-src +- main +- java +- com.example.myproject +- comm +- domain +- repository +- service +- web +- Application.java +- resources +- static +- templates +- application.properties +- test +-pom.xml

com.example.myproject 目錄下:- Application.java:建議放到根目錄下面,是專案的啟動類,Spring Boot 專案只能有一個 main() 方法。- comm:目錄建議放置公共的類,如全域性的配置檔案、工具類等。- domain:目錄主要用於實體(Entity)與資料訪問層(Repository)。- repository:資料庫訪問層程式碼。- service:該層主要是業務類程式碼。- web:該層負責頁面訪問控制。resources 目錄下:- static:目錄存放 Web 訪問的靜態資源,如 JS、CSS、圖片等。- templates:目錄存放頁面模板。- application.properties:專案的配置資訊。test 目錄存放單元測試的程式碼;pom.xml 用於配置專案依賴包,以及其他配置。採用預設配置可以省去很多設定,當然也可以根據自己的喜好來進行更改。最後,啟動 Application main 方法,至此一個 Java 專案搭建好了!### 簡單 Web 開發(1)可以在 Spring Initializr 上面新增,也可以手動在 pom.xml 中新增: 複製程式碼

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

pom.xml 檔案中預設有兩個模組:- spring-boot-starter:核心模組,包括自動配置支援、日誌和 YAML;- spring-boot-starter-test:測試模組,包括 JUnit、Hamcrest、Mockito。 (2)編寫 controller 內容:複製程式碼

java @RestController public class HelloWorldController {

@RequestMapping("/hello")public String hello() { return "Hello World";}複製程式碼

}

`@RestController` 的意思就是 controller 裡面的方法都以 json 格式輸出,不用再配置什麼 jackjson 的了!如果配置為`@Controller` 就代表著輸出為頁面內容。(3)啟動主程式,開啟瀏覽器訪問 [http://localhost:8080/hello](http://localhost:8080/hello),就可以看到以下內容,是不是很簡單!複製程式碼

Hello World

(4)如果我們想傳入引數怎麼辦?複製程式碼

java @RestController public class HelloWorldController {

@RequestMapping("/hello")public String index(String name) { return "Hello World, " +name;}複製程式碼

}

重新啟動專案,訪問 [http://localhost:8080/hello?name=neo](http://localhost:8080/hello?name=neo),返回內容如下:複製程式碼

Hello World,neo

經過上一個測試發現,修改 controller 內相關程式碼,就需要重新啟動專案才能生效,這樣做很麻煩是不是,彆著急。Spring Boot 提供了另外一個元件來解決。#### 熱部署熱啟動就需要用到我們在一開始引入的另外一個元件:devtools。它是 Spring Boot 提供的一組開發工具包,其中就包含我們需要的熱部署功能。但是在使用這個功能之前還需要再做一些配置。(1)在 dependency 中新增 optional 屬性,並設定為 true:複製程式碼

xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies>

(2)在 plugin 中配置另外一個屬性 fork,並且配置為 true複製程式碼

xml <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 還需要做以下配置。(3)配置 Idea選擇 File-Settings-Compiler 勾選 ```Build project automatically```,低版本 Idea 勾選 ```make project automatically```。![](http://www.ityouknow.com/assets/images/2017/chat/springboot3.png)使用快捷鍵:`CTRL + SHIFT + A` 輸入` Registry` 找到選項 `compile.automake.allow.when.app.running` 勾選![](http://www.ityouknow.com/assets/images/2017/chat/springboot4.png)全部配置完成後,Idea 就支援熱部署了,大家可以試著去改動一下程式碼就會發現 Spring Boot 會自動重新載入,再也不需要我們手動點選重新部署了。為什麼 Idea 需要多配置後面這一步呢,因為 Idea 預設不是自動編譯的,需要我們手動去配置後才會自動編譯,而熱部署依賴於專案的自動編譯功能。> 該模組在完整的打包環境下執行的時候會被禁用。如果使用 java -jar 啟動應用或者用一個特定的 classloader 啟動,它會認為這是一個“生產環境”。### 單元測試單元測試在日常開發中是必不可少的,一個牛逼的程式設計師,單元測試寫得也是槓槓的。下面來看下 Spring Boot 對單元測試又做了哪些支援?如果我們只想執行一個 hello World,只需要一個註解就可以。在 src/test 目錄下新建一個 HelloTests 類,程式碼如下:複製程式碼

java public class HelloTest { @Test public void hello(){ System.out.println("hello world"); } }

單擊右鍵“執行”按鈕,會發現控制檯輸出:hello world。僅僅只需要了一個註解。但是如果我們需要測試 web 層的請求呢?Spring Boot 也給出了支援。以往我們在測試 web 請求的時候,需要手動輸入相關引數在頁面測試檢視效果,或者自己寫 post 請求。在 Spring Boot 中,Spring 給出了一個簡單的解決方案;使用 mockmvc 進行 web 測試,mockmvc 內建了很多工具類和方法,可以模擬 post、get 請求,並且判斷返回的結果是否正確等,也可以利用`print()`列印執行結果。複製程式碼

java @SpringBootTest public class HelloTest {

private MockMvc mockMvc;@Beforepublic void setUp() throws Exception { mockMvc = MockMvcBuilders.standaloneSetup(new HelloWorldController()).build();}@Testpublic void getHello() throws Exception { mockMvc.perform(MockMvcRequestBuilders.post("/hello?name=小明").accept(MediaType.APPLICATION_JSON_UTF8)).andDo(print());}複製程式碼

}

在類的上面新增`@SpringBootTest`,系統會自動載入 Spring Boot 容器。在日常測試中,我們就可以注入 bean 來做一些區域性業務的測試。`MockMvcRequestBuilders`可以 post、get 請求,使用`print()`方法會將請求和相應的過程都列印出來,如下:複製程式碼

text MockHttpServletRequest: HTTP Method = POST Request URI = /hello Parameters = {name=[neo]} Headers = {}

Handler: Type = com.neo.helloWorld.web.HelloWorldController Method = public java.lang.String com.neo.helloWorld.web.HelloWorldController.hello(java.lang.String)

MockHttpServletResponse: Status = 200 Error message = null Headers = {Content-Type=[text/plain;charset=ISO-8859-1], Content-Length=[16]} Content type = text/plain;charset=ISO-8859-1 Body = Hello World ,neo Forwarded URL = null Redirected URL = null Cookies = [] ```

從返回的Body = Hello World ,neo可以看出請求成功。

總結

使用 Spring Boot 可以非常方便、快速搭建專案,而不用關心框架之間的相容性、適用版本等各種問題,我們想使用任何東西,僅僅新增一個配置就可以,所以使用 Sping Boot 非常適合構建微服務。

 順便在此給大家推薦一個Java架構方面的交流學習qq群:834962734,裡面有:Spring,MyBatis,Netty原始碼分析,高併發、高效能、分散式、微服務架構的原理,JVM效能優化這些成為架構師必備的知識體系,進群馬上免費領取學習資源!

相關文章