0

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.

4

1 回答 1

1

MyExampleCommand我相信它不是一个可以注入服务的bean。但是,applicationContextGrailsApplicationCommand(extends ApplicationCommandtrait) 中可用,可以直接利用它来获取服务 bean。

class MyExampleCommand implements GrailsApplicationCommand {

    boolean handle() {
        TestService testService = applicationContext.getBean(TestService)
        testService.test()
        return true
    }
}
于 2017-07-26T20:09:46.013 回答