Over a million developers have joined DZone.

Eclipse 4.0: Dependency Injection and OSGi Declarative Services

DZone's Guide to

Eclipse 4.0: Dependency Injection and OSGi Declarative Services

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

In my last post I explained how easy it is to inject your own objects. For the common use case that you want to specify an interface attribute but want an object being injected I showed a simple solution using a little factory. Another way of doing this is the use of OSGi declarative services (DS). But instead of creating a declarative service that implements the service interface you create a declarative service for a helper object that just registers your implementation class for the needed interface with the ContextInjectionFactory. So, the ContactPresentation code looks like this now:

private IContactView contactView;

public ContactPresenter(IContactView contactView) {
this.contactView = contactView;

The xml for the declarative service is in OSGI-INF/views.xml:

<?xml version="1.0" encoding="UTF-8"?>
<scr:component xmlns:scr="http://www.osgi.org/xmlns/scr/v1.1.0"
<implementation class="...mvp.views.ContactViewCreationFunction"/>
<provide interface="org.eclipse.e4.core.contexts.IContextFunction"/>
<property name="service.context.key" type="String"

The implementation class provides the interface org.eclipse.e4.core.contexts.IContextFunction and an additional property with the name service.context.key specifies the actual interface that the contact function is going to register. Here is the simple code for the ContactViewCreationFunction:

public class ContactViewCreationFunction extends ContextFunction {
public Object compute(IEclipseContext context) {
return ContextInjectionFactory.make(ContactView.class, context);
The only thing the ContactViewCreationFunction does is to bind the ConatcsView class to the context, using the above service.context.key to know the interface. I will check in the code soon, stay tuned…

It’s very important that you don’t forget to add the 2 manifest headers in the manifest.mf:

Service-Component: OSGI-INF/views.xml
Bundle-ActivationPolicy: lazy
I would like to thank Tom Schindl for giving me the tip not to forget the lazy Bundle-ActivationPolicy!

From http://www.toedter.com/blog/?p=222

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.


Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}