基于Spring DM管理的Bundle获取Spring上下文对象及指定Bean对象

  在讲述服务注册与引用的随笔中,有提到context.getServiceReferences()方法,通过该方法可以获取到OSGI框架容器中的指定类型的服务引用,从而获取到对应的服务对象。同时该方法还可以通过Bundle-SymbolicName名称获取到该Bundle中的Spring上下文对象,同样根据Spring上下文对象,我们也可以很好的获取到对应服务对象(服务对象,就是Spring中的一个Bean对象)

String callName = "com.sample.service.IHelloService.sayHello(msg)";
        String bundleSymbolicName = "com.sample.service.impl";
        bundleSymbolicName = "com.sample.service";
        String beanID = "com.sample.service.IHelloService";
        try {
            System.out.println(ApplicationContext.class.getName());
            
            Bundle[] bundles = context.getBundles();
            for (Bundle bundle : bundles) {
                if(bundle.getSymbolicName().startsWith(bundleSymbolicName)){
                    
                    
                        System.out.println(bundle.getSymbolicName());
                        ServiceReference[] ref = context.getServiceReferences(ApplicationContext.class.getName(), "(Bundle-SymbolicName=" + bundle.getSymbolicName() + ")");
                        if (ref == null || ref.length == 0) {
                            System.out.println("未找到对应服务");
                            continue;
                        }
                        
                        ApplicationContext springContext = (ApplicationContext) context.getService(ref[0]);
                        System.out.println(springContext.getBean(beanID));
          }

在上面这段代码中,除了引入Eclipse自动提示所需要的package,你会看到在springContext.getBean(beanID)这行代码中会报错

 对于这种问题导致的原因一定是,还有所需要依赖的包没有导入。熟悉Spring的朋友都知道,getBean()方法是在BeanFactory类中

因此,我们需要在OSGI开发环境中手动引入其所依赖的两个包,打开MANIFEST.MF文件,选中Dependencies标签页,点击Add,检索对应的Packages名,实现引入

 引入成功后,错误也就解决了!

原文地址:https://www.cnblogs.com/xufan/p/6408392.html