Tropical Software Observations

30 January 2009

Posted by Teo Choong Ping

at 3:41 PM


Labels: ,

Injecting Grails Service class via Spring

A quick note on how to inject Service objects -- or for that matter any object -- via Spring.

Grails has always been able to support the injection of objects via Spring whether using XML or Spring DSL. A good scenario of using Spring DSL is to swap implementations easily.

In our project, Party Time, we use a lot of services. Most of these services implement Java interfaces and may be changed in the future. To be flexible in the changing of these service implementation, we auto-wire the services via Spring DSL.

For example, we have a Service class, LocalCDNService that implements the ICDNProvider interface. We configure the implementation by specifying in grails-app/conf/spring/resources.groovy:

beans = {

And from then onwards we can refer to the service object within our Grails controllers, taglibs, or services by simply declaring:

class ExampleController {
def cdnProvider

Contrast this to the common way of autowiring services by declaring:

class ExampleController {
def localCdnService

If we were to change CDN provider from LocalCDNService to AWSCDNService, we would probably need to change many classes. However if you were to use the Spring DSL way, you just need to change grails-app/conf/spring/resources.groovy:

beans = {

Hopefully this will shed more light to those new to using Spring within Grails.


Wayne said...

Nicely explained. Now, how do you inject configuration information into the implementation? For example, setting a username and password on your AWSCDNService, which might be different from your localCdnService?