Search code examples
dependency-injectionosgiipojo

How to get an iPojo factory based on the interface it provides


If I want to have a service injected in iPojo using method injection I need to do

@Bind
public void bindService(MyService implementation) {
}

Based on the type of the argument it knows which impl to inject just based on the interface. If there are two impls of the same interface it will choose based on some algorithm (service rank?)

Now, if I need multiple intances of the service that need to be created on demand based on an event, I understand I'm supposed to use org.apache.felix.ipojo.Factory and construct the instances through it. The problem I have is that I have not found a way to specify which factory to have injected using only the Interface of the instances of the factory

In other words

@Bind
public void bindService(org.apache.felix.ipojo.Factory myFactory) {
}

is ambiguous. The only way I have found to get the factory injected is using @Bind(filter="(factory.name=myServiceFactoryImpl)" but this couples the consumer to a concrete provider, which defeats the whole point of OSGi services. What I want to do is in plain english "bind me to a factory whose instances implement the interface MyService". If there are again many providers' factories of the same interface, it should use the same disambiguation mechanism as when injecting instances directly. Is this possible?


Solution

  • Just use a filter using the component.providedServiceSpecifications property listing the interface exposed by the created instances:

    @Requires(filter="(component.providedServiceSpecifications=org.acme.Foo)")
    Factory[] factories;