如何在Grails应用程序中选择服务实现?

时间:2012-05-21 07:52:56

标签: spring grails groovy

我有几个服务实现了一个通用接口,我希望能够在我的应用程序启动时选择其中一个注入其他服务。

我已尝试从resources.groovy引用服务实现,如下所示,但是Spring会生成所选服务的新实例,并且不会自动装配其依赖项。

如何让这个解决方案起作用?或者还有另一种方式吗?

class MyService {

    Repository repository

    interface Repository {
        void save(...)
    }
}

class MySqlRepositoryService implements MyService.Repository { ... }

class FileRepositoryService implements MyService.Repository { ... }

resources.groovy:

beans = {
    ...
    repository(FileRepositoryService) { }
}

1 个答案:

答案 0 :(得分:3)

当然可以从手工制作的工厂中检索服务参考,但在我看来,你采取的方法是最好的。我自己使用它,因为它在一个地方收集有关应用程序配置阶段的所有信息,因此更容易找到使用的实现。

您遇到的自动装配陷阱可以很容易地解释。放入grails-app/services的所有类都由Grails自动配置为Spring单例bean,并按名称自动装配。因此,您放在grails-app/conf/resources.groovy中的bean定义会创建另一个bean,但没有Grails约定强加的默认值。

最直接的解决方案是将实现放在src/groovy中以避免重复bean并使用以下语法打开自动装配:

beans = {
  repository(FileRepositoryService) { bean ->
    bean.autowire = 'byName'
  }
}
相关问题