SpringBootでSOファイルを読み込む方法

Spring Bootで.soファイルを読み込むには、以下の手順で行います。

  1. .soファイルをプロジェクトの任意のディレクトリ(例:src/main/resources/native ディレクトリ)に配置する
  2. pom.xml に org.springframework.boot:spring-boot-starter 依存と org.springframework.boot:spring-boot-maven-plugin プラグインをインポートする。
  3. src/main/javaにネイティブライブラリをロードするカスタムNativeLibraryLoaderクラスを作成するとします。サンプルコードは次のとおりです。
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Component
public class NativeLibraryLoader {

    public void loadLibrary(String libraryName) {
        try {
            File tempFile = File.createTempFile(libraryName, ".so");
            tempFile.deleteOnExit();

            try (InputStream is = getClass().getResourceAsStream("/native/" + libraryName + ".so");
                 FileOutputStream os = new FileOutputStream(tempFile)) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = is.read(buffer)) != -1) {
                    os.write(buffer, 0, bytesRead);
                }
            }

            System.load(tempFile.getAbsolutePath());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. @Autowired
  2. ネイティブライブラリローダ
  3. ロードライブラリ
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyApplication implements CommandLineRunner {

    @Autowired
    private NativeLibraryLoader nativeLibraryLoader;

    @Override
    public void run(String... args) throws Exception {
        nativeLibraryLoader.loadLibrary("myLibrary");
    }
}

以上のステップを実行することで、Spring Bootで.soファイルのロードが成功します。ライブラリー名と.soファイルのディレクトリは、必要に応じて変更してください。

bannerAds