基於Spring DM管理的Bundle擷取Spring內容物件及指定Bean對象,bundlebean
在講述服務註冊與引用的隨筆中,有提到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名,實現引入
引入成功後,錯誤也就解決了!