22 May 2008

Grails is only Java EE with Spring

Grails is defintivly a cool framework for developing nice Java EE web apps. you can do a lot of tasks with just one step and the rest ist automatically done by Grails.
But using your existing Java code in a Grails application is no problem. Grails is based on Spring and Groovy and thus there are some easy ways to embbed Java code to your app.
  1. You can create a normal Grails controller or service and import your Java classes the normal way. This works pretty easy, if you're developing your app mainly with Groovy.
  2. If your app is allready based on Spring and thus provides allready Spring services, you can embbed'em directly and reference them in your Grails controller or services.
The second way can easyly be done, using some XML for configuration, but there is also the Groovy way to do, by using Grails' Spring Bean Builder.
To use it, you can put some Groovy code to the PROJECT_HOME/grails-app/conf/spring/resources.groovy file.
The following code shows you an example resources.groovy file:
import com.duckmaps.server.imagerendering.services.ImageServiceImpl

beans = {

imageService(ImageServiceImpl) {bean ->
bean.scope = "session"
}

}
Here you're seeing, that a bean with name imageService and the class ImageServiceImpl is defined. By setting the property scope to session, Spring instantiates this class for each session. It is important to put the import statement to the top. If you forget it, your code won't work.
Referencing this bean is the same as XML declared beans. Just put a
def imageService
to your controller and Grails will inject it like a normal Grails controller.

No comments: