简体   繁体   English

Eclipse 4注入OSGI服务

[英]Eclipse 4 Injecting an OSGI Service

I want to turn a Settings class into an OSGI declarative service which e4 can inject. 我想将Settings类变成e4可以注入的OSGI声明式服务。

I have created the service in OSGI-INF/settingsService.xml : 我已经在OSGI-INF / settingsService.xml中创建了服务:

<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0" name="org.eclipse.recommenders.privacy.rcp">
        <implementation class="org.eclipse.recommenders.privacy.rcp.PrivacySettingsService"/>
    <service>
        <provide interface="org.eclipse.recommenders.privacy.rcp.IPrivacySettingsService"/>
    </service>
</scr:component>

And I have annotated the variable with @Inject as described here: http://toedter.com/2010/06/28/eclipse-4-0-dependency-injection-and-osgi-declarative-services/ 而且我已经用@Inject注释了变量,如下所述: http : //toedter.com/2010/06/28/eclipse-4-0-dependency-injection-and-osgi-declarative-services/

@Inject
private IPrivacySettingsService privacySettingsService;

But I am getting a NullPointerException . 但是我得到了NullPointerException

Looking at your code, your problem seems to be, that you are creating the ApprovalDialogJob with the new operator. 查看您的代码,您的问题似乎是,您正在使用new运算符创建ApprovalDialogJob This way the DI engine will not manage the object, hence it will not inject any values. 这样,DI引擎将不会管理对象,因此不会注入任何值。

You need to use the ContextInjectionFactory to create your class: 您需要使用ContextInjectionFactory创建您的类:

ApprovalDialogJob job = new ApprovalDialogJob(extensionReader);
ContextInjectionFactory.inject(job, eclipseContext);

Where eclipseContext is an instance of IEclipseContext , which you can either obtain by injecting it into Startup or by using: 凡eclipseContext是一个实例IEclipseContext ,您可以通过将其注入获得Startup或使用:

BundleContext bundleContext = FrameworkUtil.getBundle(Startup.class).getBundleContext();
IEclipseContext context = EclipseContextFactory.getServiceContext(bundleContext);

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM