Reputation: 203
i am getting in touch with OSGi and right now i am a little confused. I am using a hybrid service model meaning a mixture of declarative services and low level api.
Consider the following part declaration placed under OSGi-INF/component.xml:
<property name="canHandle" type="String" value="Some kind of stuff"/>
<service>
<provide interface="foo"/>
</service>
and another one
<property name="canHandle" type="String" value="Some other Stuff"/>
<service>
<provide interface="foo"/>
</service>
In another bundle i have something like this:
bar.createSomething(String type){
ServiceReference[] services FrameworkUtil.getBundle(getClass()).getBundleContext()
.getAllServiceReferences("foo");
for (ServiceReference s : services) {
if (type.equals(s.getProperty("canHandle")){
Foo foo = (Foo)FrameworkUtilgetBundle(getClass()).getBundleContext().getService(s);
foo.execute();
To make a long story short, i a have a service interface with multiple implementations and at runtime i am using the one which matches a string against the properties. So how can i am dealing with this situation ONLY using declarative services?
We are using Virgo so if it is possible with spring, this would be an option too.
Upvotes: 1
Views: 443
Reputation: 23948
You can do this with a target filter on the <reference>
element. Or, using the bnd annotations:
@Reference(target = "(canHandle=blah)")
public void setFoo(Foo foo) {
// ...
}
Now even if there are multiple Foo
service instances available, only the ones matching the filter (canHandle=blah)
will be injected into your component.
Update
It was clarified that the value to be matched is not known statically. In that case the static filter cannot be used. But you can still use declarative services and check the value of the service property manually, for example:
@Reference(multiple = true, dynamic = true)
public void setFoo(Foo foo, Map<String,Object> serviceProps) {
if ("value".equals(serviceProps.get("canHandle"))) {
// ...
}
}
Bear in mind that you might now get multiple matching instances.
Upvotes: 4