gpt4 book ai didi

grails - 如何注入(inject)具有单例范围依赖关系的 Grails 2.4.x 服务?

转载 作者:行者123 更新时间:2023-12-02 14:06:48 26 4
gpt4 key购买 nike

我在 Grails 2.4.5 服务中处理“依赖注入(inject)”的方式是通过 @PostConstruct :

class HappyService {
final FizzClient fizzClient

@PostConstruct
void postConstruct() {
FizzClient fizzClient = new FizzClientBuilder()
.withAuth(/* auth stuff */)
.withOptions(/* complicated options here */)
.build()
}
}

我将“依赖注入(inject)”放在引号中,因为这不是真正的依赖注入(inject),它就像每个服务内部发生的 DI Bootstrap ,嗯。

我现在需要(真正)向同一个 bean/对象的同一个实例注入(inject)多个服务:
class HappyService {
final FizzClient fizzClient
final BuzzClient buzzClient // Needs to be the same bean/instance
// as injected into GrumpyService below

@PostConstruct
void postConstruct() {
FizzClient fizzClient = new FizzClientBuilder()
.withAuth(/* auth stuff */)
.withOptions(/* complicated options here */)
.build()
}
}

class GrumpyService {
final BuzzClient buzzClient // Needs to be the same bean/instance
// as injected into HappyService above
}

我该怎么做呢?

最佳答案

首先,您可以像这样编写一个简单的 Groovy 类(在 src/groovy 内):

import grails.util.Holders

class Utils {

private static FizzClient fizzClient
private static BuzzClient buzzClient

static void init() {
if (fizzClient && buzzClient) {
return
}

def grailsApplication = Holders.getGrailsApplication()

fizzClient = new FizzClientBuilder()
.withAuth(/* auth stuff */)
.withOptions(/* complicated options here */)
.build()

buzzClient = fizzClient.getBuzzClient() // Do whatever you want to get both the fields initialized
}

static FizzClient getFizzClient() {
init() // Make sure to get them initialized in case service injection happens first
return fizzClient
}

static BuzzClient getBuzzClient() {
init()
return buzzClient
}
}

现在,在您的 Bootstrap.groovy :
class BootStrap {

def init = { servletContext ->
Utils.init()
// your stuff
}
}

现在,终于在您的服务中:
class HappyService {
FizzClient fizzClient
BuzzClient buzzClient

@PostConstruct
void postConstruct() {
fizzClient = Utils.getFizzClient()
buzzClient = Utils.getBuzzClient()
}
}

您的 GrumpyService 也是如此.

关于grails - 如何注入(inject)具有单例范围依赖关系的 Grails 2.4.x 服务?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33309978/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com