在日常开发中,我们通常都是引入别人开发好的 SDK(如 xxx-spring-boot-starter),这样就可以很方便地在项目中使用别人开发好的代码。那么,接下来我就介绍一下如何开发一个简易的 SDK。
开发步骤
先创建一个 SpringBoot 项目,可以像如图一样先精简一下项目
接下来是 maven 的配置文件 pom.xml
在包下建一个测试用的客户端 TestClient,里面只有一个方法 返回姓名和年龄(这里是为了测试方便)
package com.weikey.testsdk.client;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 测试客户端
*
* @author wei-key
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class TestClient {
private String name;
private Integer age;
public String getNameAndAge() {
return "name: " + name + "; age: " + age + ";";
}
}
再建一个配置类 TestClientConfig
package com.weikey.testsdk.config;
import com.weikey.testsdk.client.TestClient;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration // 声明为配置类
@ConfigurationProperties("test.client") // 配置绑定,以"test.client"为前缀的配置项 与 类中属性 绑定
@Data
public class TestClientConfig {
private String name;
private Integer age;
@Bean("testClient") // 生成的bean交给spring管理,这样引入sdk后就可以注入使用
public TestClient getTestClient() {
return new TestClient(name, age);
}
}
在 resources 目录下建一个 META-INF 目录,META-INF 下建 spring.factories 文件,开启自动装配
等号右边是 配置类 TestClientConfig 的完整路径
org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.weikey.testsdk.config.TestClientConfig
完成后的项目结构图
将项目打包安装到本地
测试
在其他项目中拷贝坐标即可引入 SDK
配置文件中有代码提示
test:
client:
name: wei-key
age: 20
测试代码
@SpringBootTest
class MyTestApplicationTests {
@Resource
private TestClient testClient;
@Test
public void test() {
System.out.println(testClient.getNameAndAge());
}
}
测试结果
name: wei-key; age: 20;
总结
通过以上步骤即可开发出一个SDK,这样只需要在项目中引入SDK后,在配置文件中对属性进行配置,即可非常方便地使用别人开发好的代码。
如果有帮助的话,可以点个赞支持一下嘛
🙏