public interface GreetingService { void sayHello(); } public class GreetingServiceImpl implements GreetingService { public void sayHello() { System.out.println("Hello, OSGi!"); } } public class Activator implements BundleActivator { public void start(BundleContext context) { GreetingService greetingService = new GreetingServiceImpl(); context.registerService(GreetingService.class.getName(), greetingService, null); } public void stop(BundleContext context) { } } public class Consumer { private ServiceTracker<GreetingService, GreetingService> serviceTracker; public Consumer(BundleContext context) { serviceTracker = new ServiceTracker<>(context, GreetingService.class, null); serviceTracker.open(); } public void useService() { GreetingService greetingService = serviceTracker.getService(); if (greetingService != null) { greetingService.sayHello(); } else { System.out.println("GreetingService not found!"); } } public void stop() { serviceTracker.close(); } } public class Activator implements BundleActivator { private Consumer consumer; public void start(BundleContext context) { consumer = new Consumer(context); consumer.useService(); } public void stop(BundleContext context) { consumer.stop(); } }


上一篇:
下一篇:
切换中文