如何解决如何在 Spring Boot 中通过本机库正确连接到外部服务
在 Spring Boot 中工作,想使用原生库来连接和使用外部存储系统。我下载了 JAR 文件和 dll 文件,通过 Maven 导入了 JAR。现在我想创建一个 Bean 来充当@Service 的基本功能:上传、下载等。
所以它看起来像这样:
@Service
public class StorageSystemClient {
private NativeLibrary nativeLibrary;
public StorageSystemClient() {
String url = "...";
this.nativeLibrary = NativeLibraryConnector.connect(url);
}
public File downloadFile(String filename) {
return this.nativeLibrary.download(filename);
}
}
问题:我不喜欢在 StorageSystemClient
构造函数中连接进程。
问题:执行此连接一次的正确方法是什么,例如在 bean 初始化阶段?
解决方法
我认为你可以使用 PostConstruct
,比如
@PostConstruct
private void init() {
//establish connection
}
它专为在 bean 构造之后运行一次初始化代码而制作。
,我认为您使用本机库这一事实并不重要。
对于我建议从 StorageSystemClient
中排除连接逻辑并让 spring 处理它的解决方案。这样,StorageSystemClient
将变得可进行单元测试,并且总体上是清晰的。
NativeLibrary
将由 spring 管理。
您可能会得到以下代码:
@Configuration
public void NativeLibraryConfig {
@Bean
public NativeLibrary nativeLibrary() {
String url = "..."; // can be externalized to configuration,or whatever you need,// in any case StorageSystemClient should not resolve the url by itself
return NativeLibraryConnector.connect(url);
}
}
@Service
public class StorageSystemClient {
private NativeLibrary nativeLibrary;
public StorageSystemClient(NativeLibrary nativeLibrary) {
this.nativeLibrary = nativeLibrary;
}
public File downloadFile(String filename) {
return this.nativeLibrary.download(filename);
}
}
,
只需使用依赖注入。 NativeLibraryConnector.connect(url);
只是一个工厂方法。
@Bean
public NativeLibrary nativeLibrary(String url) {
return NativeLibraryConnector.connect(url);
}
@Service
public class StorageSystemClient {
private final NativeLibrary nativeLibrary;
public StorageSystemClient(NativeLibrary nativeLibrary) {
this.nativeLibrary = this.nativeLibrary;
}
public File downloadFile(String filename) {
return this.nativeLibrary.download(filename);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。