Using native dependencies inside Maven

为君一笑 提交于 2019-12-04 11:38:06

Answering my own question: http://web.archive.org/web/20120308042202/http://www.buildanddeploy.com/node/17

In short, you can use the maven-dependency-plugin:unpack goal to extract the libraries into a known path, and pass that into java.library.path:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-dependency-plugin</artifactId>
  <executions>
    <execution>
      <id>unpack</id>
      <phase>compile</phase>
      <goals>
        <goal>unpack</goal>
      </goals>
      <configuration>
        <artifactItems>
          <artifactItem>
            <groupId>org.jdesktop</groupId>
            <artifactId>jdic-native</artifactId>
            <version>${jdic.version}</version>
            <classifier>${build.type}</classifier>
            <type>jar</type>
            <overWrite>true</overWrite>
            <outputDirectory>${project.build.directory}/lib</outputDirectory>
          </artifactItem>
        </artifactItems>
      </configuration>
    </execution>
  </executions>
</plugin>

Since System.load() can't load libraries from within a jar, you will have to use a custom loader which extracts the library to a temporary file at runtime. Projects With JNI discusses this approach and provide code for the custom loader.

Library loader

We now have our JNI library on the class path, so we need a way of loading it. I created a separate project which would extract JNI libraries from the class path, then load them. Find it at http://opensource.mxtelecom.com/maven/repo/com/wapmx/native/mx-native-loader/1.2/. This is added as a dependency to the pom, obviously.

To use it, call com.wapmx.nativeutils.jniloader.NativeLoader.loadLibrary(libname). More information is in the javadoc for NativeLoader.

I generally prefer to wrap such things in a try/catch block, as follows:

public class Sqrt {
    static {
        try {
            NativeLoader.loadLibrary("sqrt");
        } catch (Throwable e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
    /* ... class body ... */
}

An alternative would be to unpack the dependency, for example using dependency:unpack.

You can use the maven dependency plugin to copy the artifacts to a predefined path:

http://maven.apache.org/plugins/maven-dependency-plugin/examples/copying-artifacts.html

If the DLL is inside the JAR, then you will need to copy it out to a directory before it can be loaded. (JARs that include native libraries usually do this themselves.) If your JAR isn't doing this, then you can use Class.getResourceAsStream() and write this to a directory that you've added to the java.library.path.

For an example of this, see loadNativeLibrary in JNA. It uses this technique to load it's own library (a JNI library) from a JAR.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!