如何向Grails2.4.x服务注入单例作用域依赖项?
我在Grails2.4.5服务中处理“依赖注入”的方式是通过如何向Grails2.4.x服务注入单例作用域依赖项?,grails,dependency-injection,Grails,Dependency Injection,我在Grails2.4.5服务中处理“依赖注入”的方式是通过@PostConstruct: class HappyService { final FizzClient fizzClient @PostConstruct void postConstruct() { FizzClient fizzClient = new FizzClientBuilder() .withAuth(/* auth stuff */)
@PostConstruct
:
class HappyService {
final FizzClient fizzClient
@PostConstruct
void postConstruct() {
FizzClient fizzClient = new FizzClientBuilder()
.withAuth(/* auth stuff */)
.withOptions(/* complicated options here */)
.build()
}
}
我把“依赖注入”放在引号里,因为这不是真正的依赖注入,它就像每个服务中发生的DI引导一样
我现在需要(真正地)使用同一bean/对象的同一实例注入多个服务:
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也一样
我想我们可以通过在resources.groovy中定义Springbean来做到这一点,默认情况下它将具有“singleton”作用域
看看这个例子
我在src/groovy中创建了一个名为UserBean的groovy类,我想在我的其他控制器和服务中用作springbean
class UserBean{
User user
def getUser(){
return user
}
def setUser(User passedUser){
user = passedUser
return user
}
}
在resources.groovy中定义这个bean,它将创建名为userBean的bean,默认情况下具有“singleton”作用域
beans = {
userBean(UserBean){
}
}
现在,您可以通过定义
def userBean
因此,您将在整个应用程序中获得相同的userBean对象实例,并且如果您通过调用userBean.set(user)在userBean下设置user对象,您也将获得类似的结果
我想这将是处理SpringBean的更有效和grails的方法。希望这能有所帮助。谢谢@Shashank-所以我不会再给你12个小时的奖金了,但这都是你的了!再次感谢!当然,我很高兴这有帮助。:-)哦,一个重要的问题@Shashank,
Utils
类在哪里?在src/groovy
下?在grails app/conf下?再次感谢!是的,应该放在src/groovy
hello smeeb中——我试着用一个例子来回答你的问题。希望有帮助同样遵循这一点,它将指导您了解“grails中的SpringBeans”。