码迷,mamicode.com
首页 > 其他好文 > 详细

OSGI框架中通过BundleContext对象对服务的注册与引用

时间:2017-02-16 23:38:04      阅读:3521      评论:0      收藏:0      [点我收藏+]

标签:.class   print   lock   注册   cer   out   code   定义   spring容器   

  • BundleActivator

    • 在每个Bundle新建时都会默认生成Activator类,该类实现了BundleActivator类,实现了其start()和stop()两个方法 
  • BundleContext

    • 框架运行时,容器中存有唯一的BundleContext对象,与Spring容器中唯一的ApplicationContext对象同理,再后期随笔中对框架通过引入Spring DM对服务进行管理后,会对两者的关系进行进一步的讲解,在此则只对使用到BundleContext中所提供的registerService方法进行注册服务、getServiceReference方法获取服务引用及getService获取最终指向的服务对象,三个方法的调用进行叙述:
      • registerService

    • public void start(BundleContext bundleContext) throws Exception {
              Activator.context = bundleContext;
              IHelloService service = new CnHelloServiceImpl();
              System.out.println(bundleContext.getBundle().getLocation());
              System.out.println(bundleContext.getBundle().getBundleId());
              System.out.println(bundleContext.getBundle().getSymbolicName());
              context.registerService(IHelloService.class, service, null);
          }

       

        第一个参数:注册服务的类型

        第二个参数:服务所指向的对象

        第三个参数:属于配置参数,如配置相同类型的服务的排序

      • getServiceReference与getService配合

        • ServiceReference<IHelloService> serviceReference = context.getServiceReference(IHelloService.class);
                  if(null!=serviceReference){
                      IHelloService service = context.getService(serviceReference);
                      if(null!=service){
                          System.out.println(service.sayHello("1111"));
                          System.out.println(context.getBundle().getSymbolicName());
                      }
                      context.ungetService(serviceReference);
                  }else{
                      System.out.println(context.getBundle().getSymbolicName()+":无法获取服务。");
                  }

           

          通过context.getServiceReference(IHelloService.class)获取到容器中服务类型为IHelloService的服务引用,如果用多个同一类型的服务,则默认获取排序最前的一个,但在正常开发中,是很少会出现发布同一类型的多个服务,然后再调用context.getService(serviceReference)方法获取到服务引用中的最终指向服务的对象,也就是在注册服务时,通过new关键字创建的对象,到此就已经可以达到服务注册与服务引用的功能实现,把它想象成Spring,其实这跟Spring对Bean的定义与注入,所达到的功能如同一辙,只是底层的实现方式不同而已。 


          下一篇随笔将对通过Spring DM如何对服务对象的管理与注入     

 

OSGI框架中通过BundleContext对象对服务的注册与引用

标签:.class   print   lock   注册   cer   out   code   定义   spring容器   

原文地址:http://www.cnblogs.com/xufan/p/6407344.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!