Springboot dynamically loads native class library

  springboot

Order

There are times when you need to use local class libraries to implement some functions, such as using jni to access so library files under linux. This time you need to involve the loading of library files. This article introduces how to load library files dynamically, that is, to put library files into engineering projects to facilitate the portability of engineering, and then load them at runtime.

Dynamic loading

 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);
            }
        }
    }
}    

Place the so file in the resources directory of the project.

Use

public class DemoJniClient{
    public native int helloWorld(String arg);
    static {
        LibLoader.loadLib("demo.so");
    }
}