如何去开发一个springboot starter

news2024/9/25 23:16:05

如何去开发一个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;
    @Override
    public 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;
    @Bean
    public 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 {

    @Resource
    private XWHKINGClient xwhkingClient;

    @Test
    void testClient(){
        xwhkingClient.getName("xwhking") ;
    }

}

调用结果:

出来了 xwhking 结果成功。

在这里插入图片描述

这样开发一个starter 就结束了

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1223585.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Wireshark TS | 应用传输缓慢问题

问题背景 沿用之前文章的开头说明&#xff0c;应用传输慢是一种比较常见的问题&#xff0c;慢在哪&#xff0c;为什么慢&#xff0c;有时候光从网络数据包分析方面很难回答的一清二楚&#xff0c;毕竟不同的技术方向专业性太强&#xff0c;全栈大佬只能仰望&#xff0c;而我们…

【Spring篇】使用注解进行开发

&#x1f38a;专栏【Spring】 &#x1f354;喜欢的诗句&#xff1a;更喜岷山千里雪 三军过后尽开颜。 &#x1f386;音乐分享【如愿】 &#x1f970;欢迎并且感谢大家指出小吉的问题 文章目录 &#x1f33a;原代码&#xff08;无注解&#xff09;&#x1f384;加上注解⭐两个注…

20231117在ubuntu20.04下使用ZIP命令压缩文件夹

20231117在ubuntu20.04下使用ZIP命令压缩文件夹 2023/11/17 17:01 百度搜索&#xff1a;Ubuntu zip 压缩 https://blog.51cto.com/u_64214/7641253 Ubuntu压缩文件夹zip命令 原创 chenglei1208 2023-09-28 17:21:58博主文章分类&#xff1a;LINUX 小工具 文章标签命令行压缩包U…

打不开github网页解决方法

问题&#xff1a; 1、composer更新包总是失败 2、github打不开&#xff0c;访问不了 解决方法&#xff1a;下载一个Watt Toolkit工具&#xff0c;勾选上&#xff0c;一键加速就可以打开了。 下载步骤&#xff1a; 1、打开网址&#xff1a; Watt Toolkit 2、点击【下载wind…

Python (十一) 迭代器与生成器

迭代器 迭代器是访问集合元素的一种方式&#xff0c;可以记住遍历的位置的对象 迭代器有两个基本的方法&#xff1a;iter() 和 next() 字符串&#xff0c;列表或元组对象都可用于创建迭代器 字符串迭代 str1 Python str_iter iter(str1) print(next(str_iter)) print(next(st…

原型网络Prototypical Network的python代码逐行解释,新手小白也可学会!!-----系列2

文章目录 一、原始代码二、每一行代码的详细解释 一、原始代码 labels_trainData ,labels_testData load_data() wide labels_trainData[0][0].shape[0] length labels_trainData[0][0].shape[1] for label in labels_trainData.keys():labels_trainData[label] np.reshap…

FastJsonAPI

maven项目 pom.xml <dependencies><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>2.0.26</version></dependency><dependency><groupId>junit</groupId>&l…

vmware17 虚拟机拷贝、备份、复制使用

可以在虚拟机运行的情况下进行拷贝 查看新安装的虚拟机位置 跳转到上一级目录 复制虚拟机 复制虚拟机整个目录 删除lck文件&#xff0c;不然开机的时候会报错 用vmware 打开新复制的虚拟机 lck文件全部删除 点击开机 开机成功

软磁交流测试仪系统磁参量指标

1. 主要应用 2. 软磁交流测试仪磁参量指标 被测参数 最佳测量不确定度 ( k 2 ) 1 kHz 最佳测量重复性 主要动态磁特性参数 Ps 2.0% 1.0% μa 3.0% 1.0% Bm 1.0% 0.5% Hm 1.0% 0.5% δ 5.0% 1.5% 其他磁特性参数供参考 Br 2.0% 1.0% Hc 3.0% 1.0% μ…

振南技术干货集:比萨斜塔要倒了,倾斜传感器快来!(6)

