如何访问 Grails 2.0 中的 Grails 配置? [英] How to access Grails configuration in Grails 2.0?
问题描述
我已经获得了最新的 Grails 2.0 里程碑,我看到了 ConfigurationHolder
类的弃用警告:
I have obtained the latest Grails 2.0 milestone, and I am seeing a deprecation warning for the ConfigurationHolder
class:
org.codehaus.groovy.grails.commons.ConfigurationHolder
弃用消息只是说改用依赖注入",这对我来说不是很有帮助.我了解依赖注入,但是如何将 bean 与正确的 Grails 配置连接起来,以便我可以在运行时访问它?我需要从控制器和标签以外的地方访问配置(例如 BootStrap
).
The deprecation message simply says "Use dependency injection instead" which is not very helpful to me. I understand dependency injection, but how can I wire up a bean with the proper Grails configuration so I can access it at runtime? I need to access the configuration from places other than my Controllers and Tags (such as BootStrap
).
推荐答案
如果你在支持依赖注入的工件中需要它,只需注入
grailsApplication
class MyController { def grailsApplication def myAction = { def bar = grailsApplication.config.my.property } }
如果您需要在 bean 中使用它,例如
src/groovy
或src/java
,请使用conf/spring/连接它资源.groovy
// src/groovy/com/example/MyBean.groovy class MyBean { def grailsApplication def foo() { def bar = grailsApplication.config.my.property } } // resources.groovy beans = { myBean(com.example.MyBean) { grailsApplication = ref('grailsApplication') // or use 'autowire' } }
在其他任何地方,将配置对象传递给需要它的类或传递所需的特定属性可能是最简单的.
Anywhere else, it's probably easiest to either pass the configuration object to the class that needs it, or pass the specific properties that are needed.
// src/groovy/com/example/NotABean.groovy class NotABean { def foo(def bar) { ... } } // called from a DI-supporting artifact class MyController { def grailsApplication def myAction = { def f = new NotABean() f.foo(grailsApplication.config.my.property) } }
更新:
Burt Beckwith 最近写了几篇关于此的博文.有人讨论在域类中使用 getDomainClass()
,而其他提供创建您自己的持有人类的选项(如果上述解决方案都不合适).
Burt Beckwith recently wrote a couple of blog posts on this. One discusses using getDomainClass()
from within domain classes, while the other offers the option of creating your own holder class (if none of the solutions above are appropriate).
这篇关于如何访问 Grails 2.0 中的 Grails 配置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!