0

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)

  • and the reason would be? (because I see no apparent reason for doing this) – injecteer Sep 24 '18 at 10:10
  • To use data from the database in the sources –  Sep 30 '18 at 14:33
  • That sound like you want to use GORM in stand-alone mode – injecteer Oct 01 '18 at 16:49
  • Yes and no. I have to use the data in the given (Java) sources and in the web-app too. In the sources is a bot for an instant-messenger running. The bot is consuming and posting data via the grails services into GORM. Is this a bad practice? –  Oct 01 '18 at 21:53
  • If I were you, I'd create a (micro-)serice for the bot, which should have not much to do with the main app. In that service I'd use GORM stand-alone – injecteer Oct 02 '18 at 08:02

2 Answers2

1

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()
    }

}
chriopp
  • 947
  • 7
  • 12
0

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.

ionutab
  • 445
  • 4
  • 21
  • 1
    The name "Command" is in my context misleading. I use the name for the class, because it's for a command, which can be triggered by a bot. It's actually not the command pattern. –  Sep 20 '18 at 18:30