What is the best way, to use a Grails 3 Service in the Groovy Source folder?

299 views Asked by At

As in the question stated, what is the best way to use a grails service in the groovy sources? I'm working currently with this code:

private RoleService roleService;

public RoleCommand() {
    this.roleService = (RoleService) Holders.getGrailsApplication().getMainContext().getBean("roleService");
}

Is there a better way to do this?

Edit / Solution: I solved it using Spring Dependency Injection (annotating the Class with @Component and register the package using the @ComponentScan Annotation in the Application.groovy file)

2

There are 2 answers

1
ionutab On

To be honest I would avoid doing this.

I've been working on a large Grails application with all kinds of services and command classes.

This was one of the mistakes I was thinking of making in the beginning, but the more I developed I realized there are no cases where you need to do this.

The role of a command object should be to wrap the parameters in the request for you to easily access and validate the command on the controller-side of the application.

If it's all good you should then call the service methods required for you to create the response to the request.

0
chriopp On

Your code could be more groovy:

import grails.util.Holders

class RoleCommand {

    // getter for the service
    def getRoleService() {
        Holders.grailsApplication.mainContext.getBean 'roleService' 
        // or Holders.applicationContext.getBean 'roleService'
    }

    def useTheService() {
       // use the getter method
       def something = roleService.doSomething()
    }

}