一般情况下,服务对象在注册后,任何其它的Bundle在请求该服务时,OSGi容器都是返回同一个对象。如果我们需要为每一个 Bundle消费者返回不同的服务对象,或者,在真正需要该服务对象时才创建。对于这些情况,我们可以创建一个实现ServiceFactory接口的 类,把该类的对象注册为服务(不是注册实际的服务对象),这样,当Bundle请求该服务时,ServiceFactory实现类将接管该请求,为每个 Bundle新建一个实际的服务对象。以下是服务工厂的使用范例源码:
1、服务接口及其实现类
- public interface HelloService {
- public String sayHello(String name);
- }
- public class HelloServiceImpl implements HelloService {
- public String sayHello(String name) {
- return "Hello " + name;
- }
- }
2、服务工厂类
- public class HelloServiceFactory implements ServiceFactory {
- //当请求服务时,OSGi容器会调用该方法返回服务对象。
- //当服务对象不为null时,OSGi框架会缓存这个对象,即对于同一个消费者,将返回同一个服务对象。
- public Object getService(Bundle bundle, ServiceRegistration serviceRegistration) {
- System.out.println("创建HelloService对象:" + bundle.getSymbolicName());
- HelloService helloService = new HelloServiceImpl();
- return helloService;
- }
- //当Bundle释放服务时,OSGi容器会调用该方法
- public void ungetService(Bundle bundle, ServiceRegistration serviceRegistration, Object service) {
- System.out.println("释放HelloService对象:" + bundle.getSymbolicName());
- }
- }
3、Bundle激活器类
- public class Activator implements BundleActivator {
- ServiceRegistration serviceRegistration;
- public void start(BundleContext context) throws Exception {
- //注册服务
- HelloServiceFactory helloServiceFactory = new HelloServiceFactory();
- serviceRegistration = context.registerService(HelloService.class .getName(), helloServiceFactory, null );
- //获取服务(通过服务工厂取得)
- ServiceReference serviceReference = context.getServiceReference(HelloService.class .getName());
- HelloService selloService = (HelloService)context.getService(serviceReference);
- System.out.println("1: " + selloService.sayHello( "cjm" ));
- //第二次取得的服务对象与之前取得的是同一个对象
- serviceReference = context.getServiceReference(HelloService.class .getName());
- selloService = (HelloService)context.getService(serviceReference);
- System.out.println("2: " + selloService.sayHello( "cjm" ));
- }
- public void stop(BundleContext context) throws Exception {
- serviceRegistration.unregister();
- }
- }