Question

Spring noob here.

I have an osgi service defined as follows in one of my bundles:

<osgi:service id="myModelInterpreter" ref="myModelInterpreterService" interface="*.IModelInterpreter" />

I know I can access it from another bundle via the BundleContext doing getServiceReference (passing down IModelInterpreter.class.getName) and then getService.

Is there a way to get the service via the id (myModelInterpreter) instead of using the Interface (passed down as IModelInterpreter.class.getName to getServiceReference)?

Any help appreciated.

Was it helpful?

Solution

I dont think you can get the service by the id you specified in the spring config as it is an internal setting of the spring context. What you can do is add some service proprties to the service and filter for them.

Like this:

<service ref="myModelInterpreterService" interface="*.IModelInterpreter">
  <service-properties>
    <beans:entry key="myId" value="myModelInterpreter"/>
  </service-properties>
</service>

Then in the other bundle you can filter for the properties:

<reference id="myModelInterpreterService" interface="com.xyz.IModelInterpreter"
  filter="(myId=myModelInterpreter)"/>

OTHER TIPS

Since you are already using Spring DM to declare your service, the simplest way to consume it is to do the same with another dm config.

<osgi:reference id="modelInterpreter" interface="IModelInterpreter" />

This can also be represented like this to filter to a specific Spring bean.

<osgi:reference id="modelInterpreter" bean-name="myModelInterpreter" interface="IModelInterpreter" />

Then you simply use the bean "modelInterpreter in your regular Spring config in the consumer bundle. This same line can be accomplished using the bean-name as well, but I am pretty sure it will still require the interface or interfaces attribute, as these are the only accepted means of looking up OSGi services. Using the bean-name simply sugar coats the usage of a property filter on the service lookup, which in most cases you don't want as it actually creates a tighter dependency between bundles. It is easier for instance to mock your dependency without such a tight coupling.

If, on the other hand, you want to get access to the service without using DM, then I would recommend that you use the straight up OSGi way using either direct access (via code) to the registry or inject it using DS (Declarative Services).

I would stay away from using regular Spring to directly access OSGi services. Use Spring to do configuration within your bundle only, and externalize the interbundle dependencies with Spring DM.

Or just use

Object obj = beanFactory.createBean(YourClass.class);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top