Grails/Spring service autowiring

While working on a Grails project, I came across 2 interesting things:

  1. autowiring for domain classes doesn’t work, even if you follow all the instructions on how to enable it (either globally, or in the domain class definition itself)
  2. autowiring on abstract service classes doesn’t work (so if you’re implementing a data service with some custom functionality, your services won’t get autowired)

I’ve been able to fix both of these issues using a very simple utility class:

import grails.util.Holders

/**
 * Since Grails doesn't seem capable of autowiring into abstract classes, this
 * causes a bit of an issue when creating data services which do more than
 * just get/save.
 * 
 * All those context beans are available, so we just need to fudge the idea of
 * autowiring, and this class helps by providing a quick reference to the
 * singe long line required to get those Spring beans.
 * 
 * This also helps with domain classes, which have autowiring disabled, and
 * despite all the documentation saying the contrary, into which you cannot
 * autowire.
 * 
 * That said, this might prove to be a faster solution for use within domain
 * classes anyway since we don't have to worry about autowiring happening on
 * every object instantiation, but rather we just have a reference to the
 * singular instance with in the main context.
 */
class Beans {
	
	static def get(String name) {
		Holders.grailsApplication.mainContext.getBean(name)
	}
	
	static def $static_propertyMissing(String name) {
		get(name)
	}
	
}

Now, instead of setting up a service like this:

def myService

You instead define a getter method like this:

def getMyService() {
    Beans.myService
}

You can then use “myService” as you would’ve expected to under normal autowiring circumstances.