Spring boot 將不少東西都集成在一塊兒了,搭建maven項目的時候只須要引入不多的依賴就能夠實現項目的搭建。java
1.搭建maven項目結構web
2.引入Spring boot 依賴 直接去官網找就能夠了,還有例子說明spring
3.pom.xml 導入依賴包,最開始用的1.5.10的版本不知道爲啥main方法啓動的時候tomcat沒法啓動,後來換了版本就能夠了tomcat
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <version>1.5.7.RELEASE</version> </dependency> </dependencies>
4.main方法啓動Spring boot 啓動類始用 @SpringBootApplication 註解app
package di.bao; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class FirstAPP { public static void main(String[] args) { SpringApplication.run(FirstAPP.class, args); } }
5.tomcat啓動以後就能夠直接訪問了,直接訪問8080端口會出現錯誤頁面,編寫一個controller,始用@Controller 註解,訪問8080/nihao,頁面出現方法返回值。eclipse
package di.bao; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class NiController { @GetMapping("/nihai") @ResponseBody public String hello() { return "shi jie ni hao!"; } }
6.rest接口,返回josn 格式字符串 :建立一個類,編寫controller,訪問http://localhost:8080/student/1 ,頁面:{"name":"zhangsan","id":1}maven
package di.bao; public class Student { private String name; private int id; public Student() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
package di.bao; import org.springframework.http.MediaType; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class JosnController { /** * value 路徑 method 訪問方法 produces 產出什麼 * @param id * @return */ @RequestMapping(value = "/student/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @ResponseBody public Student hello(@PathVariable int id) { Student student = new Student(); student.setId(id);; student.setName("zhangsan"); return student; } }
7.spring boot啓動方式:spring-boot
1.main方法啓動 this
2.mvn intall編譯成jar包後 java -jar xxxx.jar啓動 spa
3.項目目錄下執行mvn spring-boot:run
注意:再次使用main方法啓動的時候必定要先將上一次啓動的先關閉,不然會出現端口占用出現java.net.BindException: Address already in use: bind 異常。
命令行:netstat -ano|findstr "8080"
命令行:輸入tasklist 查看11000是哪一個進程
win7的話直接在任務管理器裏面把佔用端口的程序關掉就能夠了。
因爲系統換了win10,win10的任務管理器有點不同,找了半天也沒找到這個進程,索性把java相關的 都關掉了,結果仍是沒用,
後來發如今應用 eclipse下面還有一個java有關的,關掉那個就能夠正常重啓了