Thursday 10 December 2009

Make your Spring project Groovy


I know there's already an example in the Spring documentation (http://static.springsource.org/spring/docs/2.0.8/reference/dynamic-language.html) of using dynamic languages and having the Spring container instantiate, configure and dependency inject the resulting objects but after trying the example using Maven and STS there's a couple of extra points worth writing down.

So, the first thing I did was to create a new Maven project just using the quickstart archetype. At this point I added the Groovy nature to the newly created project (right click > Groovy > Add Grovy Nature) and added Groovy as a dependency in the POM


<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy</artifactId>
<version>${groovy.version}</version>
</dependency>


Next I created the Java interface, Groovy script that implements it and a Spring application context to configure my bean. Now at this point you have 2 options:

Option 1
Add the GMaven plugin to your POM to compile your Groovy scripts and configure them as just plain beans in the Spring context

<plugin>
<groupId>org.codehaus.groovy.maven</groupId>
<artifactId>gmaven-plugin</artifactId>
<version>1.0-rc-5</version>
<executions>
<execution>
<goals>
<goal>generateStubs</goal>
<goal>compile</goal>
<goal>generateTestStubs</goal>
<goal>testCompile</goal>
</goals>
<configuration>
<sources>
<fileset>
<directory>${project.build.sourceDirectory}</directory>
<includes>
<include>**/*.groovy</include>
</includes>
<directory>${project.build.testDirectory}</directory>
<includes>
<include>**/*.groovy</include>
</includes>
</fileset>
</sources>
</configuration>
</execution>
</executions>
</plugin>


<bean id="messenger" class="org.rhart.GroovyMessenger">
<property name="message" value="Groovy In Spring Works!" />
</bean>


Option 2
Include *.groovy files as resources to be exported as part of the build and use the lang namespace within the Spring context

<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
<include>**/*.xsl</include>
<include>**/*.groovy</include>
</includes>
</resource>
</resources>


<lang:groovy id="messenger" script-source="classpath:org/rhar/GroovyMessenger.groovy">
<lang:property name="message" value="Groovy In Spring Works!"></lang:property>
</lang:groovy>


You can find the complete Maven based eclipse project here

No comments:

Post a Comment

Search This Blog