注解目录 1、倾斜传感器的那些基础干货 1.1 典型应用场景 &#xff08;危楼、边坡、古建筑都是对倾斜敏感的。&#xff09; 1.2 倾斜传感器的原理 1.2.1 滚珠式倾斜开关 1.2.2 加速度式倾斜传感器 1)直接输出倾角 2)加速度计算倾角 3)倾角精度的提高 &#xff08;如果…

微积分在神经网络中的本质

calculus 在一个神经网络中我们通常将每一层的输出结果表示为&#xff1a; a [ l ] a^{[l]} a[l] 为了方便记录&#xff0c;将神经网络第一层记为&#xff1a; [ 1 ] [1] [1] 对应的计算记录为为&#xff1a; a [ l ] &#xff1a; 第 l 层 a [ j ] &#xff1a; 第 j 个神经…

How to import dgl-cu113 如何导入 dgl-cu113

参考这个 从How to import dgl-cu113 如何导入 dgl-cu113https://discuss.dgl.ai/t/how-to-import-dgl-cu113/3381https://discuss.dgl.ai/t/how-to-import-dgl-cu113/3381

vscode 推送本地新项目到gitee

一、gitee新建仓库 1、填好相关信息后点击创建 2、创建完成后复制 https&#xff0c;稍后要将本地项目与此关联 3、选择添加远程存储库 4、输入仓库地址&#xff0c;选择从URL添加远程存储仓库 5、输入仓库名称&#xff0c;确保仓库名一致

Redis:新的3种数据类型Bitmaps、HyperLoglog、Geographic

目录 Bitmaps简介常用命令bitmaps与set比较 HyperLoglog简介命令 Geographic简介命令 Bitmaps 简介 位操作字符串。 现代计算机使用二进制&#xff08;位&#xff09;作为信息的基本单位&#xff0c;1个字节等于8位&#xff0c;例如“abc”字符串是有3个字节组成&#xff0c…

开发一款回合制游戏,需要注意什么?

随着游戏行业的蓬勃发展&#xff0c;回合制游戏因其深度的策略性和令人着迷的游戏机制而受到玩家们的热烈欢迎。如果你计划投身回合制游戏的开发领域&#xff0c;本文将为你提供一份详细的指南&#xff0c;从游戏设计到发布&#xff0c;助你成功打造一款引人入胜的游戏。 1. 游…

记一次用jlink调试正常,不进入调试就不能运行的情况

一、概述 我开机会闪烁所有指示灯&#xff0c;但是重新上电时&#xff0c;指示灯并没有闪烁&#xff0c;就像"卡死"了一样。 使用jlink的swd接口进行调试&#xff0c;需要多点几次运行才能跳转到main函数里面。 调试模式第一次点击运行&#xff0c;暂停查看函数堆栈…

开源与闭源:创新与安全的平衡

目录 一、开源和闭源的优劣势比较 一、开源软件的优劣势 优势 劣势 二、闭源软件的优劣势 优势 劣势 二、开源和闭源对大模型技术发展的影响 一、机器学习领域 二、自然语言处理领域 三、数据共享、算法创新与业务拓展的差异 三、开源与闭源的商业模式比较 一、盈…

【项目管理】PMO技能树21项参照

导读&#xff1a;PMO技能树让你能够有全局视野&#xff0c;让你对照着检查自己的能力是否掌握。技能树提供了构建个人知识体系参照和地图导航&#xff0c;不至于迷失方向。 目录 1、PMO层次概览 2、技能树 2.1 项目管理流程 2.2 项目组合管理 2.3 风险管理 2.4 项目资源管…

Python数据分析实战① Python实现数据可视化

文章目录 一、数据可视化介绍二、matplotlib和pandas画图1.matplotlib简介和简单使用2.matplotlib常见作图类型3.使用pandas画图4.pandas中绘图与matplotlib结合使用 三、订单数据分析展示四、Titanic灾难数据分析显示 一、数据可视化介绍 数据可视化是指将数据放在可视环境中…