`
snoopy7713
  • 浏览: 1123489 次
  • 性别: Icon_minigender_2
  • 来自: 火星郊区
博客专栏
Group-logo
OSGi
浏览量:0
社区版块
存档分类
最新评论

服务工厂 - Bundle消费者返回不同的服务对象

    博客分类:
  • OSGi
阅读更多

一般情况下,服务对象在注册后,任何其它的Bundle在请求该服务时,OSGi容器都是返回同一个对象。如果我们需要为每一个 Bundle消费者返回不同的服务对象,或者,在真正需要该服务对象时才创建。对于这些情况,我们可以创建一个实现ServiceFactory接口的 类,把该类的对象注册为服务(不是注册实际的服务对象),这样,当Bundle请求该服务时,ServiceFactory实现类将接管该请求,为每个 Bundle新建一个实际的服务对象。以下是服务工厂的使用范例源码:

 

1、服务接口及其实现类

Java代码  收藏代码
  1. public   interface  HelloService {  
  2.     public  String sayHello(String name);  
  3. }  

 

Java代码  收藏代码
  1. public   class  HelloServiceImpl  implements  HelloService {  
  2.     public  String sayHello(String name) {  
  3.         return   "Hello "  + name;  
  4.     }  
  5. }  

 

2、服务工厂类

Java代码  收藏代码
  1. public   class  HelloServiceFactory  implements  ServiceFactory {  
  2.     //当请求服务时,OSGi容器会调用该方法返回服务对象。   
  3.     //当服务对象不为null时,OSGi框架会缓存这个对象,即对于同一个消费者,将返回同一个服务对象。   
  4.     public  Object getService(Bundle bundle, ServiceRegistration serviceRegistration) {  
  5.         System.out.println("创建HelloService对象:"  + bundle.getSymbolicName());  
  6.         HelloService helloService = new  HelloServiceImpl();  
  7.         return  helloService;  
  8.     }  
  9.   
  10.     //当Bundle释放服务时,OSGi容器会调用该方法   
  11.     public   void  ungetService(Bundle bundle, ServiceRegistration serviceRegistration, Object service) {  
  12.         System.out.println("释放HelloService对象:"  + bundle.getSymbolicName());  
  13.     }  
  14. }  

 

3、Bundle激活器类

Java代码  收藏代码
  1. public   class  Activator  implements  BundleActivator {  
  2.     ServiceRegistration serviceRegistration;  
  3.       
  4.     public   void  start(BundleContext context)  throws  Exception {  
  5.         //注册服务   
  6.         HelloServiceFactory helloServiceFactory = new  HelloServiceFactory();  
  7.         serviceRegistration =  context.registerService(HelloService.class .getName(), helloServiceFactory,  null );  
  8.           
  9.         //获取服务(通过服务工厂取得)   
  10.         ServiceReference serviceReference = context.getServiceReference(HelloService.class .getName());  
  11.         HelloService selloService = (HelloService)context.getService(serviceReference);  
  12.         System.out.println("1: "  + selloService.sayHello( "cjm" ));  
  13.           
  14.         //第二次取得的服务对象与之前取得的是同一个对象   
  15.         serviceReference = context.getServiceReference(HelloService.class .getName());  
  16.         selloService = (HelloService)context.getService(serviceReference);  
  17.         System.out.println("2: "  + selloService.sayHello( "cjm" ));  
  18.     }  
  19.       
  20.     public   void  stop(BundleContext context)  throws  Exception {  
  21.         serviceRegistration.unregister();  
  22.     }  
  23. }  

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics