Search OSGI services by properties

倾然丶 夕夏残阳落幕 提交于 2019-11-30 14:42:13

问题


How can I distinguish between published OSGI services implementing same interface by their properties?


回答1:


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.




回答2:


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) {
    // ...
}



回答3:


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)"/>


来源:https://stackoverflow.com/questions/11151376/search-osgi-services-by-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!