Search code examples
javadynamicosgideclarative-services

Dynamic target for declarative service in OSGI


Given a consumer which uses a service, how can this consumer select a specific provider dynamically using declarative service ?

Example

Service.java

public interface Service {
    public void do();
}

Provider1.java

public class Provider1 implements Service {    
    @Override
    public void do(){
        //a way 
    }   
}

Provider2.java

public class Provider2 implements Service {    
    @Override
    public void do(){
        //another way 
    }   
}

Consumer.java

public class Consumer {
    private Service myService;

    protected void bindService(Service s){ // Actually it's Provider1
        myService = s;
    }

    protected void unbindService(Service s){
        myService = null;
    }

    public void useThisKindOfService(String s){
        // Do something crazy
    }
}

So, what I would like it's instead of "Do something crazy", to find a way to reconfigure the consumer in order to release Provider1 and ask for Provider2.

Is it possible ?

Update related to "Duplicate Question"

OSGI/Felix Declarative services: How to filter the services to be bound

In my context I cannot use the declarative target because the value of the target has to be know at build time, in my case the target could be defined by a user at runtime.


Solution

  • Components of Declarative Services can be configured via ConfigurationAdmin. By doing that, the configuration of the component can be changed at runtime.

    You can also change the configuration of myService.target via ConfigurationAdmin at runtime. If you do that, another reference will be bound to your component.

    If the policy of the reference of your component is dynamic, the new reference will be bound without reactivating your component.

    For more information, see the Declarative Services chapter of the OSGi Compendium specification.