javaosgideclarative-services

Referencing a Configuration Admin factory-created OSGi service


I read this answer by Neil Bartlett that stated that DS is able to replace the old ManagedServiceFactory approach of instantiating services:

A component can be used as either a singleton (i.e. MS) or a factory (i.e. MSF) by adding "configurationPolicy: require". If you create a factory config with a Factory PID the same as the component.name, then you get a factory.

As far as I am aware, creating a new configuration with a factory PID makes the Configuration Admin create a new instance of this service; indeed, this is what happens.

Say I have a factory PID of test, and I then add a configuration for test-1 with felix-fileinstall. This service is then correctly instantiated and activated when I add the corresponding configuration.

If I do

@Reference(target="(service.pid=test-1)")
Test test;

this obviously never gets resolved, as the created configuration is required to have a generated GUID.

How is it possible to obtain a reference to this service? Would I need to add an additional property to each configuration instance to filter by?


Solution

  • Why do you need to get a reference to this specific service instance?

    Generally service consumers should avoid knowing too much about the implementation behind the service, and certainly the PID that caused a component to be instantiated should be considered an internal detail of the implementation.

    When obtaining a service, you care primarily about what the service does -- this is the service interface. Then you might additionally care about supplementary attributes of the service.

    For example, if my pipes have burst then I need a plumber so I look for a service of type Plumber. If it's 2AM and I live in London then I need a 24-hour plumber so I add a filter: (&(available=24hr)(location=London)). I might additionally refine the filter with (yelp_rating>=4.0). But I wouldn't care about the name of the plumber or what he ate for dinner.