import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
public class Activator implements BundleActivator {
private ServiceRegistration<?> registration;
public void start(BundleContext context) throws Exception {
// Register a service
MyService service = new MyServiceImpl();
registration = context.registerService(MyService.class.getName(), service, null);
System.out.println("Service registered");
}
public void stop(BundleContext context) throws Exception {
// Unregister the service
registration.unregister();
System.out.println("Service unregistered");
}
}
public interface MyService {
void doSomething();
}
public class MyServiceImpl implements MyService {
public void doSomething() {
System.out.println("Doing something...");
}
}
Bundle-ManifestVersion: 2
Bundle-Name: My Bundle
Bundle-SymbolicName: com.example.mybundle
Bundle-Version: 1.0.0
Bundle-Activator: com.example.mybundle.Activator
Export-Package: com.example.mybundle
bash
osgi> install file:/path/to/mybundle.jar
osgi> start <bundle-id>
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.osgi.framework.ServiceReference;
public class Consumer {
public void useService() {
BundleContext context = FrameworkUtil.getBundle(Consumer.class).getBundleContext();
ServiceReference<MyService> reference = context.getServiceReference(MyService.class);
MyService service = context.getService(reference);
service.doSomething();
context.ungetService(reference);
}
}