使用Spring boot 簡單搭建網站框架
阿新 • • 發佈:2019-01-25
Spring Boot的主要優點:
為所有Spring開發者更快的入門
開箱即用,提供各種預設配置來簡化專案配置
內嵌式容器簡化Web專案
src/main/java下的程式入口:Chapter1Application
src/main/resources下的配置檔案:application.properties
src/test/下的測試入口:Chapter1ApplicationTests
引入Web模組,需新增
為所有Spring開發者更快的入門
開箱即用,提供各種預設配置來簡化專案配置
內嵌式容器簡化Web專案
沒有冗餘程式碼生成和XML配置的要求
使用Maven構建專案
通過SPRING
INITIALIZR
工具產生基礎專案
- 訪問:
http://start.spring.io/
- 選擇構建工具
Maven Project
、Spring Boot版本,以及一些工程基本資訊 - 點選Generate Project下載專案壓縮包
- 解壓專案包,並用IDE以Maven專案匯入
src/main/java下的程式入口:Chapter1Application
src/main/resources下的配置檔案:application.properties
src/test/下的測試入口:Chapter1ApplicationTests
引入Web模組
當前的pom.xml
內容如下,僅引入了兩個模組:
spring-boot-starter
:核心模組,包括自動配置支援、日誌和YAMLspring-boot-starter-test
:測試模組,包括JUnit、Hamcrest、Mockito
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies>
引入Web模組,需新增
spring-boot-starter-web
模組:<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
編寫HelloWorld服務
- 建立
package
命名為com.didispace.web
(根據實際情況修改) - 建立
HelloController
類,內容如下
@RestController public class HelloController { @RequestMapping("/hello") public String index() { return "Hello World"; } }
- 啟動主程式,開啟瀏覽器訪問
http://localhost:8080/hello
,可以看到頁面輸出Hello World