Search code examples
javaosgiapache-felix

OSGI: DS and component factories issues


What I need is to get new instance of service every time when some consumer needs this service + using CDI. I've read a lot of articles and I can't find the answer to 2 my questions.

  1. If we use factories, why in service consumer we call factory (http://www.rpgnextgen.com/wiki/doku.php?id=component_factory ) and after that we get reference to service. I mean

    // get factory
    ComponentFactory factory = (ComponentFactory) context.getService(serviceReferences[0]);
    // get instance
    ComponentInstance instance = factory.newInstance(null);
    

Is there no way to set factory with certain interface and in service consumer call service when osgi inside calls the factory?

  1. If in service consumer we call factory then why we mark service as component when de facto factory is component?

The problem is that without factory I do @Inject @OsgiService (javase) or@OSGiService (javaee) and I can use different filters and code is very clear. Using component factory I (as I understand) loose this ability.


Solution

  • ComponentFactory exists for consumers that want to use a factory, because they want to control the lifecycle of the individual components. For example, if they want to create an instance of the component for every web request.

    If you don't want to use ComponentFactory... then don't.