Why you should avoid using autowiring for Grails Domain Classes?

09 May 2017

Tags: Grails, GORM

You should not inject services into a domain class. Why? Autowiring a service into a domain class can have a big performance impact. Imagine you query 1000 records from a database, and those records are mapped into a GORM entities. Injecting a service into each of those 1000 GORM entities will have a performance cost.

Thus, starting with Grails 3.2.8 auto wiring of GORM entities is disabled when you create an app from scratch.

You will find in grails-app/conf/application.yml the following setting:

        autowire: false

Let me illustrate this with an example.

The following code will not get the service greetingService injected into a domain class unless you enable auto wiring with grails.gorm.autowire = true

package demo

class Greeter {

    def greetingService

    String name

    String sayHello() {
package demo

class GreetingService {
    String sayHi() {

package demo

class HelloController {

    def index() {
        def person = new Greeter(name: 'Sergio')

        render person.sayHello()

Try to avoid the injection of services in domain classes. Grails has an excellent services layer. You should place your business logic there.

Published on 09 May 2017