如何访问 Grails 2.0 中的 Grails 配置?
我已经获得了最新的 Grails 2.0 里程碑,并且看到了 ConfigurationHolder
类的弃用警告:
org.codehaus.groovy.grails.commons.ConfigurationHolder
弃用消息只是说“改为使用依赖项注入”,这对我来说不是很有帮助。我了解依赖注入,但是如何使用正确的 Grails 配置连接 bean,以便可以在运行时访问它?我需要从控制器和标签以外的地方访问配置(例如 BootStrap
)。
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
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
).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
如果您在支持依赖项注入的工件中需要它,只需注入
grailsApplication
如果您在
src/groovy 中的 bean 中需要它
或src/java
,使用conf/spring/resources.groovy
连接它
在其他地方,将配置对象传递给需要它的类,或者传递所需的特定属性可能是最简单的。
更新:
Burt Beckwith 最近就此写了几篇博客文章。 有人讨论在域类中使用
getDomainClass()
,而其他提供了创建您自己的持有者类的选项(如果上述解决方案都不合适) 。If you need it in an artifact that supports dependency injection, simply inject
grailsApplication
If you need it in a bean in, say,
src/groovy
orsrc/java
, wire it up usingconf/spring/resources.groovy
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.
Update:
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).grailsApplication 的替代方案是 Holders 类,
您可以直接获取配置脱离 Holders,无需注入,这对于实用程序类等非常有用。
An alternative to grailsApplication is the Holders class,
You get config directly off of Holders, no injection needed, which is nice for utility classes, etc.
您可以将“grailsApplication”注入源文件中。这是一个示例conf/Bootstrap.groovy
you can inject "grailsApplication" into your source file. here is a sample conf/Bootstrap.groovy
另一种未弃用的获取配置的方法是:
这适用于没有可用的注入父级的情况,例如 servlet 类或静态方法。
Another non-deprecated way to get the config is:
This works in situations where there is no injected parent available, such as servlet classes or static methods.
访问grails配置
在控制器中
在服务中:
在 taglib 中:
您可以在视图中调用 taglib 的此方法
在视图中:
You can access grails configuration
In Controller
In services :
In taglib :
You can call this method of taglib in view as
<cd:demoMethod/>
In view :
要从域类访问,请执行以下操作:
To access from domain class do: