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

IMG_4618.JPG bridge _MG_8016 IMG_6147 Golden Gate flower DHH via IChat IMG_4552.JPG Band Photo Sjoerd met speer nearby hotel Picture 2 oldtimer Sjoerd op de Sallandse Heuvelrug (en de rug van papa) trap (II) Moscone Center - JavaOne nice place to park a bike IMG_4597 robin_met_zijn_hyundai_horloge_foon
View more photos >

Categories



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