Loading native library with Spring Boot

Viewed 10068

I have a simple Spring Boot project which loads native libraries. The problem is that I have no idea how to specify the path to the native library when running the application.

I have read tons of posts explaining how to set java.library.path but every single one leads to

java.lang.UnsatisfiedLinkError: /path/to/lib/libconnector.so: libconnector.so: cannot open shared object file: No such file or directory

The project works if I run these two commands in a sequence from command line:

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/path/to/lib
./gradlew bootRun

The library is loaded and works. But I am unable to specify the library path in my gradle file. I tried

run {
    systemProperty 'java.library.path', file('/path/to/lib')
}

bootRun {
    systemProperty 'java.library.path', file('/path/to/lib')
}

and all sorts of variations of this. Also tried adding VM arguments to my IDE etc. but nothing works. Could someone explain what am I doing wrong?

This is how I load the native library (located in $projectRoot/lib):

static {
        // load connector library
        File lib = new File("lib/" + System.mapLibraryName("connector"));
        System.load(lib.getAbsolutePath());
}
4 Answers

I finally solved my problem. I should be passing LD_LIBRARY_PATH as an environment variable instead of java.library.path as system property when running the application.

The following Gradle modification solved my issue:

tasks.withType(JavaExec) {
    environment('LD_LIBRARY_PATH', 'lib')
}

You can write a init method to auto-set java.library.path, here are some codes:

    String path = "/path/to/lib";
    String path = System.getProperty("java.library.path");
    // if os is windows
        path += ";" + classPath.getCanonicalPath();
    // if os is linux
        path += ":" + classPath.getCanonicalPath();
    System.setProperty("java.library.path", path);

Note: run this method first.

try to load the lib from your class ( just to test)

NB : i'am not sure but if you need to use so file you must be on a linux OS.

public class Test {
       static {
    try {

        System.loadLibrary("yourSohere");
       // or System.load("/path/to/lib.so");
    }
  }
    }

You can simply use:

dependencies {
    compile files('libs/something_local.jar')
}
Related