4

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).

Alexander Drobyshevsky
  • 3,907
  • 2
  • 20
  • 17

1 Answers1

6

You can use a ComponentFactory to create instances of a component. See this article at Vogella.

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();
Christian Schneider
  • 19,420
  • 2
  • 39
  • 64
  • Thank you very much! It works. Moreover, 1. This way you can create new service with appropriate configuration parameters by passing them into this.factory.newInstance(Dictionary) method; 2. It creates new instances of service (in case .newInstance(null) it returns the same object each time). – Alexander Drobyshevsky May 15 '17 at 12:09