I recently gave a presentation at COJUG on ten facilities in Spring that you may not know much about. I saved my favorite for the last. Dynamic Language integration. This facility has been around since Spring's 2.0 release, but has been mired in the relative obscurity of Chapter 24 of their docs.
While many IT managers might be hesitant to adopt a language like Groovy or Ruby for their production environment due to misconceptions about performance, security, or what have you. The management types should have very little concern with testing code making extensive use of dynamic languages. If Ruby or Groovy provides a lower barrier of entry for complex testing or mocking, why not make use of it?
Spring provides the typical DI goodness of abstracting away the underlying implementation and allowing the developer to switch from mock to production code without changing client code. In the case of Ruby backed implementations, JRuby provides the hooks to allow the .rb file to be recognized as an implementation of the Java interface.
Here's a simple interface implemented in Java with which I've created a Java and a JRuby implementation.
A JRuby based implementation of this only has a few tricks like including the library and calling a method to include the class
Finally, with the spring integration facilities, a few lines of xml locates the file and plumbs in the implementation. Client code accesses the Java interface, none the wiser to the Ruby implementation.
There are a couple of gotchas to keep in mind with JRuby/Groovy Spring integration:
- JRuby 1.1 is not supported until Spring Framework 3.0, use JRuby 1.0
- Model code after what I have above, not what is in the Spring reference docs. At last check the docs were somewhat confusing in the use of include versus include_class
- AOP can be used to wrap the dynamic beans just as if they were POJOs. The one big caveat here is to make sure they are implementing an interface. Class based proxies will not work
Spring's support for dynamic language beans is pretty powerful in it's simplicity. The uses of this technology are much farther reaching than just mock scenarios, though. JRuby or Groovy files can be polled and reloaded without compilation or server restarts. This can be immensely useful for dynamic portions of applications like lightweight rules, environment configuration, validation, or even web site navigation.
Hope this helps get you started with integrating dynamic languages into your Java code. Please leave a comment with your scenario if you are using or planning on using dynamic languages integrated with Spring.
Subscribe to:
Post Comments (Atom)
3 comments:
Is there an specific reason for having to wait until Spring 3.0 to get JRuby 1.1 support?
Not sure of the reason they are waiting until a major release. JRuby 1.1 refactored some method names after Spring 2.5 was released though so that's why it doesn't work.
Thank you!
Post a Comment