Saturday, September 27, 2008

Run Groovy with Spring 2.5

Recently, I integrated Spring 2.5.6 with Groovy 1.5.6. For anyone trying to do this, let me say it is possible and not too difficult. Just remember Groovy is an extension of Java!

Here's an outline of the steps ..

1.) Create your application context for your Groovy classes. The application context is no different than the application context format as described here for Java applications.

You will need to setup your Spring beans and the overall "plumbing" for your application. The beans you create will connect your Groovy code to those components/services/etc in your application.

Also, include the base-package of your Groovy classes for the component scan. There is nothing different about specifying the local Groovy packages for the component scan vs. what is typically done in Java/Spring.

Here's an example...

This snippet builds the classpath from
com.pacent.core.invoice.util.console
through the component-scan. If you are building your classpath through other means, just reuse your groovy package/classes to build that classpath.

2.) In your Groovy class load your application context from #1. Use the org.springframework.context.support.ClassPathXmlApplicationContext class to read your app context file.

ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext("classpath:your-appContext.xml")

3.) In your Groovy class grab the bean(s) that you need using the following code...

def yourService = appContext.getBean("yourBeanDefinedInAppContext")

4.) Code away! Use your local instance of "yourService" to get your Spring provided information to build out your logic.

That's it! I leave the practice of using annotations or other permutations of Spring up to you.

Please note, the most difficult part of Groovy/Spring may be finding an IDE that plays well with Groovy. I have used Eclipse and NetBeans. So far, NetBeans 6.5+ seems to have the best working environment for Groovy. A friend swears by IntelliJ for Groovy, but I haven't spent enough time with IntelliJ to comment. Eclipse with Groovy is OK, but a bit rough around the edges with the Groovy plugin (GroovyFeature).

Also, if you need information on how to build your Spring/Groovy classes try here.

Good luck!

3 comments:

Unknown said...

Check out the Groovy BeanBuilder, makes actually creating the Spring appContext so much easier and cooler.
http://grails.org/Spring+Bean+Builder

Anonymous said...

will you pay for Spring?

Rob Castellow said...

The Spring framework is free and open source, and can be found here... http://www.springframework.org/