Tuesday, December 05, 2006

Inject Dependencies into Extensions via Spring

After a while using the Spring-OSGi bridge I tried to use more Spring features on the client side within my Eclipse-RCP- or Equinox-based apps. Especially the question how to inject dependencies into extensions like views or editors seemed quite interesting to me.

And it is pretty easy to realize this. The only thing you need to do is: Define the view or editor in your Spring application context as a normal Spring bean (including dependency injection, AOP or whatever) and write an extension factory for the extension. This extension factory implements IExecutableExtensionFactory and is called by the Extension Registry to create the extension for you. You just need to implement the create-Method by invoking the Spring app context getBean(..) to let Spring create the real view or editor object for you. Then you put this extension factory into the extension declaration within the plugin.xml file instead of the real view or editor. Thats basically it. Cool, isn't it?

After doing this you should take care that your extension factory implements IExecutableExtension and delegates that call to the real extension if your extension implements this interface for some reason (views do so to get some initialization data). And you should take care of the definition within the Spring app context and that the context creates a new object each time you call getBean(..).

No comments: