Search code examples
javaeclipsedependency-injectione4

Eclipse 4 Injecting an OSGI Service


I want to turn a Settings class into an OSGI declarative service which e4 can inject.

I have created the service in 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
private IPrivacySettingsService privacySettingsService;

But I am getting a NullPointerException.


Solution

  • Looking at your code, your problem seems to be, that you are creating the ApprovalDialogJob with the new operator. This way the DI engine will not manage the object, hence it will not inject any values.

    You need to use the ContextInjectionFactory to create your class:

    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:

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

    Hope this helps.