使用 VSCode 創建 SpringBoot RESTful 增刪改查接口項目併發布

聲明:不用 idea 只是因爲我想試試別的環境能不能一樣起來,太複雜的配置和優化、慣例寫法我不會,我並不是專業 SpringBoot 後臺開發。



0 準備

裝好 vscode,裝好 spring 插件、java 插件

  • jdk要求:11 及以上(插件不認8了)
  • 插件列表
    • Debugger for Java
    • Dependency Analytics
    • Language Support for Java(TM) by Red Hat
    • Lombok Annotations Support for VS Code (這個之後會說明)
    • Maven for Java
    • Project Manager for Java
    • Red Hat Commons
    • Spring Boot Dashboard
    • Spring Boot Extension Pack
    • Spring Boot Tools
    • Spring Initializr Java Support

1 創建 maven 工程

Ctrl + Shift + P 快捷鍵搜索 spring,創建 maven 工程

image

然後選擇 maven 版本(默認即可,標SNAPSHOT是不穩定版)

image

然後選擇語言(默認 Java)

image

然後填 Group Id(假定我的域名是 sukiruga.cn,那麼就填 cn.sukiruga):

image

然後填 Artifact Id(隨便,小寫單詞即可)

image

發佈的格式,默認 jar 包:

image

選擇 Java 版本(我選了與本機一致的 11):

image

選擇依賴項:

image

lombok 是一個好用的包,通過註解少寫很多代碼,具體自己查,如果不選,後續要在 pom 文件中自己加 lombok 的依賴。

如果是老手,你知道要做鑑權,要連數據庫,那你可以翻到下面自己找想要的依賴點選即可,最後回車完成創建,會讓你選一個文件夾存放生成的項目有關文件:

image

image

隨後插件會下載依賴,並提示創建成功,點擊 Open 即可在新的 vscode 窗口打開:

image

插件還會提示,這是個 java 工程,是否導入:

image

選 yes 即可。

image

2 認識項目文件結構

src/main/java 目錄即寫代碼的地方,按上面的步驟來看,這個目錄下應該會有這樣層級的目錄:

cn/sukiruga/api,並且在這個 api 文件夾下會有一個主程序入口類的文件 ApiApplication.java

這個命名是大駝峯,跟 Artifact Id 是一樣的,後面接 Application 尾綴。

假如 Artifact Id 是 demo,那麼這個入口主程序文件的名稱將是 DemoApplication.java

3 創建數據模型類

cn/sukiruga/api 下創建一個 Student 類,路徑如下:cn/sukiruga/api/models/Student.java

package cn.sukiruga.api.models;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
@AllArgsConstructor
public class Student {
  private long id;
  private String name;
  private int age;
}

這兩個註解即 lombok 提供的,可以少寫很多 getter、setter 等常用函數和常用全參數構造函數。lombok 有很多這種註解,網上資料不少,需要自己查。

這個類的實例代表的就是一條數據,對應關係數據庫表裏的一個記錄(一行)。

4 創建表示連接器的接口(也叫 repository)

cn/sukiruga/api 下創建一個接口 repository/IStudentContext.java,我習慣了 ASP.NET 的寫法和稱呼,這邊抄過來用了,你也可以寫 repository/StudentRepository.java,對應待會的實現類即 StudentRepositoryImpl.java,我這裏待會的實現類即 repository/impl/StudentContext.java

接口用來表示依賴:

package cn.sukiruga.api.repository;

import java.util.Collection;

import cn.sukiruga.api.models.Student;

public interface IStudentContext {
  public Collection<Student> getAll();
  public Student getOne(long id);
  public void createOrUpdate(Student student);
  public void delete(long id);
}

Springboot 會根據對應類的註解 @Repository 將它注入程序內部:

package cn.sukiruga.api.repository.impl;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.springframework.stereotype.Repository;

import cn.sukiruga.api.models.Student;
import cn.sukiruga.api.repository.IStudentContext;

@Repository
public class StudentContext implements IStudentContext {
  private static Map<Long, Student> virtualDatabase;
  static {
    virtualDatabase = new HashMap<>();
    virtualDatabase.put(1L, new Student(1L, "張三", 21));
  }

  @Override
  public Collection<Student> getAll() {
    return virtualDatabase.values();
  }

  @Override
  public Student getOne(long id) {
    return virtualDatabase.get(id);
  }

  @Override
  public void createOrUpdate(Student student) {
    virtualDatabase.put(student.getId(), student);
  }

  @Override
  public void delete(long id) {
    virtualDatabase.remove(id);
  }
}

cn.sukiruga.world.repository 包下的接口、實現類,表示某個對應的 model 能具備什麼行爲,在某個具體的 repository 實現類下,你可以定製不同的鏈接數據庫的方式,或者像本例一樣,用 HashMap 代替數據庫作爲示例程序。

SpringBoot@Repository 這個註解。

repository 表示能怎麼樣對數據庫、數據來源進行怎麼樣的操作,而下文的 controller 則不對數據庫,它擁有一個 repository 成員變量,對外暴露訪問接口。

這樣,repository 對內,controller 對外,分工明確。

5 創建控制器

創建於 cn/sukiruga/api/controller/StudentController.java,對應包名即 cn.sukiruga.api.controller

package cn.sukiruga.api.controller;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import cn.sukiruga.api.models.Student;
import cn.sukiruga.api.repository.impl.StudentContext;

@RestController
@RequestMapping("/student")
public class StudentController {

  // 自動將 StudentContext 對象注入
  @Autowired
  private StudentContext context;

  @GetMapping
  public Collection<Student> getAll() {
    return context.getAll();
  }

  @GetMapping("/{id}")
  public Student getOne(@PathVariable("id") long id) {
    return context.getOne(id);
  }

  @PostMapping
  public void save(@RequestBody Student student) {
    context.createOrUpdate(student);
  }

  @PutMapping
  public void update(@RequestBody Student student) {
    context.createOrUpdate(student);
  }

  @DeleteMapping("/{id}")
  public void delete(@PathVariable long id) {
    context.delete(id);
  }
}

這有一堆註解,對應的功能也筆記好認:

  • @RestController:指明這個控制器是 REST 風格控制器
  • @RequestMapping:指明這個控制器對應的路由,此處參數是 "/student"
  • @GetMapping:這個註解表示此方法處理當前控制器 get 請求,可帶參數,見代碼中帶 "/{id}" 的方法
  • @PostMapping:這個註解表示此方法處理當前控制器 post 請求
  • @PutMapping:這個註解表示此方法處理當前控制器的 put 請求
  • @DeleteMapping:這個註解表示此方法處理當前控制器的 delete 請求,可帶參數
  • @PathVariable:這個註解表示參數是請求 url 中的 queryString 動態參數,例如代碼中的 id
  • @RequestBody:這個註解表示會把請求體中的 json(springboot 默認序列化和反序列化 json)反序列化爲 Student 類對象

這裏幾個簡單的增刪改查方法,利用了 context 成員變量,就不需要在這個類裏操心數據是從哪來的了。

對應接口如下:

api 方法 參數
/student GET 無參則返回 json 數組,全體 student 數據
/student/{id} GET 有參則查詢某個 student
/student POST 一個 json 對象,字段使用小駝峯,表示創建一條記錄
/student PUT 一個 json 對象,字段使用小駝峯,表示更新一條記錄
/student/{id} DELETE 刪除對應 id 的記錄

6 代碼寫完後的目錄結構

image

7 修改端口:修改 yml 文件

SpringBoot 本來就提倡少配置、無配置,不過這東西也不能絕對沒有,儘量減少它的書寫即可。

它的配置文件名必須是 application 起頭,至於命名規則和不同後綴名的優先級和書寫格式則可以自行尋找博客。

例如:https://www.jianshu.com/p/a0b3147bc4de

本文使用 yml 格式。

創建項目時,插件在 src/main/resources 目錄下(也必須是這個目錄)創建了一個 application.properties 文件,將其改爲 application.yml,並使用 yaml 格式指明啓動端口(端口隨你指定):

server:
  port: 2351 

關於 yml 和 properties 格式的切換,百度搜索“maven application.properties 和 yml”能搜到很多博客。

在這就說個經驗好了:如果之前使用了 properties 文件運行過,現在轉用 yml,要清理一次 maven -X clean install 再運行。

properties 文件存在則 yml 文件失效。

8 調試

vscode 裝完準備章節的插件後,在側欄會有如下面板:

image

JAVA PROJECT 面板比較全,其中 {} 圖標表示是一個包。此截圖中最頂級的 api 圖標,有三條小豎線,代表是一個項目。右鍵 api 層級可以點擊 Run 進行運行調試,也可以點 api 層級最右側的三角箭頭按鈕運行項目。

MAVEN 面板則比較簡單,下一節的打包成 jar 則要用到這裏的右鍵菜單 - package 命令。

SPRING BOOT DASHBORAD 面板則針對 SpringBoot 項目,它能識別出 Java 項目中的 SpringBoot 框架程序,你除了在 JAVA PROJECT 面板中運行外,也可以在這裏運行。

啓動項目後,可以在控制檯看到消息:

image

端口也是改了之後的端口。

可使用 vscode 插件 Thunder Client 或者 postman 軟件進行接口測試:

image

9 發佈 jar 包並使用終端運行

MAVEN 面板右鍵執行 package 命令,在項目根目錄下的 target 文件夾會生成 <Artifact Id>-<version>-<SNAPSHOT/RELEASE>.jar 包:

image

image

然後,你就可以拷這個文件到有 Java 環境的系統運行啦,運行命令是:

java -jar /path/to/api-0.0.1-SNAPSHOT.jar

10 作爲 Windows Service 或 Linux 守護進程在後臺運行

Windows 考慮使用 WinSW 程序製作 Windows 服務;

Linux 使用 Systemctl 程序製作 service。

11 如果是純 maven 項目(使用諸如 idea 等 ide 創建的)如何創建

需要自己在 pom 包中添加 parent 依賴和 dependencies 依賴(包括 springboot 有關的依賴和 lombok 依賴),

除了上面寫的源代碼外,還需要手動寫一個第 2 節中提到的入口主程序類,類似 C# ASP.NET 中的 Program 類。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章