views:

492

answers:

3

Is it possible to use a Spring container for DI from inside Eclipse plugins?

I'm wondering because I know that Eclipse causes a lot of issues with class loading, looking up things within the plugin, etc.

The plugin is intended to be distributed as a JAR.

+1  A: 

Yes but you will need Spring DM http://www.springsource.org/osgi

ashitaka
A: 

The answer is yes. You can use Spring DM, but you don't have to. It is probably better with it.

I did it without Spring DM and the main concern is class loading issues (not sure if Spring DM solves them, but I guess it should). Assuming you bundle the Spring JAR in a separate plugin with dependencies, you will need to load the context with the class loader of the invoking plugin .

Example:

  • Plugin A - your functional plugin
  • Plugin B - The Spring lib plugin exporting the spring packages

Plugin A depends on B. When plugin A starts, it will load the application context, when invoking this load, you will need to do something like:

Thread.currentThread().setContextClassLoader(PluginAActivator.class.getClassLoader())

So that the loading of the classes will happen under your own class loader. Now you can use a ClassPathXmlApplicationContext to load configuration XMLs from your class path.

One small note: the default ClassPathXmlApplicationContext validates your XMLs upon loading. You may want to disable it or point your XMLs to a local schema (rather than the standard Spring schema on springframework.org), otherwise, you will connect to the internet to download the schema files upon loading and working offline will fail.

zvikico
There are numerous areas where using plain Spring inside OSGi will cause you pain. I highly recommend you move to Spring DM if you plan to continue using Spring with OSGi.
hbunny
You will not need to do manage the context class loader in code if you use Spring DM and you will no longer manually create application contexts either.
hbunny
Some time passed since I wrote this answer. Indeed, Spring OSGi (formerly called Spring DM) provides all you need in a neat package, including an application context that works with no messing around and the ability to expose OSGi services by defining them in your Spring XMLs. Give it a try.
zvikico
A: 

Hi zvikico, do you have a code example for your post? This would be great, since I´m hanging around with this for a while.

Cheers!

greg
Don't be lazy - the Spring site does a good job of documenting their libraries.
hbunny