1. 程式人生 > >SpringBoot2學習筆記(一)SpringBoot基礎入門

SpringBoot2學習筆記(一)SpringBoot基礎入門

看完了Spring Boot 2精髓這本書,打算寫一系列Spring Boot的文章做下總結。這本書在網上的評價偏低,其中作者常推銷自己的輪子是一方面原因,但我認為它是一本快速入門學習Spring Boot 2的好書,對我的幫助蠻大的。

一、建立SpringBoot專案

進入Spring官網:https://start.spring.io/ 使用Initalizr建立也可在idea中直接使用Initalizr外掛建立。這裡我們新增Web依賴(內建tomcat、springmvc)和DevTools依賴(用於熱部署)並選擇2.0.3發行版。
這裡寫圖片描述

使用idea開啟專案後可以看到XxxApplication類,這個是Spring Boot專案的入口類,通過 @SpringBootApplication

註解標識。

@SpringBootApplication
public class ABaseApplication {

    public static void main(String[] args) {
        SpringApplication.run(ABaseApplication.class, args);
    }
}

二、編寫Controller

現在我們建立一個HelloController。

@RestController
public class HelloController {

    @GetMapping("/hello/{id}")
    public
String hello(@PathVariable("id") Integer id) { return "componentBean = " + componentBean + ", id = " + id; } }

@RestController:SpringBoot用於支援Rest服務,相當於SpringMVC的@Controller + @ResponseBody。
@GetMapping:SpringBoot簡化SpringMVC的RequestMapping(method=RequestMethod.GET),此外還有 PostMappingPutMapping

DeleteMappingPatchMapping

三、最後

至此,一個SpringBoot專案建立完畢,專案程式碼可至此獲取:傳送門

另外,若想在啟動時看到自己設計的一些有趣的banner或者公司的Logo,而不是Spring自己的,可在專案resources/目錄下新建banner.txt,寫下自己的東西,Spring Boot檢查到後會自行替換預設的banner。

附上自己用的:

${AnsiColor.BRIGHT_YELLOW}  
////////////////////////////////////////////////////////////////////  
//                          _ooOoo_                               //  
//                         o8888888o                              //  
//                         88" . "88                              //  
//                         (| ^_^ |)                              //  
//                         O\  =  /O                              //  
//                      ____/`---'\____                           //  
//                    .'  \\|     |//  `.                         //  
//                   /  \\|||  :  |||//  \                        //  
//                  /  _||||| -:- |||||-  \                       //  
//                  |   | \\\  -  /// |   |                       //  
//                  | \_|  ''\---/''  |   |                       //  
//                  \  .-\__  `-`  ___/-. /                       //  
//                ___`. .'  /--.--\  `. . ___                     //  
//              ."" '<  `.___\_<|>_/___.'  >'"".                  //  
//            | | :  `- \`.;`\ _ /`;.`/ - ` : | |                 //  
//            \  \ `-.   \_ __\ /__ _/   .-` /  /                 //  
//      ========`-.____`-.___\_____/___.-`____.-'========         //  
//                           `=---='                              //  
//      ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^        //
//            佛祖保佑       永不宕機     永無BUG                    //
////////////////////////////////////////////////////////////////////