Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Injector registration

Injector listener

Sometimes it's necessary to use Slice bindings during the activation of the OSGi component. It can't be done in the @Activate method, as there is a race between component activation and the application activator that creates Slice injector - the result is that Slice injector isn't created yet, so OSGi component can't use it. The workaround is to use lazy loading and initialize data on the first request, but it may make the OSGi service design more complex.

The new InjectorListener interface allows to overcome this problem. It contains method injectorAvailable(String) that will be invoked for each injector that has been already created. Therefore, the initialization logic may be moved there:

Code Block
@Component
@Service
public class MyComponent implements InjectorListener {
	// we need to have this atomic boolean, as the injector may become available
	// a few times during component lifecycle
	private final AtomicBoolean initialized = new AtomicBoolean();

	@Activate
	protected void activate() {
		initialized.set(false);
	}

	@Override
	public void injectorAvailable(String injectorName) {
		if ("myapp".equals(injectorName) && !initialized.getAndSet()) {
			InjectorWithContext injector = InjectorUtil.getInjector("myapp", getResolver());
			// do something clever with the injector
		}
	}
}