I am working on the OSGi Service right now, and I have a question about using Services in OSGi. There are some different way to register user service. Can anybody explain the difference between OSGi Service tracker and Declarative Services? Which one is better?
In OSGi, the ServiceTracker is a programmatic way to acquire a reference to a service. i.e. You write ServiceTracker code that "tracks" a reference to another service and let's you use it when it becomes available.
In contrast, Declarative Services (DS), allows you to declare dependencies that are injected into your component. DS is, as such, a form of dependency injection. The dependency graph between services, together with their start order will determine when your service starts. The cardinality property in a DS definition allows you to declare whether the relationship is mandatory (1..1), multiple with a least one (1..n), optional (0..1) or multiple optional (0..n). When you declare mandatory relationships, your service will not start until all dependencies are satisfied. When you declare an optional relationship your service will start regardless of the state of the dependency, but you need to take care in the code that the reference to your service might be null.
From a practical perspective, ServiceTracker is a lot of boilerplate code to write and maintain. Given the dynamic nature of OSGi services, there're many states allowed by the OSGi spec that need to be taken into consideration. DS will give you a clean way to declare and maintain your dependencies. Well-defined dependencies will help you maintaining consistency of your runtime environment.