我有一个关于服务领域是否由用户共享的问题?我的grails版本是2.3.4 现在我有一个带有两个动作的控制器,并尝试从服务字段设置并获取值。
//This is a controller
class TestController{
def testService
def setValue(){
testService.setValue("123")
}
def getValue(){}
println testService.getValue()
}
}
//This is a service
class TestService{
def var
def setValue(def value){
var = value
}
def getValue(){}
return var
}
}
换句话说,如果多个用户在控制器中使用操作getValue
,他们是否共享服务中的var
?
谢谢!
答案 0 :(得分:1)
是的,默认情况下,所有services都是单例,因此每个webapp只有一个服务实例,但内部函数不同步:
默认情况下,对服务方法的访问不同步,因此不会阻止并发 执行那些方法。事实上,因为服务是一个 单身并且可以同时使用,你应该非常小心 关于在服务中存储状态。或者采取简单(和更好)的道路 并且永远不会将状态存储在服务中。
您可以通过在特定服务中放置服务来更改此行为 范围。支持的范围是:
prototype - A new service is created every time it is injected into another class request - A new service will be created per request flash - A new service will be created for the current and next request only flow - In web flows the service will exist for the scope of the flow conversation - In web flows the service will exist for the scope of the conversation. ie a root flow and its sub flows session - A service is created for the scope of a user session singleton (default) - Only one instance of the service ever exists