Prioritizing OSGi service selection within a container when more than one implementation exist

送分小仙女□ 提交于 2019-12-03 10:18:19

The best way of prioritizing OSGi services to use SERVICE_RANKING service property. This property may be supplied in the properties object passed to the BundleContext.registerService() method.

According to the documentation of the BundleContext.getServiceReference() method:

If multiple such services exist, the service with the highest ranking (as specified in its Constants.SERVICE_RANKING property) is returned.

If there is a tie in ranking, the service with the lowest service ID (as specified in its Constants.SERVICE_ID property); that is, the service that was registered first is returned.

If the service is registered by a third-party library you may not have control over it's ranking or registered properties. Using ServiceTracker gives you more control. For example, you can do something like this :

ServiceTracker tracker = new ServiceTracker (bundleContext, serviceClass ,new ServiceTrackerCustomizer () {

            @Override
            public Object addingService(ServiceReference srvRef) {

                boolean criteria =  // whatever your criteria is for prioritizing
                        if(criteria)
                            return bundleContext.getService(srvRef);
                        else
                            return null;
            }

            @Override
            public void modifiedService(ServiceReference srvRef, Object arg1) {


            }

            @Override
            public void removedService(ServiceReference srvRef, Object arg1) {

            }

        });
tracker.open();
Object service = tracker.getService();

In org.osgi.framework.BundleContext.registerService(String[], Object, Dictionary) you can specify arbitrary properties in the Dictionary. To find a service, you can specify a filter in org.osgi.framework.BundleContext.getServiceReferences(String, String). And if that's not enough, you can check org.osgi.framework.ServiceReference.getProperty(String), for example for a priority value.

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