angularjsgrailsgrails-plugingrails-servicesgrails-3.3

How do I inject services into a Grails 3 command?


In a Grails 3 app, how do I create a CLI command that leverages the app's Service and Domain classes?

The following did not work:

  1. grails create-app test-grails3-angular-cmd --profile=angular
  2. cd server
  3. grails create-command MyExample
  4. Implement MyExample:

    package test.grails3.angular.cmd
    
    import grails.dev.commands.*
    
    class MyExampleCommand implements GrailsApplicationCommand {
        def testService
    
        boolean handle() {
            testService.test()
            return true
        }
    }
    
  5. grails create-service TestService

  6. Implement TestService:

    package test.grails3.angular.cmd
    
    import grails.transaction.Transactional
    
    @Transactional
    class TestService {
    
        def test() {
            System.out.println("Hello, test service!")
        }
    }
    
    1. grails run-command my-example

Command execution error: Cannot invoke method test() on null object

How can I fix this?

I am using grails 3.3.0.M2.


Solution

  • MyExampleCommand is not a bean, I believe, where service can be injected. However, applicationContext is available in GrailsApplicationCommand (extends ApplicationCommand trait) which can be leveraged directly to get the service bean.

    class MyExampleCommand implements GrailsApplicationCommand {
    
        boolean handle() {
            TestService testService = applicationContext.getBean(TestService)
            testService.test()
            return true
        }
    }