import javax.naming.Context;
import javax.naming.InitialContext;
import java.util.Hashtable;
public class JNDIServiceImpl implements JNDIService {
@Override
public String performLookup(String name) {
try {
Hashtable<String, String> env = new Hashtable<>();
env.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.felix.jndi.InitialContextFactory");
Context context = new InitialContext(env);
return (String) context.lookup(name);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.util.tracker.ServiceTracker;
import your.package.name.JNDIService;
public class JNDIClient {
public static void main(String[] args) {
BundleContext context = FrameworkUtil.getBundle(JNDIClient.class).getBundleContext();
ServiceTracker<JNDIService, JNDIService> tracker = new ServiceTracker<>(context, JNDIService.class, null);
tracker.open();
JNDIService jndiService = tracker.getService();
String result = jndiService.performLookup("yourName");
System.out.println("JNDI lookup result: " + result);
tracker.close();
}
}
<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0"
xmlns:scr-ext="http://www.apache.org/xmlns/scr-ext/v1.3.0"
name="JNDIServiceImpl"
activate="activate"
deactivate="deactivate"
immediate="true">
<implementation class="your.package.name.JNDIServiceImpl"/>
<service>
<provide interface="your.package.name.JNDIService"/>
</service>
</scr:component>