Reputation: 737
I am creating some OSGi bundles. They register services and also get (and of course use) each other's services.
I decided to use ServiceTracker
instead of Declarative Services.
As I was searching for information about this I found two approach of tracking services.
The first one is creating an own tracker class for each service, which extends the ServiceTracker
class and overrides the methods that need to be overridden. Then in the activator class creating a new instance of this tracker class giving the bundle context to it and open it for tracking.
The other approach is creating a tracker class for each service, which implements the ServiceTrackerCustomizer
interface and overrides the methods that need to be overridden. Then in the activator class creating a new instance of the ServiceTracker
class giving to it the bundle context, the name of the service that needs to be tracked and a new instance of our customizer class. Then open it for tracking.
Are there any differences between the two approaches? I would say no. In the ServiceTracker javadoc I can see that the ServiceTracker
class also implements the ServiceTrackerCustomizer
interface.
Could you please tell me the pros and cons on both the approaches? Thanks in advance.
Upvotes: 0
Views: 464
Reputation: 23948
In over 12 years of developing with OSGi I don't think I have ever written a single ServiceTrackerCustomizer
. IMHO it's just more convenient to directly subclass ServiceTracker
and leave the customizer parameter null
.
One simple reason it's easier to subclass is that you don't need to provide an implementation of the modifiedService
method, which is rarely needed.
Functionally, however, the result will be the same so it's very much a personal preference.
Upvotes: 1
Reputation: 6046
Here are my reasons:
Sub-class ServiceTracker if
Implement the interface if:
Do not use ServiceTracker directly if
Upvotes: 1