Issue
Working in Spring Boot and want to use native library in order to connect to and use external storage system. I downloaded JAR file and dll files, imported JAR via Maven. Now I want to create Bean that will serve as @Service with basic functionalities: upload, download, etc.
So it looks like this:
@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);
}
}
Problem: What I don't like here is connecting process in StorageSystemClient
constructor.
Question: What should be proper way to perform this connection once, in bean initializing phase for example?
Solution
I don't think that the fact that you're working with native library matters here.
Is for the solution I recommend excluding the connection logic from StorageSystemClient
and letting spring deal with it. This way the StorageSystemClient
will become unit testable and clear in general.
The NativeLibrary
will become managed by spring.
You might end up with the following code:
@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);
}
}
Answered By - Mark Bramnik