During the christmas break, I took an hour or so to play with Groovy and EJBs. EJB 3 are very easy to use (especially compared to what they used to be before that) so I decided to investigate how I could make them even simpler to use with Groovy.
Indeed, Groovy shares mostly the same meta-model as Java and you can easily mix Java and Groovy code in the same project (actually you can put .java and .groovy files side-by-side in your packages).
I opted for a simple hello-word style of project using Groovy 1.5 and GlassFish v2 ur1.
I started with a single HelloEJB.groovy file to host both the EJB remote interface and implementation as a stateless session bean:
package ejb import javax.ejb.Remote import javax.ejb.Stateless @Remote interface HelloRemote { String hello() } @Stateless class HelloEJB implements HelloRemote { String hello() { return "Hello world!" } }
The Groovy compiler takes care of generating 2 .class files (one for the interface and one for the class). Nice
Then I packaged this inside an EAR having groovy-all-1.5.jar so that GlassFish could make the Groovy runtime available to the EJB. Then I wrote this simple remote client to test it:
import javax.naming.InitialContext def ctx = new InitialContext() def ejb = ctx.lookup("ejb.HelloRemote") println ejb.hello()
For this client to work, you need to put appserv-rt.jar from GlassFish in your classpath. Also, you will need to tweak a jndi.properties file at the root of your client classpath if you are not using the default GlassFish ports for your target domain.
I guess I can now save quite a lot of time using Groovy to implement EJBs
Disclaimer: I am dynamic-languages agnostic as I use Python, Ruby and Groovy for various things and I like them all. Really!
Bonus: 