Grails实例化对象并在控制器中使用 [英] Grails instantiates object and uses in Controllers

查看:126
本文介绍了Grails实例化对象并在控制器中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,它只需要实例化一个对象,我正在考虑Singleton,但在我进入之前,我正在考虑依赖注入。我想要做的是在 Bootstrap中实例化对象和 setAttribute ServletContext .groove 并在每个控制器中使用该对象。我的理解是,在应用程序生命周期中bootstrap只会被调用一次?我可以这样做吗?

I have an application where it needs to instantiate only one object, I was thinking of Singleton, but before I jump in to that, I was thinking of dependency injection. What I would like to do is, to instantiate the object and setAttribute to ServletContext in Bootstrap.groove and use the object in every controller. My understanding would be that bootstrap will be called just once during the application lifetime? Could I do that?

推荐答案

您可以在resources.groovy中定义单例bean

You can define singleton beans in resources.groovy

beans = {
    myBean(my.company.MyBeanImpl) {
        singleton true
    }
}

然后在您的控制器中

class ExampleController {
     def myBean
}

a href =http://www.grails.org/doc/latest/guide/14.%20Grails%20and%20Spring.html =nofollow> http://www.grails.org/doc/latest /guide/14.%20Grails%20and%20Spring.html

All documented here: http://www.grails.org/doc/latest/guide/14.%20Grails%20and%20Spring.html

这篇关于Grails实例化对象并在控制器中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