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:
grails create-app test-grails3-angular-cmd --profile=angular
cd server
grails create-command MyExample
Implement MyExample:
package test.grails3.angular.cmd
import grails.dev.commands.*
class MyExampleCommand implements GrailsApplicationCommand {
def testService
boolean handle() {
testService.test()
return true
}
}
grails create-service TestService
Implement TestService:
package test.grails3.angular.cmd
import grails.transaction.Transactional
@Transactional
class TestService {
def test() {
System.out.println("Hello, test service!")
}
}
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.
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
}
}