javaosgiapache-felixwhiteboard

Is there a simpler method for handling MULTIPLE references in OSGi?


Suppose I have a class like this:

@References(
        value={
                @Reference(name="dataSources",cardinality=ReferenceCardinality.OPTIONAL_MULTIPLE,policy=ReferencePolicy.DYNAMIC,strategy=ReferenceStrategy.EVENT,bind="bind",unbind="unbind",referenceInterface=DataSourceProvider.class)
        })      
public class DataSourceStoreServiceImpl implements DataSourceStoreService {

    List<DataSourceProvider> dataSourceProviders = new CopyOnWriteArrayList<DataSourceProvider>();

    public void bind(DataSourceProvider dataSourceProvider) {
        dataSourceProviders.add(dataSourceProvider);
    }

    public void unbind(DataSourceProvider dataSourceProvider) {
        dataSourceProviders.remove(dataSourceProvider);
    }

}

This is how I handle refereces with MULTIPLE cardinality.

My question is whether it is possible to do it without the boilerplate? What I have in mind is something like this:

public class DataSourceStoreServiceImpl implements DataSourceStoreService {

    @CollectionType(CopyOnWriteArrayList.class)
    @Reference(name="dataSources",cardinality=ReferenceCardinality.OPTIONAL_MULTIPLE,policy=ReferencePolicy.DYNAMIC,strategy=ReferenceStrategy.EVENT,bind="bind",unbind="unbind",referenceInterface=DataSourceProvider.class)
    List<DataSourceProvider> dataSourceProviders

}

Solution

  • Using IPojo annotations.

    Simply declaring an array with the annotation "requires" as in this example:

    @Requires
    private Hello[] m_hello; // Service Dependency
    

    Then you can call your services like that:

    for(Hello helloService: m_hello){
           helloService.ohHai("Test");
    }
    

    Oh I forgot, your provider class needs 2 annotations: @Component and @Provides and your consumer class needs @Component and @Instantiate