`

OSGi框架-第二章- 在eclipse中使用Equinox 框架扩展自定义服务

阅读更多

1.注册一个自定义的服务:

1.定义一个服务,接口以及实现类。

2.把服务注册到OSGI框架中,OSGi 框架提供了两种注册方式,都是通过 BundleContext 类实现的:

 

  1. registerService(String,Object,Dictionary) 注册服务对象 object 到接口名 String 下,可以携带一个属性字典Dictionary
  2. registerService(String[],Object,Dictionary) 注册服务对象 object 到接口名数组 String[] 下,可以携带一个属性字典 Dictionary,即一个服务对象可以按照多个接口名字注册,因为类可以实现多个接口;
3.获取服务,OSGi 框架提供了两种获取服务的引用 ServiceReference 的方法:

 

  1. getServiceReference(String):根据接口的名字得到服务的引用;
  2. getServiceReferences(String,String):根据接口名和另外一个过滤器名字对应的过滤器得到服务的引用;
上面的注册服务应该跟获取服务的key保存一致,注册和获取都可以在插件的入口类的start方法中执行。

注册服务的代码:

public void start(BundleContext context) throws Exception { 
	    
    System.out.println("hello world"); 
    context.registerService( 
        IHello.class.getName(), 
        new DefaultHelloServiceImpl(), 
        null); 
	    
}
 获取服务的代码:

public void start(BundleContext context) throws Exception { 
System.out.println("hello world2"); 

/** 
* Test hello service from bundle1. 
*/ 
IHello hello1 = 
(IHello) context.getService( 
context.getServiceReference(IHello.class.getName())); 
System.out.println(hello1.getHello()); 
}
 
 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics