i want to integrate a .so library in spring boot application. use JNI to integrate it.…
- User
i want to integrate a .so library in spring boot application. use JNI to integrate it. give me end to end code including names of the files too?
- Assistant
i want to integrate a .so library in spring boot application. use JNI to integrate it. give me end to end code including names of the files too?
Integrating a .so (shared object) library into a Spring Boot application using JNI involves several steps:
.so LibraryBelow is an end-to-end guide, including all necessary files and their contents.
Assuming you are using Maven for your Spring Boot project, your project structure will look like this:
spring-boot-jni-example/
├── pom.xml
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/example/demo/
│ │ │ ├── DemoApplication.java
│ │ │ └── NativeLib.java
│ │ └── resources/
│ │ └── application.properties
├── NativeLibImpl.c
└── README.md
pom.xmlFirst, set up your pom.xml to include necessary dependencies for Spring Boot.
<!-- pom.xml -->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>spring-boot-jni-example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>spring-boot-jni-example</name>
<description>Spring Boot Application with JNI Integration</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>17</java.version> <!-- Ensure you have appropriate Java version -->
</properties>
<dependencies>
<!-- Spring Boot Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<!-- Testing Dependencies -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<!-- Spring Boot Maven Plugin -->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<!-- Compiler Plugin to Generate JNI Headers -->
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<compilerArgs>
<arg>-h</arg>
<arg>${project.build.directory}/classes</arg>
</compilerArgs>
</configuration>
</plugin>
</plugins>
</build>
</project>
Create a Java class that declares the native methods and loads the .so library.
// src/main/java/com/example/demo/NativeLib.java
package com.example.demo;
public class NativeLib {
// Load the shared library named "native-lib"
static {
System.loadLibrary("native-lib"); // The name without 'lib' prefix and '.so' suffix
}
// Declare native methods
public native int add(int a, int b);
public native String greet(String name);
}
After compiling the Java class, generate the JNI header file which will be used in the C implementation.
Compile the Java Classes and Generate Headers
Run the following Maven command in the project root:
mvn clean compile
This will generate the JNI header file in target/classes/com/example/demo/NativeLib.h.
Locate the Generated Header
The generated header will look something like this:
/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class com_example_demo_NativeLib */
#ifndef _Included_com_example_demo_NativeLib
#define _Included_com_example_demo_NativeLib
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: com_example_demo_NativeLib
* Method: add
* Signature: (II)I
*/
JNIEXPORT jint JNICALL Java_com_example_demo_NativeLib_add
(JNIEnv *, jobject, jint, jint);
/*
* Class: com_example_demo_NativeLib
* Method: greet
* Signature: (Ljava/lang/String;)Ljava/lang/String;
*/
JNIEXPORT jstring JNICALL Java_com_example_demo_NativeLib_greet
(JNIEnv *, jobject, jstring);
#ifdef __cplusplus
}
#endif
#endif
Create the C implementation file that includes the generated header and implements the native methods.
/* NativeLibImpl.c */
#include <jni.h>
#include "com_example_demo_NativeLib.h" // Adjust the path if necessary
#include <string.h>
// Implementation of the native 'add' method
JNIEXPORT jint JNICALL Java_com_example_demo_NativeLib_add(JNIEnv *env, jobject obj, jint a, jint b) {
return a + b;
}
// Implementation of the native 'greet' method
JNIEXPORT jstring JNICALL Java_com_example_demo_NativeLib_greet(JNIEnv *env, jobject obj, jstring name) {
// Convert jstring to C string
const char *nameCStr = (*env)->GetStringUTFChars(env, name, 0);
// Create greeting message
char greeting[256];
snprintf(greeting, sizeof(greeting), "Hello, %s!", nameCStr);
// Release the memory of the original string
(*env)->ReleaseStringUTFChars(env, name, nameCStr);
// Convert C string back to jstring
return (*env)->NewStringUTF(env, greeting);
}
Notes:
com_example_demo_NativeLib.h)..so LibrarySet Up Environment Variables
Ensure that JAVA_HOME is set to your JDK installation. For example:
export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64
export PATH=$JAVA_HOME/bin:$PATH
Compile the C Code
Use gcc to compile the C code into a shared library (.so).
gcc -I${JAVA_HOME}/include -I${JAVA_HOME}/include/linux -fPIC -shared -o libnative-lib.so NativeLibImpl.c
Explanation:
-I${JAVA_HOME}/include and -I${JAVA_HOME}/include/linux include JNI headers.-fPIC generates position-independent code required for shared libraries.-shared creates a shared library.-o libnative-lib.so sets the output file name (must start with lib and end with .so).Place the .so Library in a Known Location
For simplicity, place libnative-lib.so in src/main/resources/ or any directory you prefer. Ensure the JVM can locate it.
There are multiple ways to inform the JVM about the location of the .so library. One common method is to place it in a directory that's part of java.library.path.
For this example, we'll place libnative-lib.so in src/main/resources/ and load it from there.
Alternatively, you can specify the library path when running the application using -Djava.library.path.
Create the main Spring Boot application class that uses the native methods.
// src/main/java/com/example/demo/DemoApplication.java
package com.example.demo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DemoApplication {
private final NativeLib nativeLib;
public DemoApplication(NativeLib nativeLib) {
this.nativeLib = nativeLib;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public NativeLib nativeLib() {
return new NativeLib();
}
@Bean
public CommandLineRunner run() {
return args -> {
int sum = nativeLib.add(5, 7);
String greeting = nativeLib.greet("World");
System.out.println("Sum from native lib: " + sum);
System.out.println("Greeting from native lib: " + greeting);
};
}
}
Explanation:
NativeLib instance is injected as a Spring Bean.CommandLineRunner executes and calls native methods, printing their results..so LibraryTo ensure that the .so file is available at runtime, you can configure Maven to copy it to the target directory or specify its location.
Example: Place libnative-lib.so in src/main/resources/ and add the following to your DemoApplication.java to load it from the classpath.
// Inside NativeLib.java
static {
try {
// Extract the .so file from the resources to a temp directory
InputStream in = NativeLib.class.getResourceAsStream("/libnative-lib.so");
byte[] buffer = new byte[in.available()];
in.read(buffer);
in.close();
// Create temporary file
File temp = File.createTempFile("libnative-lib", ".so");
temp.deleteOnExit();
try (FileOutputStream fos = new FileOutputStream(temp)) {
fos.write(buffer);
}
// Load the library
System.load(temp.getAbsolutePath());
} catch (IOException e) {
throw new RuntimeException("Failed to load native library", e);
}
}
Alternatively:
You can specify the library path when running the application.
java -Djava.library.path=/path/to/lib -jar target/spring-boot-jni-example-0.0.1-SNAPSHOT.jar
Ensure that /path/to/lib contains libnative-lib.so.
Build the Project
mvn clean package
Run the Application
java -Djava.library.path=./ -jar target/spring-boot-jni-example-0.0.1-SNAPSHOT.jar
Note: Adjust java.library.path to point to the directory containing libnative-lib.so.
Expected Output
Sum from native lib: 12
Greeting from native lib: Hello, World!
// src/main/java/com/example/demo/NativeLib.java
package com.example.demo;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class NativeLib {
// Static block to load the native library
static {
try {
// Extract the .so file from the resources to a temp directory
InputStream in = NativeLib.class.getResourceAsStream("/libnative-lib.so");
if (in == null) {
throw new RuntimeException("Native library not found in resources");
}
byte[] buffer = new byte[in.available()];
in.read(buffer);
in.close();
// Create temporary file
File temp = File.createTempFile("libnative-lib", ".so");
temp.deleteOnExit();
try (FileOutputStream fos = new FileOutputStream(temp)) {
fos.write(buffer);
}
// Load the library
System.load(temp.getAbsolutePath());
} catch (IOException e) {
throw new RuntimeException("Failed to load native library", e);
}
}
// Declare native methods
public native int add(int a, int b);
public native String greet(String name);
}
// src/main/java/com/example/demo/DemoApplication.java
package com.example.demo;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class DemoApplication {
private final NativeLib nativeLib;
public DemoApplication(NativeLib nativeLib) {
this.nativeLib = nativeLib;
}
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@Bean
public NativeLib nativeLib() {
return new NativeLib();
}
@Bean
public CommandLineRunner run() {
return args -> {
int sum = nativeLib.add(5, 7);
String greeting = nativeLib.greet("World");
System.out.println("Sum from native lib: " + sum);
System.out.println("Greeting from native lib: " + greeting);
};
}
}
/* NativeLibImpl.c */
#include <jni.h>
#include "com_example_demo_NativeLib.h" // Adjust path if necessary
#include <string.h>
// Implementation of native 'add' method
JNIEXPORT jint JNICALL Java_com_example_demo_NativeLib_add(JNIEnv *env, jobject obj, jint a, jint b) {
return a + b;
}
// Implementation of native 'greet' method
JNIEXPORT jstring JNICALL Java_com_example_demo_NativeLib_greet(JNIEnv *env, jobject obj, jstring name) {
const char *nameCStr = (*env)->GetStringUTFChars(env, name, NULL);
if (nameCStr == NULL) {
return NULL; // OutOfMemoryError already thrown
}
// Create greeting message
char greeting[256];
snprintf(greeting, sizeof(greeting), "Hello, %s!", nameCStr);
// Release memory of the original string
(*env)->ReleaseStringUTFChars(env, name, nameCStr);
// Return new Java string
return (*env)->NewStringUTF(env, greeting);
}
Error Handling: Always check for NULL or exceptions when dealing with JNI to prevent crashes.
Library Path: Ensuring the JVM can locate your .so file is crucial. You can manage this by placing the library in a standard location or dynamically loading it from your code as shown above.
Cross-Platform Considerations: .so files are for Linux. For other operating systems, you'll need to create corresponding shared libraries (.dll for Windows, .dylib for macOS) and adjust the loading mechanism accordingly.
Security Considerations: Be cautious when loading native libraries, especially from external sources, as they can compromise the security of your application.
By following the above steps, you can successfully integrate a .so library into your Spring Boot application using JNI. This setup allows you to leverage native code performance and access platform-specific functionalities within your Java application.