springboot動態加載native類庫

有些時候須要使用到本地類庫來實現一些功能,好比在linux下使用jni去訪問so庫文件,這個時候就須要涉及庫文件的加載。本文介紹一下如何動態加載庫文件,即把庫文件放到工程項目裏頭,方便工程的可移植性,而後在運行時去加載。java

動態加載

public class LibLoader {
    public static void loadLib(String libName) {
        String resourcePath = "/" + libName;
        String folderName = System.getProperty("java.io.tmpdir") + "/lib/";
        File folder = new File(folderName);
        folder.mkdirs();
        File libFile = new File(folder, libName);
        if (libFile.exists()) {
            System.load(libFile.getAbsolutePath());
        } else {
            try {
                InputStream in = LibLoader.class.getResourceAsStream(resourcePath);
                FileUtils.copyInputStreamToFile(in,libFile);
                in.close();
                System.load(libFile.getAbsolutePath());
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("Failed to load required lib", e);
            }
        }
    }
}

將so文件放在工程的resources目錄下linux

使用

public class DemoJniClient{
    public native int helloWorld(String arg);
    static {
        LibLoader.loadLib("demo.so");
    }
}
相關文章
相關標籤/搜索