dub*_*ech 3 grails dependency-injection
是否有可能让两个服务实现相同的接口并在运行时决定为Grails中的接口注入哪些服务?
例如
MyAService implements MyInterface {
...
}
MyBService implements MyInterface {
...
}
Run Code Online (Sandbox Code Playgroud)
其他服务然后只是引用MyInterface,你决定基于配置设置或注入什么服务?
Grails使用自动注入按名称进行基于约定的注入def fooService,并且像服务这样的工件在启动时自动注册.如果配置bean及其依赖项resources.groovy,则可以获得更多控制权,并且可以使用Groovy代码应用逻辑.
但我会保持简单并完成工作BootStrap.groovy.添加一个公共字段(例如def myService)或私有字段和一个setter(例如void setMyService(service) { this.myService = service }在目标类中.然后在BootStrap中,依赖注入所有可能的候选者并手动注入正确的候选者.类似于
class BootStrap {
def myAService
def myBService
def theDestinationBean
def init = { servletContext ->
if (<some condition>) {
theDestinationBean.myService = myAService
}
else {
theDestinationBean.myService = myBService
}
}
}
Run Code Online (Sandbox Code Playgroud)
因为它是Groovy,你可能不需要接口,但它没有受到伤害,并且可以给你一点编译时的安全性.