1. 程式人生 > >使用Spring boot 簡單搭建網站框架

使用Spring boot 簡單搭建網站框架

Spring Boot的主要優點:


為所有Spring開發者更快的入門
開箱即用,提供各種預設配置來簡化專案配置
內嵌式容器簡化Web專案

沒有冗餘程式碼生成和XML配置的要求

使用Maven構建專案

通過SPRING INITIALIZR工具產生基礎專案
  1. 訪問:http://start.spring.io/
  2. 選擇構建工具Maven Project、Spring Boot版本以及一些工程基本資訊
  3. 點選Generate Project下載專案壓縮包
  4. 解壓專案包,並用IDE以Maven專案匯入
通過上面步驟完成了基礎專案的建立,如上圖所示,Spring Boot的基礎結構共三個檔案(具體路徑根據使用者生成專案時填寫的Group所有差異):


src/main/java下的程式入口:Chapter1Application
src/main/resources下的配置檔案:application.properties
src/test/下的測試入口:Chapter1ApplicationTests

引入Web模組

當前的pom.xml內容如下,僅引入了兩個模組:

  • spring-boot-starter:核心模組,包括自動配置支援、日誌和YAML
  • spring-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