由於公司最近在做技術轉型(從.Net轉Java),因此自己也開啟了學習Java之路。學習Java怎麼能不學習這幾年這麼火的Spring Boot框架,由於自己有總結的習慣,因此會把學習的過程以部落格的形式分享出來,
一來加深自己理解,二來希望能幫助到有需要的同學。
文章中如有不對之處,歡迎各位指出,屆時我會及時修改。
1.建立Spring Boot專案
說明:我這裡使用的開發軟體是IDEA。
首先在啟動頁選擇"Create New Project"

然後左側選中“Spring Initializr”,右側選擇好SDK的版本,然後點選“Next”

這裡首先會看到預設的專案資訊

按照自己的需要修改Group(可理解為組織,一般為域名反過來,如zwwhnly.com,這裡就是com.zwwhnly)和Artifact(可理解為專案名)
我這裡將Group修改為:com.zwwhnly
Artifact修改為:springbootdemo
然後點選下一步“Next”

這裡我們先選擇好依賴項“Web”和Spring Boot的版本,如圖預設為2.1.2,
然後點選下一步“Next”

修改好專案名稱和專案路徑後,點選完成“Finish”,如果路徑不存在,可能會提示你是否要自動建立目錄,點選OK即可

因為要載入一些依賴項,需要等一會才能建立成功,專案建立好的結構為:

找到啟動類SpringbootdemoApplication(一般為Group+Artifact+Application),看到預設程式碼如下:
package com.zwwhnly.springbootdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootdemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootdemoApplication.class, args);
}
}
複製程式碼
在啟動類中右鍵,執行專案,看到如下資訊

開啟瀏覽器,輸入:http://localhost:8080/,會看到如下頁面

暫時在啟動類中寫一個介面對映, 如下所示:
package com.zwwhnly.springbootdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication
public class SpringbootdemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootdemoApplication.class, args);
}
@RequestMapping
public String hello() {
return "Hello Spring Boot!";
}
}
複製程式碼
再次執行專案,訪問http://localhost:8080/,會看到如下資訊,代表專案可以成功訪問。

說明:關於@RestController和@RequestMapping在後續部落格中講解。
2.關閉Banner
其實剛剛專案啟動時我們已經看到了Spring Boot的Banner,那麼你不禁要問什麼是Spring Boot的Banner呢?其實就是下圖中紅色標記的地方

也許有人會覺得每次啟動都顯示這些資訊並沒有實際意義,那麼我們如何關閉它呢?
方式1:修改啟動類main方法程式碼
原始碼:
SpringApplication.run(SpringbootdemoApplication.class, args);
複製程式碼
修改後:
SpringApplication springApplication = new SpringApplication(SpringbootdemoApplication.class);
springApplication.setBannerMode(Banner.Mode.OFF);
springApplication.run(args);
複製程式碼
方式2:修改application.properties檔案
預設情況下,新建的專案裡application.properties檔案是空的,增加如下配置:
spring.main.banner-mode=off
複製程式碼
關閉後的效果如下圖所示:

個人建議通過方式2修改配置檔案的方式關閉。
3.使用yaml配置檔案
Spring Boot預設生成的配置檔案為application.properties,其實application.yml和application.properties差別並不大,只是層次結構明顯,可讀性更強,因此目前使用的更多一些。
我們假設本來application.properties的配置為:
server.port=8082
複製程式碼
那麼如何將配置檔案切換為application.yml呢?
首先刪除掉原來的預設配置檔案application.properties,新增配置檔案application.yml,新增方式如下:



修改application.yml為:
server:
port: 8082
複製程式碼

注意事項:port後面的:和8082之間是有一個空格的,不能省略
如果不小心將空格省略,其實IDEA也能識別出來,不過並不顯示錯誤,也不影響啟動,
我們現在把配置檔案修改為錯誤的(把空格省略),然後啟動專案


我們會發現專案雖然正常啟動成功,不過配置的埠號8082並未生效,啟動的還是預設的埠號8080。
因此使用yaml配置檔案一定要注意值前面的空格問題。
4.原始碼地址
github.com/zwwhnly/spr…,歡迎大家下載,有問題可以多多交流。