1. 程式人生 > >構建微服務:快速搭建Spring Boot專案

構建微服務:快速搭建Spring Boot專案

Spring Boot簡介:

       Spring Boot是由Pivotal團隊提供的全新框架,其設計目的是用來簡化新Spring應用的初始搭建以及開發過程。該框架使用了特定的方式來進行配置,從而使開發人員不再需要定義樣板化的配置。通過這種方式,Spring Boot致力於在蓬勃發展的快速應用開發領域(rapid application development)成為領導者(官網介紹)。

Spring Boot特點:

       1. 建立獨立的Spring應用程式        2. 嵌入的Tomcat,無需部署WAR檔案        3. 簡化Maven配置        4. 自動配置Spring
       5. 提供生產就緒型功能,如指標,健康檢查和外部配置        6. 絕對沒有程式碼生成並且對XML也沒有配置要求 快速入門:        2、填寫相關的專案資訊、jdk版本等(可參考下圖)    

       3、點選Generate Project,就會生成一個maven專案的壓縮包,下載專案壓縮包

       4、解壓後,使用eclipse,Import -> Existing Maven Projects -> Next ->選擇解壓後的資料夾-> Finsh

專案結構介紹:

       如下圖所示,Spring Boot的基礎結構共三個檔案:

       

       src/main/java  --程式開發以及主程式入口

       src/main/resources --配置檔案

       src/test/java  --測試程式

Spring Boot推薦的專案結構:

       根目錄:com.example.myproject  

       1)domain:實體類(com.example.domain)

       2)Dao:資料訪問層(com.example.repository)

       3)Service:資料服務介面層(com.example.service)

            ServiceImpl:資料服務實現層(com.example.service.impl)

       4)Controller:前端控制器(com.example.controller)

       5)utils:工具類(com.example.utils)

       6)constant:常量介面類(com.example.constant)

       7)config:配置資訊類(com.example.config)

       8)dto:資料傳輸物件(Data Transfer Object,用於封裝多個實體類(domain)之間的關係,不破壞原有的實體類結構)(com.example.dto)

       9)vo:檢視包裝物件(View Object,用於封裝客戶端請求的資料,防止部分資料洩露,保證資料安全,不破壞原有的實體類結構)(com.example.vo)

引入Web模組:

       在pom.xml新增支援Web的模組

1 <dependency>
2     <groupId>org.springframework.boot</groupId>
3     <artifactId>spring-boot-starter-web</artifactId>
4 </dependency>

執行專案:

       1、建立controller

 1 package com.example.annewebsite_server.controller;
 2 
 3 import org.springframework.web.bind.annotation.GetMapping;
 4 import org.springframework.web.bind.annotation.RestController;
 5 
 6 @RestController
 7 public class HelloController {
 8     @GetMapping("/hello")
 9     public String say(){
10         return "Hello Spring Boot!";
11     }
12 }

 

       2、啟動專案入口

       

       3、專案啟動成功

       

       4、在瀏覽器中進行訪問(http://localhost:8080/hello)

       

       以上是一個Spring Boot專案的搭建過程,希望能夠給正在學習Spring Boot的同仁帶來一些些幫助,不足之處,歡迎指正。