2017-05-04 36 views
3

不幸的是,我找不到一種方式來創建一個osgi服務與編程解析引用。這是一個衆所周知的事實,OSGi將服務創建爲單例對象。由於某種原因,我需要手動創建新的服務實例。是否有可能創建OSGI服務與注入解決

的情況:

@Service(ICasualService.class) 
@Component(immediate = true, label = "Casual Service") 
public class CasualService implements ICasualService { 

    @Reference 
    private ConfigurationAdmin configurationAdmin; 
} 

使用包上下文我可以登記自己的服務:

private BundleContext bundleContext; 
ICasualService casualService = new CasualService(); 
Dictionary props = new Properties(); 
bundleContext.registerService(ICasualService.class.getName(), casualService, props); 

然而,這種方式configurationAdmin爲空在新創建的服務。

問題是,是否有可能以編程方式創建服務的新實例?

謝謝。

更新:解決方案應該爲Felix(OSGi實現)工作。

回答

5

您可以使用ComponentFactory來創建組件的實例。請參閱this article at Vogella

使用此要創建的編程組件上:從它

@Reference(target = "(component.factory=fipro.oneshot.factory)") 
    private ComponentFactory factory; 

,並創建一個實例:

@Component(factory="fipro.oneshot.factory") 

然後在另一個組件,您可以得到ComponentFactory

ComponentInstance instance = this.factory.newInstance(null); 
OneShot shooter = (OneShot) instance.getInstance(); 
+0

非常感謝!有用。此外,1.通過這種方式,您可以通過將適當的配置參數傳遞給this.factory.newInstance(Dictionary)方法來創建新的服務; 2.它創建新的服務實例(以.newInstance(null)爲例,每次都返回相同的對象)。 –

相關問題