java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot3.x开发通用SDK

SpringBoot3.x中自定义开发通用SDK的实现

作者:米饭好好吃.

本文介绍了SpringBoot和Maven创建自定义的SDK,包括创建项目、修改配置、编写配置类、设置配置文件、构建Jar包等,具有一定的参考价值,感兴趣的可以了解一下

1. 前言

相信大家学习SpringBoot到现在,使用Maven构建项目时,会在pom.xml文件中引入各种各样的依赖,那么我们如何将自己常用的一些工具类库进行封装成starter或者SDK供其他项目使用呢,本博客就会带着大家一步一步创建自定义的SDK依赖

2. 前置准备

本博客基于的Java开发环境如下:

3. 开发步骤

3.1 创建项目

此处使用IDEA内置Spring Initializr初始化工具快速创建项目:

image.png

image.png

此处一定要勾选(Spring Configuration Processor依赖)

3.2 修改无关配置

3.2.1 设置项目版本

pom.xml文件中的项目版本改写成:<version>0.0.1<version>

image.png

3.2.2 删除Maven的build插件

将如下内容从pom.xml文件中删除

image.png

3.2.3 删除启动类

由于这不是一个Web项目,因此我们需要将启动类给删除

3.3 编写配置类

3.3.1 编写属性配置类

例如,下面该类用于读取配置文件中形如rice.executors.fixedPoolSize=10的变量

/**
 * 线程池属性类
 * @author 米饭好好吃
 */
@Configuration
@ConfigurationProperties(prefix = "rice.executors")
@Data
public class ExecutorProperties {
    private int fixedPoolSize; // num of threads
}

3.3.2 编写业务类

@Data
public class FixedExecutorTemplate {
    private ExecutorService executorService;

    public FixedExecutorTemplate(int fixedPoolSize) {
        this.executorService = Executors.newFixedThreadPool(fixedPoolSize);
    }

    public void submit(Runnable task) {
        this.executorService.submit(task);
    }
}

3.3.3 编写配置类

该类就用于注入不同的属性配置类对象,读取配置文件中的信息,然后创建出不同的bean实例供其他项目使用,本质就是省去了其余项目手动创建的麻烦!!!

/**
 * 项目配置类
 * @author 米饭好好吃
 */
@AutoConfiguration
@EnableConfigurationProperties({ExecutorProperties.class})
public class CommonConfig {
    @Resource
    private ExecutorProperties executorProperties;

    @Bean
    public FixedExecutorTemplate executorTemplate() {
        return new FixedExecutorTemplate(executorProperties.getFixedPoolSize());
    }
}

3.4 设置配置文件

下面我们还需要给其余项目在application.yml等文件中给予友好提示,类似于下图这样的效果:

image.png

详细步骤:

image.png

image.png

3.5 使用Maven构建成Jar包

接下来我们就可以借助Maven的install命令将项目构建成jar包,供其余项目引入:

image.png

如果出现以下错误,说明是测试的问题,只要将项目中的test目录删除或者在Maven配置面板中选择toggle skip test model选项即可省略执行测试的步骤:
构建完成后就可以在本地的Maven仓库目录找到所在jar包,默认路径为:C:\用户目录\.m2\repository\包名

image.png

3.6 测试

我们在别的项目中就可以引入jar包依赖观察能够正常使用:

image.png

此处我们也能在pom.xml文件中看到提示了:

image.png

编写控制类测试:

@RestController
@RequestMapping("/test")
public class ClientController {

    @Resource
    private FixedExecutorTemplate fixedExecutorTemplate;

    @GetMapping("/fixed")
    public void testFixed() {
        for (int i = 0; i < 10; i++) {
            int j = i;
            fixedExecutorTemplate.submit(() -> {
                System.out.println(j);
            });
        }
    }
}

到此这篇关于SpringBoot3.x中自定义开发通用SDK的实现的文章就介绍到这了,更多相关SpringBoot3.x通用SDK内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

您可能感兴趣的文章:
阅读全文