Channa
Channa

Reputation: 3737

How to bind dynamic reference based on configuration?

I have following consumer component that uses a reference service called sender,

    @Component(configurationPolicy = ConfigurationPolicy.REQUIRE, configurationPid = DATA_SYNC_CONFIG)
    public class DataSynchronizer {

        @Reference
        private TelemetrySender sender;

        //calls some methods of sender
}

And this works fine as long as there is one implementation for interface TelementrySender

But if there are two implementations for that interface, and if I want to select which implementation to bind based on configuration property , what is the correct way to do it? According to my understanding and findings following method is tried.

included a bind method to my component as follows.

   @Component(configurationPolicy = ConfigurationPolicy.REQUIRE, configurationPid = DATA_SYNC_CONFIG)
    public class DataSynchronizer {

        private TelemetrySender sender;

       @Reference
        void setSender(TelemetrySender telemetrySender ) {
            // read configuration and set only correct implementation 
           this.sender= telemetrySender ;
         }

        //calls some methods of sender
}

one of my TelemetrySender implementation is as follows,

@Component(configurationPolicy = ConfigurationPolicy.REQUIRE, configurationPid = HTTP_TELEMETRY_SENDER_CONFIG,property={ "service=http" })
 public class HttpConnector implements TelemetrySender {
}

My problem is how to select correct TelemntrySender inside setSender method? Or if I'm using wrong approach please correct me. I referred this article

Upvotes: 2

Views: 256

Answers (1)

Christian Schneider
Christian Schneider

Reputation: 19606

The simplest way is to use an attribute in the config sender.target=<search filter>. See OSGi compendium 112.6.2.1.

So if the service you want to bind has the property sendername=my then you could set:

sender.target=(sendername=my)

Upvotes: 2

Related Questions