Today I had a short look at referencing Spring beans from Grails. Since Grails is build on top of Spring this was actually 100% simpler then expected. Grails controllers and taglibs are autowired by name on startup.

Just for the fun I create a simple tag which depends on a Spring bean for converting textile markup into HTML:

The tagfile looks like this:

GROOVY:
  1. import com.plink.plextile.*;
  2.  
  3. class TextileTagLib {
  4.     TextParser textileParser
  5.  
  6.     def textile = { attrs ->
  7.         out << textileParser.parseTextile(attrs.text, true)
  8.     }
  9. }

The file (TexttileTagLig.groovy in my case) is placed in the taglib subfolder. Closures in classes placed here will be available as tags in the g namespace your gsp pages.

In the code above you can clearly see the power of grails, writing tags in this way is really easy and nice. The attrs attribute of the 'textile' closure contains all attributes passed to the tag, we will use the text attribute.

The interesting part is the 'textileParser' attribute. This will be automatically injected by Spring, so all we have to do is define it in the resources.xml file in the spring directory:

XML:
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.        xsi:schemaLocation="
  5. http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
  6.    
  7.     <bean id="textileParser" class="com.plink.plextile.TextParser"/>
  8. </beans>

And modify the 'show.gsp' template in the view directory to use the tag:

HTML:
  1. <g:textile text="${task.description}"/>

And this is the result:

Textile inputted in the textarea of the formRendered as HTML (notice the ordered list)


0 Responses to “Referencing spring beans from a Grails tag”

  1. No Comments

Leave a Reply





About

Welcome to the weblog of Peter Maas. Here you'll find various posts related to stuff I like (like my kids and espresso) and stuff I do (like developing software).

JavaOne 2008 Pictures


Greenland Hotel room Okke en Rudie Cable Car line Charles Nutter & Guillaume Laforge Community One Keynote Acme Anvile at CommunityOne Keynote Moscone Center - JavaOne Golden Gate Scribbled Sun Logo alcatraz Tim Bray introducing the (J)Ruby panel smashmouth Stage being build in the nearby park pub Joshua Bloch at JavaOne2008 Rudie Stretched Limo nearby hotel Java + You on a cab
View more photos >

Categories



Meld u aan voor PayPal en begin direct met het accepteren van creditcardbetalingen.