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


    • 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如何对服务对象的管理与注入     

  • 相关阅读:
    Caused by: java.lang.IllegalArgumentException: Not an managed type: class XXX
    SpringBoot配置文件详细解析
    解决eclipse环境下maven项目tomcat启动,未加载到项目的问题
    CSS+元素,鼠标事件触发鼠标模形变成手状的形状
    LeetCode-Wildcard Matching
    LeetCode-NQueensII
    LeetCode-Climbing Stairs
    LeetCode-Word Search
    LeetCode-Minimum Window Substring
    LeetCode-Largest Rectangle in Histogram
  • 原文地址:https://www.cnblogs.com/xufan/p/6407344.html
Copyright © 2020-2023  润新知