How can I distinguish between published OSGI services implementing same interface by their properties?
In Blueprint you can specify the filter attribute on the reference or reference-list element. For example:
<reference id="sampleRef"
interface="org.sample.MyInterface"
filter="(port=5000)"/>
Luca's answer above is correct, however it assumes you are using the low level API for accessing services.
If you are using Declarative Services (which I would generally recommend) then the filter can be added to the target
attribute of the service reference. For example (using the bnd annotations for DS):
@Reference(target = "(port=8080)")
public void setHttpService(HttpService http) {
// ...
}
Assuming that you want to retrieve registered services based on certain values for properties, you need to use a filter (which is based on the LDAP syntax).
For example:
int myport = 5000;
String filter = "&(objectClass=" + MyInterface.class.getName()
+ ")(port=" + myport + ")";
ServiceReference[] serviceReferences = bundleContext.getServiceReferences(null,filter);
where you want to look for services both implementing MyInterface
and having a value of the port
property equal to myport
.
Here is the relevant javadoc for getting the references.
Remark 1:
The above example and javadoc refer to the Release 4.2. If you are not restricted to a J2SE 1.4 runtime, I suggest you to have a look at the Release 4.3 syntax, where you can use generics.
Remark 2: (courtesy of Ray)
You can also pre-check the correctness of your filter by instead creating a Filter object from a filterStr
string:
Filter filter = bundleContext.createFilter(filterStr);
which also allows you to match the filter with other criteria. You still pass filterStr
to get the references, since there is no overloading that accounts for a Filter
argument. Please be aware, however, that in this way you will check the correctness twice: both getServiceReferences
and createFilter
throw InvalidSyntaxException
on parsing the filter. Certainly not a show-stopper inefficiency, I guess, but it is worth mentioning.