Monday, February 4, 2008

Spring IOC in JRuby - life outside the container

If you're a JRuby aficionado you probably read about the Spring IOC Plugin for rails, but what if you want to get spring IOC running outside a servlet container? Here's how.

Now, the first important thing I learned is that spring uses the Java Thread's context class loader to load its resources. If you're using JRuby's $CLASSPATH to set up your test environment this poses a problem. So, first thing I override the current Thread's context class loader at the end of my test.rb environment file:

require 'java'
require 'jruby'

java.lang.Thread.current_thread.context_class_loader = JRuby.runtime.getJRubyClassLoader

Now we can move on to Spring. We can't use the WebApplicationContext that the Spring plugin uses because it'll (obviously) complain that there isn't a servlet context. So let's fall back on the ClassPathXmlApplicationContext. Add this wherever you'd like to hook in and replace the spring context from the plugin:

config = ["classpath:applicationContext.xml",
ctx =

And there you go! Provided you've configured the $CLASSPATH correctly you should be on your way.


MysteryCoder said...

Coolness, didn't know anyone was actually using it ;)

Mike Andrzejewski said...

Thanks a lot. It helped a lot...