如何去開發一個springboot starter

如何去開發一個springboot starter

我們在平時用 Java 開發的時候,在 pom.xml 文件中引入一個依賴就可以很方便的使用了,但是你們知道這是如何實現的嗎。

現在我們就來解決這一個問題!

創建 SpringBoot 項目

首先我們要做的就是把你想要給別人方便使用的內容自己的寫好

我這里直接另外創建了一個 springboot 的 web 項目,在這個 web 項目中我用 controller 寫了幾個簡單的接口,用于后面的調用,然后再創建一個 springboot 項目,這個新的 springboot 項目就是用來開發 starter 的方便使用者更好、更方便使用。

現在是具體流程:

springboot 的 web 項目創建

用 IDEA 快速創建一個 springboot 項目,創建方法如下:

  1. 選擇 spring Initializer
  2. 自己寫一個項目的名稱
  3. 語言選擇 Java
  4. 包管理工具選擇 Maven
  5. 組這個可以自己寫 例如我的昵稱 xwhking 就可以寫 com.xwkhing
  6. jdk 選擇1.8
  7. Java 選擇8
  8. 然后就是下一步

在這里插入圖片描述

進入下一步后

  1. 選擇 springboot 的版本,我一般選擇2.7左右的

  2. 然后選擇開發工具

    1. Spring Boot Devtools
    2. Spring COnfiguration Processor 主要用于后面我們在工程中使用的使用在 yml 中寫配置時能夠自動提示配置
    3. Lombok 通過使用 annotation 快速的生成主要的 getter 和 setter
    4. Spring Web 加上也沒事
      在這里插入圖片描述
  3. 然后就是創建了。

創建好了以后就進入寫代碼環節,寫一個簡單的 web 請求的 Demo

我這里的目錄結構如下:

在這里插入圖片描述

UserController的代碼如下:
package com.xwhking.interface_test.controller;import com.xwhking.interface_test.entity.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest;
import java.util.Date;import static com.xwhking.interface_test.utils.GenSign.genSign;@RestController
@RequestMapping("/user")
public class UserController {@GetMapping("/name")public String getName(@RequestParam String name , HttpServletRequest request){System.out.println("請求參數名字為 : " + name);return "GET 請求參數名字為 : " + name;}@GetMapping("/getOne")public User getUser(HttpServletRequest request){User user = new User();user.setId(123l);user.setUsername("xwhking");user.setPassword("admin123");System.out.println(user);return user ;}
}
User代碼
package com.xwhking.interface_test.entity;import lombok.Data;@Data
public class User {private Long id;private String username;private String password;@Overridepublic String toString(){return "User { " +"id: " + id + "," +"name:" + username + ","+"password: " + password + "}";}
}

這些完成以后就可以啟動這一個項目了。

可以用瀏覽器試試

在這里插入圖片描述

starter開發

以同樣的方式創建一個springboot項目,需要特別注意的就是,我們需要把 pom.xml 文件中的 build 部分代碼全部去掉

pom.xml 文件

注意這里引入了 Hutool 工具庫,用于后面開發,并且文件里面是沒有 build 模塊的,這里還需要注意把版本的snapshot去掉

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.10</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.xwhking</groupId><artifactId>InterfaceStarter</artifactId><version>0.0.1</version><name>InterfaceStarter</name><description>InterfaceStarter</description><properties><java.version>8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>cn.hutool</groupId><artifactId>hutool-all</artifactId><version>5.8.16</version></dependency></dependencies>
</project>
目錄結構
  1. client 目錄 這里就是真正使用的類,對對應的功能進行了封裝。
  2. config 目錄 這里對 client 進行配置,并且把 client 包裝成一個 Bean 返回
  3. utils 工具類,這里用來生成簽名的工具
  4. META-INF.spring.factories 這個非常重要,用于別人調用的時候,在寫配置的之后能夠進行提示與自動裝配

在這里插入圖片描述

client 代碼
package com.xwhking.interfacestarter.client;import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import lombok.Data;import java.time.LocalDateTime;
import java.util.Date;
import java.util.HashMap;import static com.xwhking.interfacestarter.utils.GenSign.genSign;/*** 發起請求時候一定要注意,不要把secretKey直接傳送,只需要進行一個簽名傳送就好了,然后后端通過同樣的方式進行簽名* 的生成,進行對比,驗證身份。*/
@Data
public class XWHKINGClient {private String accessKey;private String secretKey;private Long userId;public XWHKINGClient(String accessKey,String secretKey,Long userId){this.userId = userId;this.accessKey = accessKey;this.secretKey = secretKey;}public String getName(String name){//可以單獨傳入http參數,這樣參數會自動做URL編碼,拼接在URL中HashMap<String, Object> paramMap = new HashMap<>();paramMap.put("name", name);HashMap<String,String> headerMap = new HashMap<>();headerMap.put("accessKey",accessKey);headerMap.put("userId",userId.toString());headerMap.put("sign", genSign(accessKey,secretKey,userId));headerMap.put("timestamp",Long.toString(new Date().getTime()));String result1= HttpRequest.get("http://localhost:8080/user/name").addHeaders(headerMap).form(paramMap).execute().body();System.out.println(result1);return result1;}public String GetUser(){HashMap<String,String> headerMap = new HashMap<>();headerMap.put("accessKey",accessKey);headerMap.put("userId",userId.toString());headerMap.put("sign", genSign(accessKey,secretKey,userId));headerMap.put("timestamp",Long.toString(new Date().getTime()));String result1= HttpRequest.get("http://localhost:8080/user/getOne").addHeaders(headerMap).execute().body();System.out.println(result1);return result1;}public static void main(String[] args) {new XWHKINGClient("xwhking","admin123",123123l).getName("XWHKING");}
}

這里都加了請求頭,加請求頭的目的是為了,進行簽名認證。

為什么要進行簽名認證
  1. 保證安全性,一個人不能隨便調用,如果隨便調用的話,自己的服務器資源會收到壓迫,以及資源的損失。
  2. 適用于無需保存登錄態。只認簽名,不關注用戶登錄態。
如何進行簽名認證

通過 http request header 頭傳遞參數

這里主要傳遞的參數

  • accessKey: 調用的標識, 需要復雜、 無序、無規律,這里我沒有實現,只是簡單的模擬,如果需要實現的話可以使用現成的簽名實現工具包,例如 hutool
  • secretKey: 調用的密鑰,需要復雜、 無序、無規律,該參數一定一定不能放到請求頭中,不然可能會被別人抓包,以及可能造成泄露。
  • 用戶請求的參數
  • sign: 簽名,由 accessKey 和 secretKey 以及 userId 等信息生成,用于傳遞信息。然后后端通過同樣的方式進行生成對比驗證權限。
  • 上述問題滿足了,可能還抵擋不了別人的攻擊,例如別人用重放就可以再次調用 API 了,限制重放的方法:
    • 加隨機數,只能使用一次,服務端要保存使用過的隨機數
    • 加 timestamp 時間戳,檢驗時間戳是否過期,我這里就是通過時間戳,超過10s就失效。
對web中的UserController進行更新

更新就是為了校驗,然后如果更新了,項目記得重啟

package com.xwhking.interface_test.controller;import com.xwhking.interface_test.entity.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;import javax.servlet.http.HttpServletRequest;
import java.util.Date;import static com.xwhking.interface_test.utils.GenSign.genSign;@RestController
@RequestMapping("/user")
public class UserController {/*** 校驗簽名,以及其他信息,注意這里的 secretKey 是模擬的一般用戶的 secretKey 是需要去從數據庫取出來,* 然后進行驗證。* @param request*/private void verifyRequest(HttpServletRequest request){String sign = request.getHeader("sign");String accessKey = request.getHeader("accessKey");String secretKey = "admin123";String userId = request.getHeader("userId");String requestTime = request.getHeader("timestamp");long oldTime = Long.parseLong(requestTime);long newTime = new Date().getTime();if(newTime - oldTime > 10000){throw new RuntimeException("檢測到請求異常");}String newSign = genSign(accessKey,secretKey,Long.parseLong(userId));if(!newSign.equals(sign)){throw new RuntimeException("簽名錯誤");}}@GetMapping("/name")public String getName(@RequestParam String name , HttpServletRequest request){verifyRequest(request);System.out.println("請求參數名字為 : " + name);return "GET 請求參數名字為 : " + name;}@GetMapping("/getOne")public User getUser(HttpServletRequest request){verifyRequest(request);User user = new User();user.setId(123l);user.setUsername("xwhking");user.setPassword("admin123");System.out.println(user);return user ;}
}
config 代碼

要注意其中的注解

package com.xwhking.interfacestarter.config;import com.xwhking.interfacestarter.client.XWHKINGClient;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "xwhking.client")
@Data
@ComponentScan
public class XWHKINGClientConfig {private String accessKey;private String secretKey;private String userId;@Beanpublic XWHKINGClient xwhkingClient(){return new XWHKINGClient(accessKey,secretKey,Long.parseLong(userId));}
}
生成簽名代碼

這里直接使用了 Hutool 工具庫中的 sh256 的生成方法

package com.xwhking.interfacestarter.utils;import cn.hutool.crypto.SecureUtil;
import lombok.Data;@Data
public class GenSign {public static String genSign(String accessKey,String secretKey,Long userId){String key = "xwhking" + "." + accessKey + "." + secretKey + "."  + userId;return SecureUtil.sha256(key);}
}
META-INF 中文件的內容

通過看內容就可以看出,你需要把后面的內容進行替換,寫入你的地址。

org.springframework.boot.autoconfigure.EnableAutoConfiguration = com.xwhking.interfacestarter.XWHKINGClientConfig

到這里 Starter 就完了,然后使用 maven 進行打包(調用install)。這里的打包會把包直接放入你的 maven 倉庫,打包成功就會出現 BUILD SUCCESS

在這里插入圖片描述

在其他項目中使用

首先復制這段代碼

<groupId>com.xwhking</groupId>
<artifactId>InterfaceStarter</artifactId>
<version>0.0.1</version>

然后在你的其他項目中添加進依賴

<dependency><groupId>com.xwhking</groupId><artifactId>InterfaceStarter</artifactId><version>0.0.1</version>
</dependency>

刷新 maven 倉庫

然后再 yml 配置中加入配置

在 config中的prefix 可以設置前綴,也就是可以更改xwhking.client

在這里插入圖片描述

然后在你的代碼中使用 Test 進行測試

@SpringBootTest
class MainApplicationTests {@Resourceprivate XWHKINGClient xwhkingClient;@Testvoid testClient(){xwhkingClient.getName("xwhking") ;}}

調用結果:

出來了 xwhking 結果成功。

在這里插入圖片描述

這樣開發一個starter 就結束了

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/160208.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/160208.shtml
英文地址,請注明出處:http://en.pswp.cn/news/160208.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

css3

基礎 <!DOCTYPE html> <html><head><meta charset"utf-8"><title>style</title><!-- link&#xff08;外部樣式&#xff09;和style&#xff08;內部樣式&#xff09;優先級相同&#xff0c;重復寫會覆蓋 --><link re…

面試題-9

1.如何封裝一個組件 1.使用Vue.extend()創建一個組件 2.使用Vue.components()方法注冊組件 3.如果子組件需要數據,可以在props中接收定義 4.子組件修改好數據,要把數據傳遞給父組件&#xff0c;可以用emit()方法 原則: 把功能拆開 盡量讓組件原子化,一個組件做一件事情 …

centos7安裝MySQL—以MySQL5.7.30為例

centos7安裝MySQL—以MySQL5.7.30為例 本文以MySQL5.7.30為例。 官網下載 進入MySQL官網&#xff1a;https://www.mysql.com/ 點擊DOWNLOADS 點擊鏈接&#xff1b; 點擊如上鏈接&#xff1a; 選擇對應版本&#xff1a; 點擊下載。 安裝 將下載后的安裝包上傳到/usr/local下…

CTF靶場搭建及Web賽題制作與終端docker環境部署

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? 寫在前面 ╔═══════════════════════════════════════════════════…

使用ChatGPT創建Makefile構建系統:使用Make運行Docker

使用ChatGPT創建Makefile構建系統&#xff1a;使用Make運行Docker 芯語芯愿&#xff08;知乎/紛傳/CSDN/&#xff09;&#xff1b;小石頭的芯語芯愿&#xff08;微信公眾號&#xff09; 開發高效現代的構建系統對于滿足開發周期需求至關重要。原先&#xff0c;嵌入式開發者一…

Unity 場景烘培 ——LensFlare鏡頭光暈(三)

提示&#xff1a;文章有錯誤的地方&#xff0c;還望諸位大神指出&#xff01; 文章目錄 前言一、鏡頭光暈 (Lens Flares)是什么&#xff1f;二、使用Lens Flares組件總結 前言 一般情況下都會忽略的東西&#xff0c;鏡頭光暈。理論上不加鏡頭光暈&#xff0c;也不會有什么影響…

vue3的兩個提示[Vue warn]: 關于組件渲染和函數外部使用

1. [Vue warn]: inject() can only be used inside setup() or functional components. 這個消息是提示我們&#xff0c;需要將引入的方法作為一個變量使用。以vue-store為例&#xff0c;如果我們按照如下的方式使用&#xff1a; import UseUserStore from ../../store/module…

數據治理之考評環節

考評的流程&#xff08;批處理&#xff09; 周期調度&#xff0c;每天一次&#xff1a;采集hive, hdfs元數據存放到mysql中的dga庫的metainfo表手動通過管理頁面補充輔助信息指標考評 讀取要考評的表的元數據及輔助信息讀取要考評的指標對每張表的每個指標逐個進行考評保存考評…

RabbitMQ快速入門(簡單收發消息)

文章目錄 前言一、數據隔離1.用戶管理2.virtual host 二、控制臺收發1.交換機2.隊列3.綁定 三、編程式收發1.依賴和配置2.收發信息 總結 前言 1.了解數據隔離 2.RabbitMQ控制臺收發信息 3.SpringBoot整合RabbitMQ收發信息 一、數據隔離 1.用戶管理 點擊Admin選項卡&#xff0…

mmdet全教程

官方給的文檔一言難盡&#xff0c;網上的教程又沒有從大綱到源碼的完整解讀&#xff0c;計劃年后開個系列記錄一下

依賴庫:Ceres-solver-2.0.0安裝

依賴庫&#xff1a;Ceres-solver-2.0.0安裝 前言安裝ceres-solver-2.0.0驗證 前言 Ceres Solver是谷歌開源的C非線性優化庫&#xff0c;能夠解決有約束或無約束條件下的非線性最小二乘問題。2010年之后大量的運用在谷歌的產品開發中&#xff0c;尤其在谷歌開源的cartographer中…

圖像分類單張圖片預測準確率達到百分之百

在圖像分類任務中&#xff0c;針對單個圖片得到100%的準確率是有可能但極其罕見的&#xff0c;并且不代表模型在整個測試集上也能達到100%的準確率。 ??針對單個圖片獲得100%準確率的情況可能包括以下幾種情形&#xff1a; 圖片本身特殊性: 如果測試集中的某張圖片在訓練集中…

【python基礎(1)】變量和簡單數據類型

文章目錄 一. 變量的命名和使用二. 字符串1. 修改字符串的大小寫2. 在字符串中使用變量3. 使用制表符或換行符來添加空白4. 刪除空白 三. 數1. 整數2. 浮點數3. 整數和浮點數4. 數中的下劃線5. 同時給多個變量賦值6. 常量 三. 注釋四. Python之禪 一. 變量的命名和使用 變量規…

各種LLM數據集包括SFT數據集

各種LLM數據集包括SFT數據集 數集介紹和 hf上的名字對話數據生成方法交通領域數據集SFT 的解釋數集介紹和 hf上的名字 通用預訓練數據集 SFT datasets SFT 數據集 50萬條中文ChatGPT指令Belle數據集:BelleGroup/train_0.5M_CN 100萬條中文ChatGPT指令Belle數據集:BelleGrou…

C++學習 --stack

目錄 1&#xff0c; 什么是stack 2&#xff0c; 創建stack 2-1&#xff0c; 標準數據類型 2-2&#xff0c; 自定義數據類型 2-3&#xff0c; 其他創建方式 3&#xff0c; 操作stack 3-1&#xff0c; 賦值 3-2&#xff0c; 插入元素(push) 3-3&#xff0c; 查詢元素 3…

Linux的簡單使用

Linux命令使用技巧 Tab鍵自動補全連續兩次Tab鍵&#xff0c;給出操作提示使用上下箭頭快速調出曾經使用過的命令使用clear命令或者Ctrll快捷鍵實現清屏Linux的常用命令 命令作用詳細說明ls [-al] [dir]顯示指定目錄下的內容 -a 顯示所有文件及目錄 (. 開頭的隱藏文件也會列出) …

sonar對webgoat進行靜態掃描

安裝sonar并配置 docker安裝sonarqube&#xff0c;sonarQube靜態代碼掃描 - Joson6350 - 博客園 (cnblogs.com) 對webgoat進行sonar掃描 掃描結果 bugs Change this condition so that it does not always evaluate to "false" 意思是這里的else if語句不會執行…

“我,24歲,年薪20萬”:選對了行業究竟多重要?

那些在職場上順風順水&#xff0c;按部就班拿到高薪的人都有什么特點&#xff1f; 今天的主人公Flee告訴我&#xff0c;是穩。 在她的故事里&#xff0c;我看到一個“別人家的姑娘”&#xff0c;是怎樣在職場上穩步晉升&#xff0c;大學畢業僅2年&#xff0c;就拿到18.6K月薪&a…

「go查漏補缺」命名規則以及 GROM 結構體的應用

概述&#xff1a; 在學習GORM過程中&#xff0c;總是在調用結構體和文件導入這里出錯&#xff0c;所以整理了以下文檔用于梳理變量/結構體命名規則和import導入的知識點 一、變量/結構體命名規則 變量/結構體都遵守同樣的命名規則&#xff1a;可見性由首字母大小寫決定 大寫…