【问题标题】:How do I inject services into a Grails 3 command?如何将服务注入 Grails 3 命令?
【发布时间】:2017-07-26 18:47:59
【问题描述】:

在 Grails 3 应用程序中,如何创建利用应用程序的 Service 和 Domain 类的 CLI 命令?

以下不起作用

  1. grails create-app test-grails3-angular-cmd --profile=angular
  2. cd server
  3. grails create-command MyExample
  4. 实现 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. 实现测试服务:

    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

命令执行错误:无法在空对象上调用方法 test()

我该如何解决这个问题?

我正在使用 grails 3.3.0.M2。

【问题讨论】:

  • 我没有地方可以测试这个,所以只是把它作为评论,这样你就可以快速测试它(而不是答案)。这对你有用吗? Holders.applicationContext.testService.whateverMethod()
  • 这和angularjs有什么关系?

标签: angularjs grails grails-plugin grails-services grails-3.3


【解决方案1】:

MyExampleCommand 不是 bean,我相信,可以注入服务。但是,applicationContext 可用于 GrailsApplicationCommand(扩展 ApplicationCommand 特征),可直接用于获取服务 bean。

class MyExampleCommand implements GrailsApplicationCommand {

    boolean handle() {
        TestService testService = applicationContext.getBean(TestService)
        testService.test()
        return true
    }
}

【讨论】:

    猜你喜欢
    • 2016-01-30
    • 1970-01-01
    • 2016-02-08
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    • 1970-01-01
    • 1970-01-01
    • 2017-03-01
    相关资源
    最近更新 更多