osgi.bundles=org.eclipse.equinox.common@2:start, org.eclipse.equinox.registry@2:start, org.eclipse.core.runtime@start
osgi.console=*
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.launch.Framework;
import org.osgi.framework.launch.FrameworkFactory;
import java.util.HashMap;
import java.util.Map;
public class OsgiLauncher {
private Framework framework;
private BundleContext context;
public void start() {
Map<String, String> config = new HashMap<>();
config.put("org.osgi.framework.storage.clean", "onFirstInit");
FrameworkFactory factory = new org.eclipse.osgi.framework.internal.core.FrameworkFactory();
framework = factory.newFramework(config);
try {
framework.start();
context = framework.getBundleContext();
} catch (BundleException e) {
e.printStackTrace();
}
}
public void stop() {
try {
framework.stop();
framework.waitForStop(0);
e.printStackTrace();
}
}
}
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import javax.naming.Context;
import javax.naming.InitialContext;
import java.util.Properties;
public class ServiceRegistry implements BundleActivator {
private ServiceRegistration<MyService> registration;
@Override
public void start(BundleContext context) throws Exception {
Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.apache.naming.java.javaURLContextFactory");
properties.put(Context.URL_PKG_PREFIXES, "org.apache.naming");
Context initialContext = new InitialContext(properties);
MyService service = new MyServiceImpl();
registration = context.registerService(MyService.class, service, null);
initialContext.bind("java:comp/env/myService", service);
}
@Override
public void stop(BundleContext context) throws Exception {
initialContext.unbind("java:comp/env/myService");
registration.unregister();
initialContext.close();
}
}
public interface MyService {
void doSomething();
}
public class MyServiceImpl implements MyService {
@Override
public void doSomething() {
System.out.println("Doing something...");
}
}
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import javax.naming.Context;
import javax.naming.InitialContext;
public class ServiceConsumer implements BundleActivator {
@Override
public void start(BundleContext context) throws Exception {
Context initialContext = new InitialContext();
MyService service = (MyService) initialContext.lookup("java:comp/env/myService");
service.doSomething();
}
@Override
public void stop(BundleContext context) throws Exception {
}
}