如何在Grails2.0中访问Grails配置?
我已经获得了最新的Grails 2.0里程碑,并且看到了如何在Grails2.0中访问Grails配置?,grails,groovy,grails-2.0,Grails,Groovy,Grails 2.0,我已经获得了最新的Grails 2.0里程碑,并且看到了ConfigurationHolder类的弃用警告: org.codehaus.groovy.grails.commons.ConfigurationHolder 弃用消息只是说“改用依赖项注入”,这对我没有多大帮助。我理解依赖注入,但如何用适当的Grails配置连接bean,以便在运行时访问它?我需要从控制器和标签以外的其他位置访问配置(例如引导) 您可以将“grailsApplication”注入到源文件中。下面是一个示例conf/B
ConfigurationHolder
类的弃用警告:
org.codehaus.groovy.grails.commons.ConfigurationHolder
弃用消息只是说“改用依赖项注入”,这对我没有多大帮助。我理解依赖注入,但如何用适当的Grails配置连接bean,以便在运行时访问它?我需要从控制器和标签以外的其他位置访问配置(例如引导
) 您可以将“grailsApplication”注入到源文件中。下面是一个示例conf/Bootstrap.groovy
class BootStrap {
def grailsApplication
def init = { servletContext ->
println grailsApplication.config
}
def destroy = {
}
}
- 如果在支持依赖注入的工件中需要它,只需注入
grailsApplication
class MyController { def grailsApplication def myAction = { def bar = grailsApplication.config.my.property } }
- 如果您需要在bean中使用它,例如,
或src/groovy
,请使用src/java
conf/spring/resources.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' } }
- 在其他任何地方,将配置对象传递给需要它的类或传递所需的特定属性可能都是最简单的
// 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) } }
最近写了几篇关于这个的博客文章
getDomainClass()
来自域类,而另一个提供选项(如果上述解决方案都不合适)。另一种不推荐的获取配置的方法是:
ApplicationContext context = ServletContextHolder.servletContext.
getAttribute(GrailsApplicationAttributes.APPLICATION_CONTEXT)
as ApplicationContext
ConfigObject config = context.getBean(GrailsApplication).config
这适用于没有注入父类的情况,例如servlet类或静态方法
您可以直接从保持器中获取配置,无需注入,这对于实用程序类等很好。您可以访问grails配置
class DemoController {
def grailsApplication
def demoAction = {
def obj = grailsApplication.config.propertyInConfig
}
}
class DemoService {
def grailsApplication
def demoMethod = {
def obj = grailsApplication.config.propertyInConfig
}
}
class DemoTaglib {
def grailsApplication
static namespace = "cd"
def demoMethod = {
def obj = grailsApplication.config.propertyInConfig
out << obj
}
}
class-aglib{
def grailsApplication
静态名称空间=“cd”
def demoMethod={
def obj=grailsApplication.config.propertyInConfig
要从域类访问,请执行以下操作:
import grails.util.Holders
// more code
static void foo() {
def configOption = Holders.config.myProperty
}
Rob,非常有用的答案。谢谢。这可能是最简单的方法,因为有一个直接的1:1映射到不推荐使用的类。当您不想让Spring控制bean的生命周期时,grails.util.Holders
比注入grailsApplication
?@AlexanderSuraphel更可取。例如,一个实用程序使用公共静态方法初始化。如何在外部javascript文件中使用它?
<html>
<head><title>Demo</title></head>
<body>
${grailsApplication.config.propertyInConfig}
</body>
</html>
import grails.util.Holders
// more code
static void foo() {
def configOption = Holders.config.myProperty
}