Spring Boot 學習之路——1 入門demo
阿新 • • 發佈:2019-01-04
前言:
使用Spring Boot已有一年多時間,卻從未靜下心來總結,今天抽空寫個傻瓜式教程,鞏固一下。
- 為所有Spring開發者更快的入門
- 開箱即用,提供各種預設配置來簡化專案配置
- 內嵌式容器簡化Web專案
- 沒有冗餘程式碼生成和XML配置的要求(Spring 4可實現零配置)
入門demo很簡單,實現一個簡單的Http 請求處理。廢話不說看截圖。
- IDE : IntelliJ IDEA 2018.1 x64
- JDK : 1.8
- Spring Framework 5.0.5
1.建立專案
建立完畢,專案結構如下:
2 新增Controller
controller程式碼如下:
packagecom.joanna.springbootdemo.demo.controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController@RequestMapping(value = "/sayHello") public class SayHello { @RequestMapping(value = "/humanSays", method = RequestMethod.GET) public String humanSays(@RequestParam(name = "name", required = false) String name, @RequestParam(name = "comeFrom", required = false) String comeFrom) { return"Hello " + name + ", who comes from " + comeFrom + ", I'm a human"; } @RequestMapping(value = "/catSays", method = RequestMethod.GET) public String catSays(@RequestParam(name = "name", required = false) String name) { return "Hello " + name + ", I'm a cat"; } @RequestMapping(value = "/dogSays", method = RequestMethod.GET) public String dogSays(@RequestParam(name = "name", required = false) String name) { return "Hello " + name + ", I'm a dog"; } }
新增pom依賴如下(idea自動add dependency,棒棒噠):
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
3 啟動
啟動方式:
- Application類main方法啟動
- mvn clean install/package cd 到target目錄,java -jar 專案.jar,注意這裡需要加入依賴spring-boot-maven-plugin生成可執行的jar
- mvn spring-boot: run 啟動
啟動後,開啟瀏覽器中訪問:http://localhost:8080/sayHello/humanSays?name=Joanna&comeFrom=China
可以看到頁面輸出:Hello Joanna, who comes from China, I'm a human
打完收工。