Is it possible to programmatically create an OSGI Service using Injections
Unfortunately I could not find a way to create the osgi service programmatically with links resolved. It is well known that OSGi creates a service as a singleton object. For some reason I need to create new instances of the service manually.
Happening:
@Service(ICasualService.class)
@Component(immediate = true, label = "Casual Service")
public class CasualService implements ICasualService {
@Reference
private ConfigurationAdmin configurationAdmin;
}
Using Bundle Context I can register my service:
private BundleContext bundleContext;
ICasualService casualService = new CasualService();
Dictionary props = new Properties();
bundleContext.registerService(ICasualService.class.getName(), casualService, props);
However, this way the configurationAdmin is null in the newly created service.
The question is, is it possible to programmatically create a new instance of the service?
Thank.
UPDATE: The solution should work for Felix (OSGi implementation).
source to share
You can use ComponentFactory to create component instances. See this article at Vogella .
Use this for the component you want to build 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();
source to share