javaosgiaemapache-felix

Is it possible to create OSGI Service programmatically with Injections resolved


Unfortunately, I could not find a way to create an osgi service programmatically with resolved references. It is a well known fact, that OSGi creates service as a singleton object. Owing to some reason, I need to create new service instances manually.

The case:

@Service(ICasualService.class)
@Component(immediate = true, label = "Casual Service")
public class CasualService implements ICasualService {

    @Reference
    private ConfigurationAdmin configurationAdmin;
}

Using Bundle Context I am able to register my service:

private BundleContext bundleContext;
ICasualService casualService = new CasualService();  
Dictionary props = new Properties();
bundleContext.registerService(ICasualService.class.getName(), casualService, props);

However, this way configurationAdmin is null in a new created service.

The question is whether it possible to create a new instance of the service programmatically?

Thank you.

UPDATE: Solution should work for Felix (OSGi implementation).


Solution

  • You can use a ComponentFactory to create instances of a component. See this article at Vogella (and its 2024 update).

    Use this on the component you want to create programmatically:

    @Component(factory="fipro.oneshot.factory")
    

    Then in another component you can get the ComponentFactory:

    @Reference(target = "(component.factory=fipro.oneshot.factory)")
        private ComponentFactory factory;
    

    and create an instance from it:

    ComponentInstance instance = this.factory.newInstance(null);
    OneShot shooter = (OneShot) instance.getInstance();