Grails instantiates object and uses in Controllers

给你一囗甜甜゛ 提交于 2019-12-11 11:12:50

问题


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?


回答1:


You can define singleton beans in resources.groovy

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

then in your controllers

class ExampleController {
     def myBean
}

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



来源:https://stackoverflow.com/questions/6716551/grails-instantiates-object-and-uses-in-controllers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!